~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to __init__.py

  • Committer: Aaron Bentley
  • Date: 2006-05-03 19:39:28 UTC
  • mfrom: (147.4.37 push-to-rpush)
  • mto: This revision was merged to the branch mainline in revision 366.
  • Revision ID: abentley@panoramicfeedback.com-20060503193928-9cb76ec7fa7e881d
MergeĀ fromĀ Robert

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/python
 
2
"""\
 
3
Various useful plugins for working with bzr.
 
4
"""
 
5
import bzrlib.commands
 
6
import rpush
 
7
from errors import CommandError
 
8
from patchsource import BzrPatchSource
 
9
from shelf import Shelf
 
10
from switch import cmd_switch
 
11
import sys
 
12
import os.path
 
13
from bzrlib.option import Option
 
14
import bzrlib.branch
 
15
from bzrlib.errors import BzrCommandError
 
16
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), 
 
17
                                                 "external")))
 
18
from bzrlib import DEFAULT_IGNORE
 
19
 
 
20
 
 
21
DEFAULT_IGNORE.append('./.shelf')
 
22
DEFAULT_IGNORE.append('./.bzr-shelf*')
 
23
 
 
24
 
 
25
Option.OPTIONS['ignored'] = Option('ignored',
 
26
        help='delete all ignored files.')
 
27
Option.OPTIONS['detritus'] = Option('detritus',
 
28
        help='delete conflict files merge backups, and failed selftest dirs.' +
 
29
              '(*.THIS, *.BASE, *.OTHER, *~, *.tmp')
 
30
Option.OPTIONS['dry-run'] = Option('dry-run',
 
31
        help='show files to delete instead of deleting them.')
 
32
 
 
33
class cmd_clean_tree(bzrlib.commands.Command):
 
34
    """Remove unwanted files from working tree.  <BZRTOOLS>
 
35
    Normally, ignored files are left alone.
 
36
    """
 
37
    takes_options = ['ignored', 'detritus', 'dry-run']
 
38
    def run(self, ignored=False, detritus=False, dry_run=False):
 
39
        from clean_tree import clean_tree
 
40
        clean_tree('.', ignored=ignored, detritus=detritus, dry_run=dry_run)
 
41
 
 
42
Option.OPTIONS['merge-branch'] = Option('merge-branch',type=str)
 
43
 
 
44
class cmd_graph_ancestry(bzrlib.commands.Command):
 
45
    """Produce ancestry graphs using dot.  <BZRTOOLS>
 
46
    
 
47
    Output format is detected according to file extension.  Some of the more
 
48
    common output formats are html, png, gif, svg, ps.  An extension of '.dot'
 
49
    will cause a dot graph file to be produced.  HTML output has mouseovers
 
50
    that show the commit message.
 
51
 
 
52
    Branches are labeled r?, where ? is the revno.  If they have no revno,
 
53
    with the last 5 characters of their revision identifier are used instead.
 
54
 
 
55
    The value starting with d is "(maximum) distance from the null revision".
 
56
    
 
57
    If --merge-branch is specified, the two branches are compared and a merge
 
58
    base is selected.
 
59
    
 
60
    Legend:
 
61
    white    normal revision
 
62
    yellow   THIS  history
 
63
    red      OTHER history
 
64
    orange   COMMON history
 
65
    blue     COMMON non-history ancestor
 
66
    green    Merge base (COMMON ancestor farthest from the null revision)
 
67
    dotted   Ghost revision (missing from branch storage)
 
68
 
 
69
    Ancestry is usually collapsed by skipping revisions with a single parent
 
70
    and descendant.  The number of skipped revisions is shown on the arrow.
 
71
    This feature can be disabled with --no-collapse.
 
72
 
 
73
    By default, revisions are ordered by distance from root, but they can be
 
74
    clustered instead using --cluster.
 
75
 
 
76
    If available, rsvg is used to antialias PNG and JPEG output, but this can
 
77
    be disabled with --no-antialias.
 
78
    """
 
79
    takes_args = ['branch', 'file']
 
