~abentley/bzrtools/bzrtools.dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#!/usr/bin/env python

# Copyright (C) 2005 Aaron Bentley
# <aaron.bentley@utoronto.ca>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

try:
    import pybaz
except ImportError:
    print "This command requires PyBaz.  Please ensure that it is installed."
    import sys
    sys.exit(1)
from pybaz.backends.baz import null_cmd
import tempfile
import os
import os.path
import shutil
import bzrlib
import sys
import email.Utils
from progress import *

def add_id(files, id=None):
    """Adds an explicit id to a list of files.

    :param files: the name of the file to add an id to
    :type files: list of str
    :param id: tag one file using the specified id, instead of generating id
    :type id: str
    """
    args = ["add-id"]
    if id is not None:
        args.extend(["--id", id])
    args.extend(files)
    return null_cmd(args)

def test_environ():
    """
    >>> q = test_environ()
    >>> os.path.exists(q)
    True
    >>> os.path.exists(os.path.join(q, "home", ".arch-params"))
    True
    >>> teardown_environ(q)
    >>> os.path.exists(q)
    False
    """
    tdir = tempfile.mkdtemp(prefix="baz2bzr-")
    os.environ["HOME"] = os.path.join(tdir, "home")
    os.mkdir(os.environ["HOME"])
    arch_dir = os.path.join(tdir, "archive_dir")
    pybaz.make_archive("test@example.com", arch_dir)
    work_dir = os.path.join(tdir, "work_dir")
    os.mkdir(work_dir)
    os.chdir(work_dir)
    pybaz.init_tree(work_dir, "test@example.com/test--test--0")
    lib_dir = os.path.join(tdir, "lib_dir")
    os.mkdir(lib_dir)
    pybaz.register_revision_library(lib_dir)
    pybaz.set_my_id("Test User<test@example.org>")
    return tdir

def add_file(path, text, id):
    """
    >>> q = test_environ()
    >>> add_file("path with space", "text", "lalala")
    >>> tree = pybaz.tree_root(".")
    >>> inv = list(tree.iter_inventory_ids(source=True, both=True))
    >>> ("x_lalala", "path with space") in inv
    True
    >>> teardown_environ(q)
    """
    file(path, "wb").write(text)
    add_id([path], id)


def add_dir(path, id):
    """
    >>> q = test_environ()
    >>> add_dir("path with\(sp) space", "lalala")
    >>> tree = pybaz.tree_root(".")
    >>> inv = list(tree.iter_inventory_ids(source=True, both=True))
    >>> ("x_lalala", "path with\(sp) space") in inv
    True
    >>> teardown_environ(q)
    """
    os.mkdir(path)
    add_id([path], id)

def teardown_environ(tdir):
    os.chdir("/")
    shutil.rmtree(tdir)

def timport(tree, summary):
    msg = tree.log_message()
    msg["summary"] = summary
    tree.import_(msg)

def commit(tree, summary):
    """
    >>> q = test_environ()
    >>> tree = pybaz.tree_root(".")
    >>> timport(tree, "import")
    >>> commit(tree, "commit")
    >>> logs = [str(l.revision) for l in tree.iter_logs()]
    >>> len(logs)
    2
    >>> logs[0]
    'test@example.com/test--test--0--base-0'
    >>> logs[1]
    'test@example.com/test--test--0--patch-1'
    >>> teardown_environ(q)
    """
    msg = tree.log_message()
    msg["summary"] = summary
    tree.commit(msg)

def commit_test_revisions():
    """
    >>> q = test_environ()
    >>> commit_test_revisions()
    >>> a = pybaz.Archive("test@example.com")
    >>> revisions = list(a.iter_revisions("test--test--0"))
    >>> len(revisions)
    3
    >>> str(revisions[2])
    'test@example.com/test--test--0--base-0'
    >>> str(revisions[1])
    'test@example.com/test--test--0--patch-1'
    >>> str(revisions[0])
    'test@example.com/test--test--0--patch-2'
    >>> teardown_environ(q)
    """
    tree = pybaz.tree_root(".")
    add_file("mainfile", "void main(void){}", "mainfile by aaron")
    timport(tree, "Created mainfile")
    file("mainfile", "wb").write("or something like that")
    commit(tree, "altered mainfile")
    add_file("ofile", "this is another file", "ofile by aaron")
    commit(tree, "altered mainfile")

def version_ancestry(version):
    """
    >>> q = test_environ()
    >>> commit_test_revisions()
    >>> version = pybaz.Version("test@example.com/test--test--0")
    >>> ancestors = version_ancestry(version)
    >>> str(ancestors[0])
    'test@example.com/test--test--0--base-0'
    >>> str(ancestors[1])
    'test@example.com/test--test--0--patch-1'
    >>> teardown_environ(q)
    """
    revision = version.iter_revisions(reverse=True).next()
    ancestors = list(revision.iter_ancestors(metoo=True))
    ancestors.reverse()
    return ancestors


