~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to baz2bzr

  • Committer: abentley
  • Date: 2005-04-29 14:41:03 UTC
  • Revision ID: abentley@lappy-20050429144103-b0a1a78752650702
refactored out progress.py

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
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
 
import sys
21
 
from errors import NoPyBaz
22
2
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."
 
3
    import pybaz
 
4
except ImportError:
 
5
    print "This command requires PyBaz.  Please ensure that it is installed."
 
6
    import sys
26
7
    sys.exit(1)
27
 
 
28
 
import pybaz
 
8
from pybaz.backends.baz import null_cmd
 
9
import tempfile
 
10
import os
29
11
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
 
12
import shutil
 
13
import bzrlib
 
14
import sys
 
15
from progress import *
 
16
bzrlib.trace.create_tracefile([])
 
17
 
 
18
def add_id(files, id=None):
 
19
    """Adds an explicit id to a list of files.
 
20
 
 
21
    :param files: the name of the file to add an id to
 
22
    :type files: list of str
 
23
    :param id: tag one file using the specified id, instead of generating id
 
24
    :type id: str
 
25
    """
 
26
    args = ["add-id"]
 
27
    if id is not None:
 
28
        args.extend(["--id", id])
 
29
    args.extend(files)
 
30
    return null_cmd(args)
 
31
 
 
32
def test_environ():
 
33
    """
 
34
    >>> q = test_environ()
 
35
    >>> os.path.exists(q)
 
36
    True
 
37
    >>> os.path.exists(os.path.join(q, "home", ".arch-params"))
 
38
    True
 
39
    >>> teardown_environ(q)
 
40
    >>> os.path.exists(q)
 
41
    False
 
42
    """
 
43
    tdir = tempfile.mkdtemp(prefix="baz2bzr-")
 
44
    os.environ["HOME"] = os.path.join(tdir, "home")
 
45
    os.mkdir(os.environ["HOME"])
 
46
    arch_dir = os.path.join(tdir, "archive_dir")
 
47
    pybaz.make_archive("test@example.com", arch_dir)
 
48
    work_dir = os.path.join(tdir, "work_dir")
 
49
    os.mkdir(work_dir)
 
50
    os.chdir(work_dir)
 
51
    pybaz.init_tree(work_dir, "test@example.com/test--test--0")
 
52
    lib_dir = os.path.join(tdir, "lib_dir")
 
53
    os.mkdir(lib_dir)
 
54
    pybaz.register_revision_library(lib_dir)
 
55
    pybaz.set_my_id("Test User<test@example.org>")
 
56
    return tdir
 
57
 
 
58
def add_file(path, text, id):
 
59
    """
 
60
    >>> q = test_environ()
 
61
    >>> add_file("path with space", "text", "lalala")
 
62
    >>> tree = pybaz.tree_root(".")
 
63
    >>> inv = list(tree.iter_inventory_ids(source=True, both=True))
 
64
    >>> ("x_lalala", "path with space") in inv
 
65
    True
 
66
    >>> teardown_environ(q)
 
67
    """
 
68
    file(path, "wb").write(text)
 
69
    add_id([path], id)
 
70
 
 
71
 
 
72
def add_dir(path, id):
 
73
    """
 
74
    >>> q = test_environ()
 
75
    >>> add_dir("path with\(sp) space", "lalala")
 
76
    >>> tree = pybaz.tree_root(".")
 
77
    >>> inv = list(tree.iter_inventory_ids(source=True, both=True))
 
78
    >>> ("x_lalala", "path with\(sp) space") in inv
 
79
    True
 
80
    >>> teardown_environ(q)
 
81
    """
 
82
    os.mkdir(path)
 
83
    add_id([path], id)
 
84
 
 
85
def teardown_environ(tdir):
 
86
    os.chdir("/")
 
87
    shutil.rmtree(tdir)
 
88
 
 
89
def timport(tree, summary):
 
90
    msg = tree.log_message()
 
91
    msg["summary"] = summary
 
92
    tree.import_(msg)
 
93
 
 
94
def commit(tree, summary):
 
95
    """
 
96
    >>> q = test_environ()
 
97
    >>> tree = pybaz.tree_root(".")
 
98
    >>> timport(tree, "import")
 
99
    >>> commit(tree, "commit")
 
100
    >>> logs = [str(l.revision) for l in tree.iter_logs()]
 
101
    >>> len(logs)
 
102
    2
 
103
    >>> logs[0]
 
104
    'test@example.com/test--test--0--base-0'
 
105
    >>> logs[1]
 
106
    'test@example.com/test--test--0--patch-1'
 
107
    >>> teardown_environ(q)
 
108
    """
 
109
    msg = tree.log_message()
 
110
    msg["summary"] = summary
 
111
    tree.commit(msg)
 
112
 
 
113
def commit_test_revisions():
 
114
    """
 
115
    >>> q = test_environ()
 
116
    >>> commit_test_revisions()
 
117
    >>> a = pybaz.Archive("test@example.com")
 
118
    >>> revisions = list(a.iter_revisions("test--test--0"))
 
119
    >>> len(revisions)
 
120
    3
 
121
    >>> str(revisions[2])
 
122
    'test@example.com/test--test--0--base-0'
 
123
    >>> str(revisions[1])
 
124
    'test@example.com/test--test--0--patch-1'
 
125
    >>> str(revisions[0])
 
126
    'test@example.com/test--test--0--patch-2'
 
127
    >>> teardown_environ(q)
 
128
    """
 