80
    takes_options = [Option('no-collapse', help="Do not skip simple nodes"), 
 
81
                     Option('no-antialias',
 
82
                     help="Do not use rsvg to produce antialiased output"), 
 
83
                     Option('merge-branch', type=str, 
 
84
                     help="Use this branch to calcuate a merge base"), 
 
85
                     Option('cluster', help="Use clustered output.")]
 
86
    def run(self, branch, file, no_collapse=False, no_antialias=False,
 
87
        merge_branch=None, cluster=False):
 
88
        import graph
 
89
        if cluster:
 
90
            ranking = "cluster"
 
91
        else:
 
92
            ranking = "forced"
 
93
        graph.write_ancestry_file(branch, file, not no_collapse, 
 
94
                                  not no_antialias, merge_branch, ranking)
 
95
 
 
96
class cmd_fetch_ghosts(bzrlib.commands.Command):
 
97
    """Attempt to retrieve ghosts from another branch.  <BZRTOOLS>
 
98
    If the other branch is not supplied, the last-pulled branch is used.
 
99
    """
 
100
    aliases = ['fetch-missing']
 
101
    takes_args = ['branch?']
 
102
    takes_options = [Option('no-fix')]
 
103
    def run(self, branch=None, no_fix=False):
 
104
        from fetch_ghosts import fetch_ghosts
 
105
        fetch_ghosts(branch, no_fix)
 
106
 
 
107
strip_help="""Strip the smallest prefix containing num leading slashes  from \
 
108
each file name found in the patch file."""
 
109
Option.OPTIONS['strip'] = Option('strip', type=int, help=strip_help)
 
110
Option.OPTIONS['bzrdiff'] = Option('bzrdiff',type=None,
 
111
                                help="""Handle extra bzr tags""")
 
112
class cmd_patch(bzrlib.commands.Command):
 
113
    """Apply a named patch to the current tree.  <BZRTOOLS>
 
114
    """
 
115
    takes_args = ['filename?']
 
116
    takes_options = ['strip','bzrdiff']
 
117
    def run(self, filename=None, strip=-1, bzrdiff=0):
 
118
        from patch import patch
 
119
        from bzrlib.workingtree import WorkingTree
 
120
        wt = WorkingTree.open_containing('.')[0]
 
121
        if strip == -1:
 
122
            if bzrdiff: strip = 0
 
123
            else:       strip = 1
 
124
 
 
125
        return patch(wt, filename, strip, legacy= not bzrdiff)
 
126
 
 
127
class cmd_shelve(bzrlib.commands.Command):
 
128
    """Temporarily set aside some changes from the current tree.  <BZRTOOLS>
 
129
 
 
130
    Shelve allows you to temporarily put changes you've made "on the shelf",
 
131
    ie. out of the way, until a later time when you can bring them back from
 
132
    the shelf with the 'unshelve' command.
 
133
 
 
134
    Shelve is intended to help separate several sets of text changes that have
 
135
    been inappropriately mingled.  If you just want to get rid of all changes
 
136
    (text and otherwise) and you don't need to restore them later, use revert.
 
137
    If you want to shelve all text changes at once, use shelve --all.
 
138
 
 
139
    By default shelve asks you what you want to shelve, press '?' at the
 
140
    prompt to get help. To shelve everything run shelve --all.
 
141
 
 
142
    You can put multiple items on the shelf, each time you run unshelve the
 
143
    most recently shelved changes will be reinstated.
 
144
 
 
145
    If filenames are specified, only the changes to those files will be
 
146
    shelved, other files will be left untouched.
 
147
 
 
148
    If a revision is specified, changes since that revision will be shelved.
 
149
    """
 
150
 
 
151
    takes_args = ['file*']
 
152
    takes_options = ['message', 'revision',
 
153
            Option('all', help='Shelve all changes without prompting')]
 
154
 
 
155
    def run(self, all=False, file_list=None, message=None, revision=None):
 
156
        if revision is not None and revision:
 
157
            if len(revision) == 1:
 
158
                revision = revision[0]
 
159
            else:
 
160
                raise CommandError("shelve only accepts a single revision "
 
161
                                  "parameter.")
 
162
 
 
163
        source = BzrPatchSource(revision, file_list)
 
