~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to baz2bzr

  • Committer: abentley
  • Date: 2005-05-10 05:20:50 UTC
  • Revision ID: abentley@lappy-20050510052050-d82d0e61ac608fc2
removed now un-necessary tracefile use

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
 
 
3
# Copyright (C) 2005 Aaron Bentley
 
4
# <aaron.bentley@utoronto.ca>
 
5
#
 
6
#    This program is free software; you can redistribute it and/or modify
 
7
#    it under the terms of the GNU General Public License as published by
 
8
#    the Free Software Foundation; either version 2 of the License, or
 
9
#    (at your option) any later version.
 
10
#
 
11
#    This program is distributed in the hope that it will be useful,
 
12
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
#    GNU General Public License for more details.
 
15
#
 
16
#    You should have received a copy of the GNU General Public License
 
17
#    along with this program; if not, write to the Free Software
 
18
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
19
 
 
20
try:
 
21
    import pybaz
 
22
except ImportError:
 
23
    print "This command requires PyBaz.  Please ensure that it is installed."
 
24
    import sys
 
25
    sys.exit(1)
 
26
from pybaz.backends.baz import null_cmd
 
27
import tempfile
 
28
import os
 
29
import os.path
 
30
import shutil
 
31
import bzrlib
 
32
import sys
 
33
from progress import *
 
34
 
 
35
def add_id(files, id=None):
 
36
    """Adds an explicit id to a list of files.
 
37
 
 
38
    :param files: the name of the file to add an id to
 
39
    :type files: list of str
 
40
    :param id: tag one file using the specified id, instead of generating id
 
41
    :type id: str
 
42
    """
 
43
    args = ["add-id"]
 
44
    if id is not None:
 
45
        args.extend(["--id", id])
 
46
    args.extend(files)
 
47
    return null_cmd(args)
 
48
 
 
49
def test_environ():
 
50
    """
 
51
    >>> q = test_environ()
 
52
    >>> os.path.exists(q)
 
53
    True
 
54
    >>> os.path.exists(os.path.join(q, "home", ".arch-params"))
 
55
    True
 
56
    >>> teardown_environ(q)
 
57
    >>> os.path.exists(q)
 
58
    False
 
59
    """
 
60
    tdir = tempfile.mkdtemp(prefix="baz2bzr-")
 
61
    os.environ["HOME"] = os.path.join(tdir, "home")
 
62
    os.mkdir(os.environ["HOME"])
 
63
    arch_dir = os.path.join(tdir, "archive_dir")
 
64
    pybaz.make_archive("test@example.com", arch_dir)
 
65
    work_dir = os.path.join(tdir, "work_dir")
 
66
    os.mkdir(work_dir)
 
67
    os.chdir(work_dir)
 
68
    pybaz.init_tree(work_dir, "test@example.com/test--test--0")
 
69
    lib_dir = os.path.join(tdir, "lib_dir")
 
70
    os.mkdir(lib_dir)
 
71
    pybaz.register_revision_library(lib_dir)
 
72
    pybaz.set_my_id("Test User<test@example.org>")
 
73
    return tdir
 
74
 
 
75
def add_file(path, text, id):
 
76
    """
 
77
    >>> q = test_environ()
 
78
    >>> add_file("path with space", "text", "lalala")
 
79
    >>> tree = pybaz.tree_root(".")
 
80
    >>> inv = list(tree.iter_inventory_ids(source=True, both=True))
 
81
    >>> ("x_lalala", "path with space") in inv
 
82
    True
 
83
    >>> teardown_environ(q)
 
84
    """
 
85
    file(path, "wb").write(text)
 
86
    add_id([path], id)
 
87
 
 
88
 
 
89
def add_dir(path, id):
 
90
    """
 
91
    >>> q = test_environ()
 
92
    >>> add_dir("path with\(sp) space", "lalala")
 
93
    >>> tree = pybaz.tree_root(".")
 
94
    >>> inv = list(tree.iter_inventory_ids(source=True, both=True))
 
95
    >>> ("x_lalala", "path with\(sp) space") in inv
 
96
    True
 
97
    >>> teardown_environ(q)
 
98
    """
 