129
    tree = pybaz.tree_root(".")
 
130
    add_file("mainfile", "void main(void){}", "mainfile by aaron")
 
131
    timport(tree, "Created mainfile")
 
132
    file("mainfile", "wb").write("or something like that")
 
133
    commit(tree, "altered mainfile")
 
134
    add_file("ofile", "this is another file", "ofile by aaron")
 
135
    commit(tree, "altered mainfile")
 
136
 
 
137
def version_ancestry(version):
 
138
    """
 
139
    >>> q = test_environ()
 
140
    >>> commit_test_revisions()
 
141
    >>> version = pybaz.Version("test@example.com/test--test--0")
 
142
    >>> ancestors = version_ancestry(version)
 
143
    >>> str(ancestors[0])
 
144
    'test@example.com/test--test--0--base-0'
 
145
    >>> str(ancestors[1])
 
146
    'test@example.com/test--test--0--patch-1'
 
147
    >>> teardown_environ(q)
 
148
    """
 
149
    revision = version.archive.iter_revisions(version.nonarch).next()
 
150
    ancestors = list(revision.iter_ancestors())
 
151
    ancestors.reverse()
 
152
    ancestors.append(revision)
 
153
    return ancestors
 
154
 
 
155
 
 
156
def import_version(output_dir, version):
 
157
    """
 
158
    >>> q = test_environ()
 
159
    >>> result_path = os.path.join(q, "result")
 
160
    >>> commit_test_revisions()
 
161
    >>> version = pybaz.Version("test@example.com/test--test--0")
 
162
    >>> import_version(result_path, version)
 
163
    Importing 3 revisions
 
164
    ...
 
165
    >>> teardown_environ(q)
 
166
    """
 
167
    tempdir = tempfile.mkdtemp(prefix="baz2bzr")
 
168
    try:
 
169
        for result in iter_import_version(output_dir, version, tempdir):
 
170
            progress_bar(result)
 
171
        clear_progress_bar()
 
172
        print "Import complete."
 
173
    finally:
 
174
        shutil.rmtree(tempdir)
76
175
            
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
 
        
92
 
    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
98
 
    except UserError, e:
99
 
        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
 
 
 
176
def iter_import_version(output_dir, version, tempdir):
 
177
    revdir = None
 
178
    ancestors = version_ancestry(version)
 
179
    for i in range(len(ancestors)):
 
180
        revision = ancestors[i]
 
181
        yield Progress("revisions", i, len(ancestors))
 
182
        if revdir is None:
 
183
            revdir = os.path.join(tempdir, "rd")
 
184
            baz_inv, log = get_revision(revdir, revision)
 
185
            branch = bzrlib.Branch(revdir, init=True)
 
186
        else:
 
187
            old = os.path.join(revdir, ".bzr")
 
188
            new = os.path.join(tempdir, ".bzr")
 
189
            os.rename(old, new)
 
190
            shutil.rmtree(revdir)
 
191
            baz_inv, log = get_revision(revdir, revision)
 
192
            os.rename(new, old)
 
193
            branch = bzrlib.Branch(revdir)
 
194
        branch.set_inventory(baz_inv)
 
195
        branch.commit(log.summary)
 
196
    yield Progress("revisions", len(ancestors), len(ancestors))
 
197
    unlink_unversioned(branch, revdir)
 
198
    os.rename(revdir, output_dir)   
 
199
 
 
200
def unlink_unversioned(branch, revdir):
 
201
    for unversioned in branch.working_tree().extras():
 
202
        path = os.path.join(revdir, unversioned)
 
203
        if os.path.isdir(path):
 
204
            shutil.rmtree(path)
 
205
        else:
 
206
            os.unlink(path)
 
207
 
 
208
def get_revision(revdir, revision):
 
209
    revision.get(revdir)
 
210
    tree = pybaz.tree_root(revdir)
 
211
    log = tree.iter_logs(reverse=True).next()
 
212
    return bzr_inventory_data(tree), log 
 
213
 
 
214
def bzr_inventory_data(tree):
 
215
    inv_iter = tree.iter_inventory_ids(source=True, both=True)
 
216
    inv_map = {}
 
217
    for file_id, path in inv_iter:
 
218
        inv_map[path] = file_id 
 
219
 
 
220
    bzr_inv = []
 
221
    for path, file_id in inv_map.iteritems():
 
222
        kind = bzrlib.osutils.file_kind(os.path.join(tree, path))
 
223
        assert kind in ("file", "directory")
 
224
        parent_dir = os.path.dirname(path)
 
225
        if parent_dir != "":
 
226
            parent_id = inv_map[parent_dir]
 
227
        else:
 
228
            parent_id = bzrlib.inventory.ROOT_ID
 
229
        bzr_inv.append((path, file_id, parent_id, kind))
 
230
    bzr_inv.sort()
 
231
    return bzr_inv
 
232
 
 
233
if len(sys.argv) == 2 and sys.argv[1] == "test":
 
234
    print "Running tests"
 
235
    import doctest
 
236
    doctest.testmod()
 
237
elif len(sys.argv) == 3:
 
238
    import_version(sys.argv[2], pybaz.Version(sys.argv[1]))
 
239
else:
 
240
    print "usage: %s VERSION OUTDIR" % os.path.basename(sys.argv[0])