~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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
#!/usr/bin/python
"""\
Various useful plugins for working with bzr.
"""
import bzrlib.commands
import push
from errors import CommandError
from patchsource import BzrPatchSource
from shelf import Shelf
from switch import cmd_switch
import sys
import os.path
from bzrlib.option import Option
import bzrlib.branch
from bzrlib.errors import BzrCommandError
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), 
						 "external")))
from bzrlib import DEFAULT_IGNORE


DEFAULT_IGNORE.append('./.shelf')
DEFAULT_IGNORE.append('./.bzr-shelf*')


Option.OPTIONS['ignored'] = Option('ignored',
        help='delete all ignored files.')
Option.OPTIONS['detritus'] = Option('detritus',
        help='delete conflict files merge backups, and failed selftest dirs.' +
              '(*.THIS, *.BASE, *.OTHER, *~, *.tmp')
Option.OPTIONS['dry-run'] = Option('dry-run',
        help='show files to delete instead of deleting them.')

class cmd_clean_tree(bzrlib.commands.Command):
    """Remove unwanted files from working tree.  <BZRTOOLS>
    Normally, ignored files are left alone.
    """
    takes_options = ['ignored', 'detritus', 'dry-run']
    def run(self, ignored=False, detritus=False, dry_run=False):
        from clean_tree import clean_tree
        clean_tree('.', ignored=ignored, detritus=detritus, dry_run=dry_run)

Option.OPTIONS['merge-branch'] = Option('merge-branch',type=str)

class cmd_graph_ancestry(bzrlib.commands.Command):
    """Produce ancestry graphs using dot.  <BZRTOOLS>
    
    Output format is detected according to file extension.  Some of the more
    common output formats are html, png, gif, svg, ps.  An extension of '.dot'
    will cause a dot graph file to be produced.  HTML output has mouseovers
    that show the commit message.

    Branches are labeled r?, where ? is the revno.  If they have no revno,
    with the last 5 characters of their revision identifier are used instead.

    The value starting with d is "(maximum) distance from the null revision".
    
    If --merge-branch is specified, the two branches are compared and a merge
    base is selected.
    
    Legend:
    white    normal revision
    yellow   THIS  history
    red      OTHER history
    orange   COMMON history
    blue     COMMON non-history ancestor
    green    Merge base (COMMON ancestor farthest from the null revision)
    dotted   Ghost revision (missing from branch storage)

    Ancestry is usually collapsed by skipping revisions with a single parent
    and descendant.  The number of skipped revisions is shown on the arrow.
    This feature can be disabled with --no-collapse.

    By default, revisions are ordered by distance from root, but they can be
    clustered instead using --cluster.

    If available, rsvg is used to antialias PNG and JPEG output, but this can
    be disabled with --no-antialias.
    """
    takes_args = ['branch', 'file']
    takes_options = [Option('no-collapse', help="Do not skip simple nodes"), 
                     Option('no-antialias',
                     help="Do not use rsvg to produce antialiased output"), 
                     Option('merge-branch', type=str, 
                     help="Use this branch to calcuate a merge base"), 
                     Option('cluster', help="Use clustered output.")]
    def run(self, branch, file, no_collapse=False, no_antialias=False,
        merge_branch=None, cluster=False):
        import graph
        if cluster:
            ranking = "cluster"
        else:
            ranking = "forced"
        graph.write_ancestry_file(branch, file, not no_collapse, 
                                  not no_antialias, merge_branch, ranking)

class cmd_fetch_ghosts(bzrlib.commands.Command):
    """Attempt to retrieve ghosts from another branch.  <BZRTOOLS>
    If the other branch is not supplied, the last-pulled branch is used.
    """
    aliases = ['fetch-missing']
    takes_args = ['branch?']
    takes_options = [Option('no-fix')]
    def run(self, branch=None, no_fix=False):
        from fetch_ghosts import fetch_ghosts
        fetch_ghosts(branch, no_fix)

strip_help="""Strip the smallest prefix containing num leading slashes  from \
each file name found in the patch file."""
Option.OPTIONS['strip'] = Option('strip', type=int, help=strip_help)
Option.OPTIONS['bzrdiff'] = Option('bzrdiff',type=None,
                                help="""Handle extra bzr tags""")
class cmd_patch(bzrlib.commands.Command):
    """Apply a named patch to the current tree.  <BZRTOOLS>
    """
    takes_args = ['filename?']
    takes_options = ['strip','bzrdiff']
    def run(self, filename=None, strip=-1, bzrdiff=0):
        from patch import patch
        from bzrlib.workingtree import WorkingTree
        wt = WorkingTree.open_containing('.')[0]
        if strip == -1:
            if bzrdiff: strip = 0
            else:       strip = 1

        return patch(wt, filename, strip, legacy= not bzrdiff)