99
    os.mkdir(path)
 
100
    add_id([path], id)
 
101
 
 
102
def teardown_environ(tdir):
 
103
    os.chdir("/")
 
104
    shutil.rmtree(tdir)
 
105
 
 
106
def timport(tree, summary):
 
107
    msg = tree.log_message()
 
108
    msg["summary"] = summary
 
109
    tree.import_(msg)
 
110
 
 
111
def commit(tree, summary):
 
112
    """
 
113
    >>> q = test_environ()
 
114
    >>> tree = pybaz.tree_root(".")
 
115
    >>> timport(tree, "import")
 
116
    >>> commit(tree, "commit")
 
117
    >>> logs = [str(l.revision) for l in tree.iter_logs()]
 
118
    >>> len(logs)
 
119
    2
 
120
    >>> logs[0]
 
121
    'test@example.com/test--test--0--base-0'
 
122
    >>> logs[1]
 
123
    'test@example.com/test--test--0--patch-1'
 
124
    >>> teardown_environ(q)
 
125
    """
 
126
    msg = tree.log_message()
 
127
    msg["summary"] = summary
 
128
    tree.commit(msg)
 
129
 
 
130
def commit_test_revisions():
 
131
    """
 
132
    >>> q = test_environ()
 
133
    >>> commit_test_revisions()
 
134
    >>> a = pybaz.Archive("test@example.com")
 
135
    >>> revisions = list(a.iter_revisions("test--test--0"))
 
136
    >>> len(revisions)
 
137
    3
 
138
    >>> str(revisions[2])
 
139
    'test@example.com/test--test--0--base-0'
 
140
    >>> str(revisions[1])
 
141
    'test@example.com/test--test--0--patch-1'
 
142
    >>> str(revisions[0])
 
143
    'test@example.com/test--test--0--patch-2'
 
144
    >>> teardown_environ(q)
 
145
    """
 
146
    tree = pybaz.tree_root(".")
 
147
    add_file("mainfile", "void main(void){}", "mainfile by aaron")
 
148
    timport(tree, "Created mainfile")
 
149
    file("mainfile", "wb").write("or something like that")
 
150
    commit(tree, "altered mainfile")
 
151
    add_file("ofile", "this is another file", "ofile by aaron")
 
152
    commit(tree, "altered mainfile")
 
153
 
 
154
def version_ancestry(version):
 
155
    """
 
156
    >>> q = test_environ()
 
157
    >>> commit_test_revisions()
 
158
    >>> version = pybaz.Version("test@example.com/test--test--0")
 
159
    >>> ancestors = version_ancestry(version)
 
160
    >>> str(ancestors[0])
 
161
    'test@example.com/test--test--0--base-0'
 
162
    >>> str(ancestors[1])
 
163
    'test@example.com/test--test--0--patch-1'
 
164
    >>> teardown_environ(q)
 
165
    """
 
166
    revision = version.archive.iter_revisions(version.nonarch).next()
 
167
    ancestors = list(revision.iter_ancestors())
 
168
    ancestors.reverse()
 
169
    ancestors.append(revision)
 
170
    return ancestors
 
171
 
 
172
 
 
173
def import_version(output_dir, version):
 
174
    """
 
175
    >>> q = test_environ()
 
176
    >>> result_path = os.path.join(q, "result")
 
177
    >>> commit_test_revisions()
 
178
    >>> version = pybaz.Version("test@example.com/test--test--0")
 
179
    >>> import_version(result_path, version)
 
180
    Importing 3 revisions
 
181
    ...
 
182
    >>> teardown_environ(q)
 
183
    """
 
184
    tempdir = tempfile.mkdtemp(prefix="baz2bzr")
 
185
    try:
 
186
        for result in iter_import_version(output_dir, version, tempdir):
 
187
            progress_bar(result)
 
188
        clear_progress_bar()
 
189
        print "Import complete."
 
