~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to baz2bzr

  • Committer: abentley
  • Date: 2005-04-30 07:31:13 UTC
  • Revision ID: abentley@lappy-20050430073113-bb4f4a80c01a6cf5
GPLed the project, ignored files

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
#    along with this program; if not, write to the Free Software
18
18
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
19
 
20
 
import sys
21
 
from errors import NoPyBaz
22
20
try:
23
 
    from baz_import import import_version, UserError
24
 
except NoPyBaz:
25
 
    print >> sys.stderr, "This command requires PyBaz.  Please ensure that it is installed."
 
21
    import pybaz
 
22
except ImportError:
 
23
    print "This command requires PyBaz.  Please ensure that it is installed."
 
24
    import sys
26
25
    sys.exit(1)
27
 
 
28
 
import pybaz
 
26
from pybaz.backends.baz import null_cmd
 
27
import tempfile
 
28
import os
29
29
import os.path
30
 
 
31
 
def main(args):
32
 
    """Just the main() function for this script.
33
 
 
34
 
    By separating it into a function, this can be called as a child from some other
35
 
    script.
36
 
 
37
 
    :param args: The arguments to this script. Essentially sys.argv[1:]
38
 
    """
39
 
    import optparse
40
 
    parser = optparse.OptionParser(usage='%prog [options] [VERSION] OUTDIR'
41
 
        '\n  VERSION is the arch version to import.'
42
 
        '\n  OUTDIR can be an existing directory to be updated'
43
 
        '\n         or a new directory which will be created from scratch.')
44
 
    parser.add_option('--verbose', action='store_true'
45
 
        , help='Get chatty')
46
 
 
47
 
    parser.add_option('--skip-symlinks', action="store_true", 
48
 
                      dest="skip_symlinks", 
49
 
                      help="Ignore any symlinks present in the Arch tree.")
50
 
 
51
 
    g = optparse.OptionGroup(parser, 'Test options', 'Options useful while testing process.')
52
 
    g.add_option('--test', action='store_true'
53
 
        , help='Run the self-tests and exit.')
54
 
    g.add_option('--dry-run', action='store_true'
55
 
        , help='Do the update, but don\'t copy the result to OUTDIR')
56
 
    g.add_option('--max-count', type='int', metavar='COUNT', default=None
57
 
        , help='At most, add COUNT patches.')
58
 
    g.add_option('--safe', action='store_false', dest='fast')
59
 
    g.add_option('--fast', action='store_true', default=False
60
 
        , help='By default the .bzr control directory will be copied, so that an error'
61
 
        ' does not modify the original. --fast allows the directory to be renamed instead.')
62
 
    parser.add_option_group(g)
63
 
 
64
 
    (opts, args) = parser.parse_args(args)
65
 
 
66
 
    if opts.test:
67
 
        print "Running tests"
68
 
        import doctest, baz_import
69
 
        nfail, ntests = doctest.testmod(baz_import, verbose=opts.verbose)
70
 
        if nfail > 0:
71
 
            return 1
72
 
        else:
73
 
            return 0
74
 
    if len(args) == 2:
75
 
        version,output_dir = args
 
30
import shutil
 
31
import bzrlib
 
32
import sys
 
33
from progress import *
 
34
bzrlib.trace.create_tracefile([])
 
35
 
 
36
def add_id(files, id=None):
 
37
    """Adds an explicit id to a list of files.
 
38
 
 
39
    :param files: the name of the file to add an id to
 
40
    :type files: list of str
 
41
    :param id: tag one file using the specified id, instead of generating id
 
42
    :type id: str
 
43
    """
 
44
    args = ["add-id"]
 
45
    if id is not None:
 
46
        args.extend(["--id", id])
 
47
    args.extend(files)
 
48
    return null_cmd(args)
 
49
 
 
50
def test_environ():
 
51
    """
 
52
    >>> q = test_environ()
 
53
    >>> os.path.exists(q)
 
54
    True
 
55
    >>> os.path.exists(os.path.join(q, "home", ".arch-params"))
 
56
    True
 
57
    >>> teardown_environ(q)
 
58
    >>> os.path.exists(q)
 
59
    False
 
60
    """
 
61
    tdir = tempfile.mkdtemp(prefix="baz2bzr-")
 
62
    os.environ["HOME"] = os.path.join(tdir, "home")
 
63
    os.mkdir(os.environ["HOME"])
 
64
    arch_dir = os.path.join(tdir, "archive_dir")
 
65
    pybaz.make_archive("test@example.com", arch_dir)
 
66
    work_dir = os.path.join(tdir, "work_dir")
 
67
    os.mkdir(work_dir)
 
68
    os.chdir(work_dir)
 
69
    pybaz.init_tree(work_dir, "test@example.com/test--test--0")
 
70
    lib_dir = os.path.join(tdir, "lib_dir")
 
71
    os.mkdir(lib_dir)
 
72
    pybaz.register_revision_library(lib_dir)
 
73
    pybaz.set_my_id("Test User<test@example.org>")
 