class cmd_shelve(bzrlib.commands.Command):
    """Temporarily set aside some changes from the current tree.  <BZRTOOLS>

    Shelve allows you to temporarily put changes you've made "on the shelf",
    ie. out of the way, until a later time when you can bring them back from
    the shelf with the 'unshelve' command.

    Shelve is intended to help separate several sets of text changes that have
    been inappropriately mingled.  If you just want to get rid of all changes
    (text and otherwise) and you don't need to restore them later, use revert.
    If you want to shelve all text changes at once, use shelve --all.

    By default shelve asks you what you want to shelve, press '?' at the
    prompt to get help. To shelve everything run shelve --all.

    You can put multiple items on the shelf, each time you run unshelve the
    most recently shelved changes will be reinstated.

    If filenames are specified, only the changes to those files will be
    shelved, other files will be left untouched.

    If a revision is specified, changes since that revision will be shelved.
    """

    takes_args = ['file*']
    takes_options = ['message', 'revision',
            Option('all', help='Shelve all changes without prompting')]

    def run(self, all=False, file_list=None, message=None, revision=None):
        if revision is not None and revision:
            if len(revision) == 1:
                revision = revision[0]
            else:
                raise CommandError("shelve only accepts a single revision "
                                  "parameter.")

        source = BzrPatchSource(revision, file_list)
        s = Shelf(source.base)
        s.shelve(source, all, message)
        return 0

class cmd_shelf(bzrlib.commands.Command):
    """Perform various operations on your shelved patches. See also shelve.

    Subcommands:
        list   (ls)           List the patches on the current shelf.
        delete (del) <patch>  Delete a patch from the current shelf.
        switch       <shelf>  Switch to the named shelf, create it if necessary.
        show         <patch>  Show the contents of the specified patch.
        upgrade               Upgrade old format shelves.
    """
    takes_args = ['subcommand', 'args*']

    def run(self, subcommand, args_list):
        import sys

        source = BzrPatchSource()
        s = Shelf(source.base)

        if subcommand == 'ls' or subcommand == 'list':
            self.__check_no_args(args_list, "shelf list takes no arguments!")
            s.list()
        elif subcommand == 'delete' or subcommand == 'del':
            self.__check_one_arg(args_list, "shelf delete takes one argument!")
            s.delete(args_list[0])
        elif subcommand == 'switch':
            self.__check_one_arg(args_list, "shelf switch takes one argument!")
            s = Shelf(source.base, args_list[0])
            s.make_default()
        elif subcommand == 'show':
            self.__check_one_arg(args_list, "shelf show takes one argument!")
            s.display(args_list[0])
        elif subcommand == 'upgrade':
            self.__check_no_args(args_list, "shelf upgrade takes no arguments!")
            s.upgrade()
        else:
            print subcommand, args_list
            print >>sys.stderr, "Unknown shelf subcommand '%s'" % subcommand

    def __check_one_arg(self, args, msg):
        if args is None or len(args) != 1:
            raise CommandError(msg)

    def __check_no_args(self, args, msg):
        if args is not None:
            raise CommandError(msg)


class cmd_unshelve(bzrlib.commands.Command):
    """Restore the most recently shelved changes to current tree.  <BZRTOOLS>
    See 'shelve' for more information.
    """
    takes_options = [
            Option('all', help='Unshelve all changes without prompting'),
            Option('force', help='Force unshelving even if errors occur'),
    ]
    def run(self, all=False, force=False):
        source = BzrPatchSource()
        s = Shelf(source.base)
        s.unshelve(source, all, force)
        return 0


class cmd_shell(bzrlib.commands.Command):
    """Begin an interactive shell tailored for bzr.  <BZRTOOLS>
    Bzr commands can be used without typing bzr first, and will be run natively
    when possible.  Tab completion is tailored for bzr.  The shell prompt shows
    the branch nick, revno, and path.

    If it encounters any moderately complicated shell command, it will punt to
    the system shell.

    Example:
    $ bzr shell
    bzr bzrtools:287/> status
    modified:
      __init__.py
    bzr bzrtools:287/> status --[TAB][TAB]
    --all        --help       --revision   --show-ids
    bzr bzrtools:287/> status --
    """
    def run(self):
        import shell
        return shell.run_shell()

class cmd_branch_history(bzrlib.commands.Command):
    """\
    Display the development history of a branch  <BZRTOOLS>.

    Each different committer or branch nick is considered a different line of
    development.  Committers are treated as the same if they have the same
    name, or if they have the same email address.
    """
    takes_args = ["branch?"]
    def run(self, branch=None):
        from branchhistory import branch_history 
        return branch_history(branch)


class cmd_zap(bzrlib.commands.Command):
    """\
    Remove a checkout, if it can be done safely. <BZRTOOLS>

    This command will remove a checkout without losing data.  That means
    it only removes checkouts, and only if they have no uncommitted changes.
    """
    takes_options = [Option("branch", help="Remove associtated branch from"
                                           " repository")]
    takes_args = ["checkout"]
    def run(self, checkout, branch=False):
        from zap import zap
        return zap(checkout, remove_branch=branch)