164
        s = Shelf(source.base)
 
165
        s.shelve(source, all, message)
 
166
        return 0
 
167
 
 
168
class cmd_shelf(bzrlib.commands.Command):
 
169
    """Perform various operations on your shelved patches. See also shelve.
 
170
 
 
171
    Subcommands:
 
172
        list   (ls)           List the patches on the current shelf.
 
173
        delete (del) <patch>  Delete a patch from the current shelf.
 
174
        switch       <shelf>  Switch to the named shelf, create it if necessary.
 
175
        show         <patch>  Show the contents of the specified patch.
 
176
        upgrade               Upgrade old format shelves.
 
177
    """
 
178
    takes_args = ['subcommand', 'args*']
 
179
 
 
180
    def run(self, subcommand, args_list):
 
181
        import sys
 
182
 
 
183
        source = BzrPatchSource()
 
184
        s = Shelf(source.base)
 
185
 
 
186
        if subcommand == 'ls' or subcommand == 'list':
 
187
            self.__check_no_args(args_list, "shelf list takes no arguments!")
 
188
            s.list()
 
189
        elif subcommand == 'delete' or subcommand == 'del':
 
190
            self.__check_one_arg(args_list, "shelf delete takes one argument!")
 
191
            s.delete(args_list[0])
 
192
        elif subcommand == 'switch':
 
193
            self.__check_one_arg(args_list, "shelf switch takes one argument!")
 
194
            s = Shelf(source.base, args_list[0])
 
195
            s.make_default()
 
196
        elif subcommand == 'show':
 
197
            self.__check_one_arg(args_list, "shelf show takes one argument!")
 
198
            s.display(args_list[0])
 
199
        elif subcommand == 'upgrade':
 
200
            self.__check_no_args(args_list, "shelf upgrade takes no arguments!")
 
201
            s.upgrade()
 
202
        else:
 
203
            print subcommand, args_list
 
204
            print >>sys.stderr, "Unknown shelf subcommand '%s'" % subcommand
 
205
 
 
206
    def __check_one_arg(self, args, msg):
 
207
        if args is None or len(args) != 1:
 
208
            raise CommandError(msg)
 
209
 
 
210
    def __check_no_args(self, args, msg):
 
211
        if args is not None:
 
212
            raise CommandError(msg)
 
213
 
 
214
 
 
215
class cmd_unshelve(bzrlib.commands.Command):
 
216
    """Restore the most recently shelved changes to current tree.  <BZRTOOLS>
 
217
    See 'shelve' for more information.
 
218
    """
 
219
    takes_options = [
 
220
            Option('all', help='Unshelve all changes without prompting'),
 
221
            Option('force', help='Force unshelving even if errors occur'),
 
222
    ]
 
223
    def run(self, all=False, force=False):
 
224
        source = BzrPatchSource()
 
225
        s = Shelf(source.base)
 
226
        s.unshelve(source, all, force)
 
227
        return 0
 
228
 
 
229
 
 
230
class cmd_shell(bzrlib.commands.Command):
 
231
    """Begin an interactive shell tailored for bzr.  <BZRTOOLS>
 
232
    Bzr commands can be used without typing bzr first, and will be run natively
 
233
    when possible.  Tab completion is tailored for bzr.  The shell prompt shows
 
234
    the branch nick, revno, and path.
 
235
 
 
236
    If it encounters any moderately complicated shell command, it will punt to
 
237
    the system shell.
 
238
 
 
239
    Example:
 
240
    $ bzr shell
 
241
    bzr bzrtools:287/> status
 
242
    modified:
 
243
      __init__.py
 
244
    bzr bzrtools:287/> status --[TAB][TAB]
 
245
    --all        --help       --revision   --show-ids
 
246
    bzr bzrtools:287/> status --
 
247
    """
 
248
    def run(self):
 
249
        import shell
 
250
        return shell.run_shell()
 
251
 
 
252
class cmd_branch_history(bzrlib.commands.Command):
 