74
    return tdir
 
75
 
 
76
def add_file(path, text, id):
 
77
    """
 
78
    >>> q = test_environ()
 
79
    >>> add_file("path with space", "text", "lalala")
 
80
    >>> tree = pybaz.tree_root(".")
 
81
    >>> inv = list(tree.iter_inventory_ids(source=True, both=True))
 
82
    >>> ("x_lalala", "path with space") in inv
 
83
    True
 
84
    >>> teardown_environ(q)
 
85
    """
 
86
    file(path, "wb").write(text)
 
87
    add_id([path], id)
 
88
 
 
89
 
 
90
def add_dir(path, id):
 
91
    """
 
92
    >>> q = test_environ()
 
93
    >>> add_dir("path with\(sp) space", "lalala")
 
94
    >>> tree = pybaz.tree_root(".")
 
95
    >>> inv = list(tree.iter_inventory_ids(source=True, both=True))
 
96
    >>> ("x_lalala", "path with\(sp) space") in inv
 
97
    True
 
98
    >>> teardown_environ(q)
 
99
    """
 
100
    os.mkdir(path)
 
101
    add_id([path], id)
 
102
 
 
103
def teardown_environ(tdir):
 
104
    os.chdir("/")
 
105
    shutil.rmtree(tdir)
 
106
 
 
107
def timport(tree, summary):
 
108
    msg = tree.log_message()
 
109
    msg["summary"] = summary
 
110
    tree.import_(msg)
 
111
 
 
112
def commit(tree, summary):
 
113
    """
 
114
    >>> q = test_environ()
 
115
    >>> tree = pybaz.tree_root(".")
 
116
    >>> timport(tree, "import")
 
117
    >>> commit(tree, "commit")
 
118
    >>> logs = [str(l.revision) for l in tree.iter_logs()]
 
119
    >>> len(logs)
 
120
    2
 
121
    >>> logs[0]
 
122
    'test@example.com/test--test--0--base-0'
 
123
    >>> logs[1]
 
124
    'test@example.com/test--test--0--patch-1'
 
125
    >>> teardown_environ(q)
 
126
    """
 
127
    msg = tree.log_message()
 
128
    msg["summary"] = summary
 
129
    tree.commit(msg)
 
130
 
 
131
def commit_test_revisions():
 
132
    """
 
133
    >>> q = test_environ()
 
134
    >>> commit_test_revisions()
 
135
    >>> a = pybaz.Archive("test@example.com")
 
136
    >>> revisions = list(a.iter_revisions("test--test--0"))
 
137
    >>> len(revisions)
 
138
    3
 
139
    >>> str(revisions[2])
 
140
    'test@example.com/test--test--0--base-0'
 
141
    >>> str(revisions[1])
 
142
    'test@example.com/test--test--0--patch-1'
 
143
    >>> str(revisions[0])
 
144
    'test@example.com/test--test--0--patch-2'
 
145
    >>> teardown_environ(q)
 
146
    """
 
147
    tree = pybaz.tree_root(".")
 
148
    add_file("mainfile", "void main(void){}", "mainfile by aaron")
 
149
    timport(tree, "Created mainfile")
 
150
    file("mainfile", "wb").write("or something like that")
 
151
    commit(tree, "altered mainfile")
 
152
    add_file("ofile", "this is another file", "ofile by aaron")
 
153
    commit(tree, "altered mainfile")
 
154
 
 
155
def version_ancestry(version):
 
156
    """
 
157
    >>> q = test_environ()
 
158
    >>> commit_test_revisions()
 
159
    >>> version = pybaz.Version("test@example.com/test--test--0")
 
160
    >>> ancestors = version_ancestry(version)
 
161
    >>> str(ancestors[0])
 
162
    'test@example.com/test--test--0--base-0'
 
163
    >>> str(ancestors[1])
 
164
    'test@example.com/test--test--0--patch-1'
 
165
    >>> teardown_environ(q)
 
166
    """
 
167
    revision = version.archive.iter_revisions(version.nonarch).next()
 
168
    ancestors = list(revision.iter_ancestors())
 
169
    ancestors.reverse()
 
170
    ancestors.append(revision)
 
171
    return ancestors
 
172
 
 
173
 
 
174
def import_version(output_dir, version):
 
175
    """
 
176
    >>> q = test_environ()
 
177
    >>> result_path = os.path.join(q, "result")
 
178
    >>> commit_test_revisions()
 
179
    >>> version = pybaz.Version("test@example.com/test--test--0")
 
180
    >>> import_version(result_path, version)
 
181
    Importing 3 revisions
 
182
    ...
 
183
    >>> teardown_environ(q)
 
184
    """
 
185
    tempdir = tempfile.mkdtemp(prefix="baz2bzr")
 
186
    try:
 
187
        for result in iter_import_version(output_dir, version, tempdir):
 
188
            progress_bar(result)
 
189
        clear_progress_bar()
 
190
        print "Import complete."
 
191
    finally:
 
192
        shutil.rmtree(tempdir)