190
    finally:
 
191
        shutil.rmtree(tempdir)
 
192
            
 
193
class UserError(Exception):
 
194
    def __init__(self, message):
 
195
        """Exception to throw when a user makes an impossible request
 
196
        :param message: The message to emit when printing this exception
 
197
        :type message: string
 
198
        """
 
199
        Exception.__init__(self, message)
 
200
 
 
201
def iter_import_version(output_dir, version, tempdir):
 
202
    revdir = None
 
203
    ancestors = version_ancestry(version)
 
204
    for i in range(len(ancestors)):
 
205
        revision = ancestors[i]
 
206
        yield Progress("revisions", i, len(ancestors))
 
207
        if revdir is None:
 
208
            revdir = os.path.join(tempdir, "rd")
 
209
            baz_inv, log = get_revision(revdir, revision)
 
210
            branch = bzrlib.Branch(revdir, init=True)
 
211
        else:
 
212
            old = os.path.join(revdir, ".bzr")
 
213
            new = os.path.join(tempdir, ".bzr")
 
214
            os.rename(old, new)
 
215
            baz_inv, log = apply_revision(revdir, revision)
 
216
            os.rename(new, old)
 
217
            branch = bzrlib.Branch(revdir)
 
218
        branch.set_inventory(baz_inv)
 
219
        branch.commit(log.summary)
 
220
    yield Progress("revisions", len(ancestors), len(ancestors))
 
221
    unlink_unversioned(branch, revdir)
 
222
    os.rename(revdir, output_dir)   
 
223
 
 
224
def unlink_unversioned(branch, revdir):
 
225
    for unversioned in branch.working_tree().extras():
 
226
        path = os.path.join(revdir, unversioned)
 
227
        if os.path.isdir(path):
 
228
            shutil.rmtree(path)
 
229
        else:
 
230
            os.unlink(path)
 
231
 
 
232
def get_revision(revdir, revision):
 
233
    revision.get(revdir)
 
234
    tree = pybaz.tree_root(revdir)
 
235
    log = tree.iter_logs(reverse=True).next()
 
236
    return bzr_inventory_data(tree), log 
 
237
 
 
238
def apply_revision(revdir, revision):
 
239
    tree = pybaz.tree_root(revdir)
 
240
    revision.apply(tree)
 
241
    log = tree.iter_logs(reverse=True).next()
 
242
    return bzr_inventory_data(tree), log 
 
243
 
 
244
 
 
245
def bzr_inventory_data(tree):
 
246
    inv_iter = tree.iter_inventory_ids(source=True, both=True)
 
247
    inv_map = {}
 
248
    for file_id, path in inv_iter:
 
249
        inv_map[path] = file_id 
 
250
 
 
251
    bzr_inv = []
 
252
    for path, file_id in inv_map.iteritems():
 
253
        kind = bzrlib.osutils.file_kind(os.path.join(tree, path))
 
254
        assert kind in ("file", "directory")
 
255
        parent_dir = os.path.dirname(path)
 
256
        if parent_dir != "":
 
257
            parent_id = inv_map[parent_dir]
 
258
        else:
 
259
            parent_id = bzrlib.inventory.ROOT_ID
 
260
        bzr_inv.append((path, file_id, parent_id, kind))
 
261
    bzr_inv.sort()
 
262
    return bzr_inv
 
263
 
 
264
if len(sys.argv) == 2 and sys.argv[1] == "test":
 
265
    print "Running tests"
 
266
    import doctest
 
267
    doctest.testmod()
 
268
elif len(sys.argv) == 3:
 
269
    try:
 
270
        output_dir = sys.argv[2]
 
271
        if os.path.exists(output_dir):
 
272
            raise UserError("Directory \"%s\" already exists" % output_dir)
 
273
        import_version(output_dir, pybaz.Version(sys.argv[1]))
 
274
    except UserError, e:
 
275
        print e
 
276
else:
 
277
    print "usage: %s VERSION OUTDIR" % os.path.basename(sys.argv[0])