253
    """\
 
254
    Display the development history of a branch  <BZRTOOLS>.
 
255
 
 
256
    Each different committer or branch nick is considered a different line of
 
257
    development.  Committers are treated as the same if they have the same
 
258
    name, or if they have the same email address.
 
259
    """
 
260
    takes_args = ["branch?"]
 
261
    def run(self, branch=None):
 
262
        from branchhistory import branch_history 
 
263
        return branch_history(branch)
 
264
 
 
265
 
 
266
class cmd_zap(bzrlib.commands.Command):
 
267
    """\
 
268
    Remove a checkout, if it can be done safely. <BZRTOOLS>
 
269
 
 
270
    This command will remove a checkout without losing data.  That means
 
271
    it only removes checkouts, and only if they have no uncommitted changes.
 
272
    """
 
273
    takes_options = [Option("branch", help="Remove associtated branch from"
 
274
                                           " repository")]
 
275
    takes_args = ["checkout"]
 
276
    def run(self, checkout, branch=False):
 
277
        from zap import zap
 
278
        return zap(checkout, remove_branch=branch)
 
279
 
 
280
 
 
281
class cmd_cbranch(bzrlib.commands.Command):
 
282
    """
 
283
    Create a new checkout, associated with a new repository branch. <BZRTOOLS>
 
284
    
 
285
    When you cbranch, bzr looks up the repository associated with your current
 
286
    directory in branches.conf.  It creates a new branch in that repository
 
287
    with the same name and relative path as the checkout you request.
 
288
 
 
289
    The branches.conf parameter is "cbranch_root".  So if you want 
 
290
    cbranch operations in /home/jrandom/bigproject to produce branches in 
 
291
    /home/jrandom/bigproject/repository, you'd add this:
 
292
 
 
293
    [/home/jrandom/bigproject]
 
294
    cbranch_root = /home/jrandom/bigproject/repository
 
295
 
 
296
    Note that if "/home/jrandom/bigproject/repository" isn't a repository,
 
297
    standalone branches will be produced.  Standalone branches will also
 
298
    be produced if the source branch is in 0.7 format (or earlier).
 
299
    """
 
300
    takes_options = [Option("lightweight", 
 
301
                            help="Create a lightweight checkout")]
 
302
    takes_args = ["source", "target?"]
 
303
    def run(self, source, target=None, lightweight=False):
 
304
        from cbranch import cbranch
 
305
        return cbranch(source, target, lightweight=lightweight)
 
306
 
 
307
 
 
308
class cmd_branches(bzrlib.commands.Command):
 
309
    """Scan a location for branches <BZRTOOLS>"""
 
310
    takes_args = ["location?"]
 
311
    def run(self, location=None):
 
312
        from branches import branches
 
313
        return branches(location)
 
314
 
 
315
 
 
316
class cmd_multi_pull(bzrlib.commands.Command):
 
317
    """Pull all the branches under a location, e.g. a repository. <BZRTOOLS>
 
318
    
 
319
    Both branches present in the directory and the branches of checkouts are
 
320
    pulled.
 
321
    """
 
322
    takes_args = ["location?"]
 
323
    def run(self, location=None):
 
324
        from bzrlib.branch import Branch
 
325
        from bzrlib.transport import get_transport
 
326
        from bzrtools import iter_branch_tree
 
327
        if location is None:
 
328
            location = '.'
 
329
        t = get_transport(location)
 
330
        if not t.listable():
 
331
            print "Can't list this type of location."
 
332
            return 3
 
333
        for branch, wt in iter_branch_tree(t):
 
334
            if wt is None:
 
335
                pullable = branch
 
336
            else:
 
337
                pullable = wt
 
338
            parent = branch.get_parent()
 
339
            if parent is None:
 
340
                continue
 
341
            if wt is not None:
 
342
                base = wt.basedir
 
343
            else:
 
344
                base = branch.base
 
345
            if base.startswith(t.base):
 
346
                relpath = base[len(t.base):].rstrip('/')
 
347
            else:
 
348
                relpath = base
 
349
            print "Pulling %s from %s" % (relpath, parent)
 
350
            try:
 
351
                pullable.pull(Branch.open(parent))
 
352
            except Exception, e:
 
353
                print e
 