76
193
            
77
 
    elif len(args) == 1:
78
 
        output_dir = args[0]
79
 
        version = None
80
 
    else:
81
 
        print 'Invalid number of arguments, try --help for more info'
82
 
        return 1
83
 
 
84
 
    output_dir = os.path.realpath(output_dir)
85
 
    if version is not None:
86
 
        try:
87
 
            version = pybaz.Version(version)
88
 
        except pybaz.errors.NamespaceError:
89
 
            print "%s is not a valid Arch branch." % version
90
 
            return 1
91
 
        
 
194
class UserError(Exception):
 
195
    def __init__(self, message):
 
196
        """Exception to throw when a user makes an impossible request
 
197
        :param message: The message to emit when printing this exception
 
198
        :type message: string
 
199
        """
 
200
        Exception.__init__(self, message)
 
201
 
 
202
def iter_import_version(output_dir, version, tempdir):
 
203
    revdir = None
 
204
    ancestors = version_ancestry(version)
 
205
    for i in range(len(ancestors)):
 
206
        revision = ancestors[i]
 
207
        yield Progress("revisions", i, len(ancestors))
 
208
        if revdir is None:
 
209
            revdir = os.path.join(tempdir, "rd")
 
210
            baz_inv, log = get_revision(revdir, revision)
 
211
            branch = bzrlib.Branch(revdir, init=True)
 
212
        else:
 
213
            old = os.path.join(revdir, ".bzr")
 
214
            new = os.path.join(tempdir, ".bzr")
 
215
            os.rename(old, new)
 
216
            baz_inv, log = apply_revision(revdir, revision)
 
217
            os.rename(new, old)
 
218
            branch = bzrlib.Branch(revdir)
 
219
        branch.set_inventory(baz_inv)
 
220
        branch.commit(log.summary)
 
221
    yield Progress("revisions", len(ancestors), len(ancestors))
 
222
    unlink_unversioned(branch, revdir)
 
223
    os.rename(revdir, output_dir)   
 
224
 
 
225
def unlink_unversioned(branch, revdir):
 
226
    for unversioned in branch.working_tree().extras():
 
227
        path = os.path.join(revdir, unversioned)
 
228
        if os.path.isdir(path):
 
229
            shutil.rmtree(path)
 
230
        else:
 
231
            os.unlink(path)
 
232
 
 
233
def get_revision(revdir, revision):
 
234
    revision.get(revdir)
 
235
    tree = pybaz.tree_root(revdir)
 
236
    log = tree.iter_logs(reverse=True).next()
 
237
    return bzr_inventory_data(tree), log 
 
238
 
 
239
def apply_revision(revdir, revision):
 
240
    tree = pybaz.tree_root(revdir)
 
241
    revision.apply(tree)
 
242
    log = tree.iter_logs(reverse=True).next()
 
243
    return bzr_inventory_data(tree), log 
 
244
 
 
245
 
 
246
def bzr_inventory_data(tree):
 
247
    inv_iter = tree.iter_inventory_ids(source=True, both=True)
 
248
    inv_map = {}
 
249
    for file_id, path in inv_iter:
 
250
        inv_map[path] = file_id 
 
251
 
 
252
    bzr_inv = []
 
253
    for path, file_id in inv_map.iteritems():
 
254
        kind = bzrlib.osutils.file_kind(os.path.join(tree, path))
 
255
        assert kind in ("file", "directory")
 
256
        parent_dir = os.path.dirname(path)
 
257
        if parent_dir != "":
 
258
            parent_id = inv_map[parent_dir]
 
259
        else:
 
260
            parent_id = bzrlib.inventory.ROOT_ID
 
261
        bzr_inv.append((path, file_id, parent_id, kind))
 
262
    bzr_inv.sort()
 
263
    return bzr_inv
 
264
 
 
265
if len(sys.argv) == 2 and sys.argv[1] == "test":
 
266
    print "Running tests"
 
267
    import doctest
 
268
    doctest.testmod()
 
269
elif len(sys.argv) == 3:
92
270
    try:
93
 
        import_version(output_dir, version,
94
 
            verbose=opts.verbose, fast=opts.fast,
95
 
            dry_run=opts.dry_run, max_count=opts.max_count,
96
 
            skip_symlinks=opts.skip_symlinks)
97
 
        return 0
 
271
        output_dir = sys.argv[2]
 
272
        if os.path.exists(output_dir):
 
273
            raise UserError("Directory \"%s\" already exists" % output_dir)
 
274
        import_version(output_dir, pybaz.Version(sys.argv[1]))
98
275
    except UserError, e:
99
276
        print e
100
 
        return 1
101
 
    except KeyboardInterrupt:
102
 
        print "Aborted."
103
 
        return 1
104
 
 
105
 
        
106
 
 
107
 
if __name__ == '__main__':
108
 
    sys.exit(main(sys.argv[1:]))
109
 
 
 
277
else:
 
278
    print "usage: %s VERSION OUTDIR" % os.path.basename(sys.argv[0])