def import_version(output_dir, version, fancy=True):
    """
    >>> q = test_environ()
    >>> result_path = os.path.join(q, "result")
    >>> commit_test_revisions()
    >>> version = pybaz.Version("test@example.com/test--test--0")
    >>> import_version(result_path, version, fancy=False)
    not fancy
    ....
    Import complete.
    >>> teardown_environ(q)
    """
    tempdir = tempfile.mkdtemp(prefix="baz2bzr")
    try:
        if not fancy:
            print "not fancy"
        for result in iter_import_version(output_dir, version, tempdir):
            if fancy:
                progress_bar(result)
            else:
                sys.stdout.write('.')
    finally:
        if fancy:
            clear_progress_bar()
        else:
            sys.stdout.write('\n')
        shutil.rmtree(tempdir)
    print "Import complete."
            
class UserError(Exception):
    def __init__(self, message):
        """Exception to throw when a user makes an impossible request
        :param message: The message to emit when printing this exception
        :type message: string
        """
        Exception.__init__(self, message)

def iter_import_version(output_dir, version, tempdir):
    revdir = None
    ancestors = version_ancestry(version)
    for i in range(len(ancestors)):
        revision = ancestors[i]
        yield Progress("revisions", i, len(ancestors))
        if revdir is None:
            revdir = os.path.join(tempdir, "rd")
            baz_inv, log = get_revision(revdir, revision)
            branch = bzrlib.Branch(revdir, init=True)
        else:
            old = os.path.join(revdir, ".bzr")
            new = os.path.join(tempdir, ".bzr")
            os.rename(old, new)
            baz_inv, log = apply_revision(revdir, revision)
            os.rename(new, old)
            branch = bzrlib.Branch(revdir)
        branch.set_inventory(baz_inv)
        timestamp = email.Utils.mktime_tz(log.date + (0,))
            
        branch.commit(log.summary, verbose=False,
                      committer=log.creator, timestamp=timestamp, timezone=0)
    yield Progress("revisions", len(ancestors), len(ancestors))
    unlink_unversioned(branch, revdir)
    os.rename(revdir, output_dir)   

def unlink_unversioned(branch, revdir):
    for unversioned in branch.working_tree().extras():
        path = os.path.join(revdir, unversioned)
        if os.path.isdir(path):
            shutil.rmtree(path)
        else:
            os.unlink(path)

def get_log(tree, revision):
    log = tree.iter_logs(version=revision.version, reverse=True).next()
    assert log.revision == revision
    return log

def get_revision(revdir, revision):
    revision.get(revdir)
    tree = pybaz.tree_root(revdir)
    log = get_log(tree, revision)
    try:
        return bzr_inventory_data(tree), log 
    except BadFileKind, e:
        raise UserError("Cannot convert %s because %s is a %s" % (revision,e.path, e.kind) )


def apply_revision(revdir, revision):
    tree = pybaz.tree_root(revdir)
    revision.apply(tree)
    log = get_log(tree, revision)
    try:
        return bzr_inventory_data(tree), log
    except BadFileKind, e:
        raise UserError("Cannot convert %s because %s is a %s" % (revision,e.path, e.kind) )




class BadFileKind(Exception):
    """The file kind is not permitted in bzr inventories"""
    def __init__(self, tree_root, path, kind):
        self.tree_root = tree_root
        self.path = path
        self.kind = kind
        Exception.__init__(self, "File %s is of forbidden type %s" %
                           (os.path.join(tree_root, path), kind))

def bzr_inventory_data(tree):
    inv_iter = tree.iter_inventory_ids(source=True, both=True)
    inv_map = {}
    for file_id, path in inv_iter:
        inv_map[path] = file_id 

    bzr_inv = []
    for path, file_id in inv_map.iteritems():
        full_path = os.path.join(tree, path)
        kind = bzrlib.osutils.file_kind(full_path)
        if kind not in ("file", "directory"):
            raise BadFileKind(tree, path, kind)
        parent_dir = os.path.dirname(path)
        if parent_dir != "":
            parent_id = inv_map[parent_dir]
        else:
            parent_id = bzrlib.inventory.ROOT_ID
        bzr_inv.append((path, file_id, parent_id, kind))
    bzr_inv.sort()
    return bzr_inv

if len(sys.argv) == 2 and sys.argv[1] == "test":
    print "Running tests"
    import doctest
    doctest.testmod()
elif len(sys.argv) == 3:
    try:
        output_dir = sys.argv[2]
        if os.path.exists(output_dir):
            raise UserError("Directory \"%s\" already exists" % output_dir)
        import_version(output_dir, pybaz.Version(sys.argv[1]))
    except UserError, e:
        print e
else:
    print "usage: %s VERSION OUTDIR" % os.path.basename(sys.argv[0])