354
 
 
355
 
 
356
class cmd_branch_mark(bzrlib.commands.Command):
 
357
    """
 
358
    Add, view or list branch markers <EXPERIMENTAL>
 
359
 
 
360
    To add a mark, do 'bzr branch-mark MARK'.
 
361
    To list marks, do 'bzr branch-mark' (this lists all marks for the branch's
 
362
    repository).
 
363
    To delete a mark, do 'bzr branch-mark --delete MARK'
 
364
 
 
365
    These marks can be used to track a branch's status.
 
366
    """
 
367
    takes_args = ['mark?', 'branch?']
 
368
    takes_options = [Option('delete', help='Delete this mark')]
 
369
    def run(self, mark=None, branch=None, delete=False):
 
370
        from branch_mark import branch_mark
 
371
        branch_mark(mark, branch, delete)
 
372
 
 
373
 
 
374
commands = [cmd_shelve, cmd_unshelve, cmd_shelf, cmd_clean_tree,
 
375
            cmd_graph_ancestry, cmd_fetch_ghosts, cmd_patch, cmd_shell,
 
376
            cmd_branch_history, cmd_zap, cmd_cbranch, cmd_branches, 
 
377
            cmd_multi_pull, cmd_switch, cmd_branch_mark]
 
378
 
 
379
 
 
380
 
 
381
 
 
382
import bzrlib.builtins
 
383
commands.append(rpush.cmd_rpush)
 
384
 
 
385
from errors import NoPyBaz
 
386
try:
 
387
    import baz_import
 
388
    commands.append(baz_import.cmd_baz_import_branch)
 
389
    commands.append(baz_import.cmd_baz_import)
 
390
 
 
391
except NoPyBaz:
 
392
    class cmd_baz_import_branch(bzrlib.commands.Command):
 
393
        """Disabled. (Requires PyBaz)   <BZRTOOLS>"""
 
394
        takes_args = ['to_location?', 'from_branch?', 'reuse_history*']
 
395
        takes_options = ['verbose', Option('max-count', type=int)]
 
396
        def run(self, to_location=None, from_branch=None, fast=False, 
 
397
                max_count=None, verbose=False, dry_run=False,
 
398
                reuse_history_list=[]):
 
399
            print "This command is disabled.  Please install PyBaz."
 
400
 
 
401
 
 
402
    class cmd_baz_import(bzrlib.commands.Command):
 
403
        """Disabled. (Requires PyBaz)   <BZRTOOLS>"""
 
404
        takes_args = ['to_root_dir?', 'from_archive?', 'reuse_history*']
 
405
        takes_options = ['verbose', Option('prefixes', type=str,
 
406
                         help="Prefixes of branches to import")]
 
407
        def run(self, to_root_dir=None, from_archive=None, verbose=False,
 
408
                reuse_history_list=[], prefixes=None):
 
409
                print "This command is disabled.  Please install PyBaz."
 
410
    commands.extend((cmd_baz_import_branch, cmd_baz_import))
 
411
 
 
412
 
 
413
if hasattr(bzrlib.commands, 'register_command'):
 
414
    for command in commands:
 
415
        bzrlib.commands.register_command(command)
 
416
 
 
417
 
 
418
def test_suite():
 
419
    import baz_import
 
420
    from bzrlib.tests.TestUtil import TestLoader
 
421
    import tests
 
422
    from doctest import DocTestSuite, ELLIPSIS
 
423
    from unittest import TestSuite
 
424
    import clean_tree
 
425
    import zap
 
426
    import tests.blackbox
 
427
    import tests.shelf_tests
 
428
    result = TestSuite()
 
429
    result.addTest(DocTestSuite(bzrtools, optionflags=ELLIPSIS))
 
430
    result.addTest(clean_tree.test_suite())
 
431
    result.addTest(DocTestSuite(baz_import))
 
432
    result.addTest(tests.test_suite())
 
433
    result.addTest(TestLoader().loadTestsFromModule(tests.shelf_tests))
 
434
    result.addTest(tests.blackbox.test_suite())
 
435
    result.addTest(zap.test_suite())
 
436
    return result