class cmd_cbranch(bzrlib.commands.Command):
    """
    Create a new checkout, associated with a new repository branch. <BZRTOOLS>
    
    When you cbranch, bzr looks up the repository associated with your current
    directory in branches.conf.  It creates a new branch in that repository
    with the same name and relative path as the checkout you request.

    The branches.conf parameter is "cbranch_root".  So if you want 
    cbranch operations in /home/jrandom/bigproject to produce branches in 
    /home/jrandom/bigproject/repository, you'd add this:

    [/home/jrandom/bigproject]
    cbranch_root = /home/jrandom/bigproject/repository

    Note that if "/home/jrandom/bigproject/repository" isn't a repository,
    standalone branches will be produced.  Standalone branches will also
    be produced if the source branch is in 0.7 format (or earlier).
    """
    takes_options = [Option("lightweight", 
                            help="Create a lightweight checkout")]
    takes_args = ["source", "target?"]
    def run(self, source, target=None, lightweight=False):
        from cbranch import cbranch
        return cbranch(source, target, lightweight=lightweight)


class cmd_branches(bzrlib.commands.Command):
    """Scan a location for branches <BZRTOOLS>"""
    takes_args = ["location?"]
    def run(self, location=None):
        from branches import branches
        return branches(location)


class cmd_multi_pull(bzrlib.commands.Command):
    """Pull all the branches under a location, e.g. a repository. <BZRTOOLS>
    
    Both branches present in the directory and the branches of checkouts are
    pulled.
    """
    takes_args = ["location?"]
    def run(self, location=None):
        from bzrlib.branch import Branch
        from bzrlib.transport import get_transport
        from bzrtools import iter_branch_tree
        if location is None:
            location = '.'
        t = get_transport(location)
        if not t.listable():
            print "Can't list this type of location."
            return 3
        for branch, wt in iter_branch_tree(t):
            if wt is None:
                pullable = branch
            else:
                pullable = wt
            parent = branch.get_parent()
            if parent is None:
                continue
            if wt is not None:
                base = wt.basedir
            else:
                base = branch.base
            if base.startswith(t.base):
                relpath = base[len(t.base):].rstrip('/')
            else:
                relpath = base
            print "Pulling %s from %s" % (relpath, parent)
            try:
                pullable.pull(Branch.open(parent))
            except Exception, e:
                print e


commands = [cmd_shelve, cmd_unshelve, cmd_shelf, cmd_clean_tree,
            cmd_graph_ancestry, cmd_fetch_ghosts, cmd_patch, cmd_shell,
            cmd_branch_history, cmd_zap, cmd_cbranch, cmd_branches, 
            cmd_multi_pull, cmd_switch]


command_decorators = []


import bzrlib.builtins
if not hasattr(bzrlib.builtins, "cmd_push"):
    commands.append(push.cmd_push)
else:
    command_decorators.append(push.cmd_push)

from errors import NoPyBaz
try:
    import baz_import
    commands.append(baz_import.cmd_baz_import_branch)
    commands.append(baz_import.cmd_baz_import)

except NoPyBaz:
    class cmd_baz_import_branch(bzrlib.commands.Command):
        """Disabled. (Requires PyBaz)   <BZRTOOLS>"""
        takes_args = ['to_location?', 'from_branch?', 'reuse_history*']
        takes_options = ['verbose', Option('max-count', type=int)]
        def run(self, to_location=None, from_branch=None, fast=False, 
                max_count=None, verbose=False, dry_run=False,
                reuse_history_list=[]):
            print "This command is disabled.  Please install PyBaz."


    class cmd_baz_import(bzrlib.commands.Command):
        """Disabled. (Requires PyBaz)   <BZRTOOLS>"""
        takes_args = ['to_root_dir?', 'from_archive?', 'reuse_history*']
        takes_options = ['verbose', Option('prefixes', type=str,
                         help="Prefixes of branches to import")]
        def run(self, to_root_dir=None, from_archive=None, verbose=False,
                reuse_history_list=[], prefixes=None):
                print "This command is disabled.  Please install PyBaz."
    commands.extend((cmd_baz_import_branch, cmd_baz_import))


if hasattr(bzrlib.commands, 'register_command'):
    for command in commands:
        bzrlib.commands.register_command(command)
    for command in command_decorators:
        command._original_command = bzrlib.commands.register_command(
            command, True)


def test_suite():
    import baz_import
    from bzrlib.tests.TestUtil import TestLoader
    import tests
    from doctest import DocTestSuite, ELLIPSIS
    from unittest import TestSuite
    import clean_tree
    import zap
    import tests.blackbox
    import tests.shelf_tests
    result = TestSuite()
    result.addTest(DocTestSuite(bzrtools, optionflags=ELLIPSIS))
    result.addTest(clean_tree.test_suite())
    result.addTest(DocTestSuite(baz_import))
    result.addTest(tests.test_suite())
    result.addTest(TestLoader().loadTestsFromModule(tests.shelf_tests))
    result.addTest(tests.blackbox.test_suite())
    result.addTest(zap.test_suite())
    return result