~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to command_classes.py

  • Committer: Aaron Bentley
  • Date: 2013-08-20 03:02:43 UTC
  • Revision ID: aaron@aaronbentley.com-20130820030243-r8v1xfbcnd8f10p4
Fix zap command for 2.6/7

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 push
 
1
# Copyright (C) 2005, 2006, 2007, 2011 Aaron Bentley <aaron@aaronbentley.com>
 
2
# Copyright (C) 2005, 2006, 2011 Canonical Limited.
 
3
# Copyright (C) 2006 Michael Ellerman.
 
4
#
 
5
#    This program is free software; you can redistribute it and/or modify
 
6
#    it under the terms of the GNU General Public License as published by
 
7
#    the Free Software Foundation; either version 2 of the License, or
 
8
#    (at your option) any later version.
 
9
#
 
10
#    This program is distributed in the hope that it will be useful,
 
11
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
12
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
13
#    GNU General Public License for more details.
 
14
#
 
15
#    You should have received a copy of the GNU General Public License
 
16
#    along with this program; if not, write to the Free Software
 
17
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
18
 
 
19
import bzrlib
 
20
 
 
21
from bzrlib.lazy_import import lazy_import
 
22
lazy_import(globals(), """
 
23
from bzrlib import help, urlutils
 
24
from bzrlib.plugins.bzrtools import shelf
 
25
""")
 
26
 
 
27
from bzrlib.plugins import bzrtools
 
28
from command import BzrToolsCommand
7
29
from errors import CommandError
8
30
from patchsource import BzrPatchSource
9
 
from shelf import Shelf
10
 
import sys
11
 
import os.path
12
 
from bzrlib.option import Option
13
 
import bzrlib.branch
 
31
 
 
32
import bzrlib.commands
 
33
from bzrlib.branch import Branch
 
34
from bzrlib.commands import get_cmd_object
14
35
from bzrlib.errors import BzrCommandError
15
 
from reweave_inventory import cmd_fix
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.
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):
 
36
from bzrlib.option import Option, RegistryOption
 
37
 
 
38
 
 
39
class cmd_graph_ancestry(BzrToolsCommand):
45
40
    """Produce ancestry graphs using dot.
46
 
    
 
41
 
47
42
    Output format is detected according to file extension.  Some of the more
48
43
    common output formats are html, png, gif, svg, ps.  An extension of '.dot'
49
44
    will cause a dot graph file to be produced.  HTML output has mouseovers
53
48
    with the last 5 characters of their revision identifier are used instead.
54
49
 
55
50
    The value starting with d is "(maximum) distance from the null revision".
56
 
    
 
51
 
57
52
    If --merge-branch is specified, the two branches are compared and a merge
58
53
    base is selected.
59
 
    
 
54
 
60
55
    Legend:
61
56
    white    normal revision
62
57
    yellow   THIS  history
76
71
    If available, rsvg is used to antialias PNG and JPEG output, but this can
77
72
    be disabled with --no-antialias.
78
73
    """
79
 
    takes_args = ['branch', 'file']
80
 
    takes_options = [Option('no-collapse', help="Do not skip simple nodes"), 
 
74
    takes_args = ['file', 'merge_branch?']
 
75
    takes_options = [Option('no-collapse', help="Do not skip simple nodes."),
81
76
                     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):
 
77
                     help="Do not use rsvg to produce antialiased output."),
 
78
                     Option('merge-branch', type=str,
 
79
                     help="Use this branch to calcuate a merge base."),
 
80
                     Option('cluster', help="Use clustered output."),
 
81
                     Option('max-distance',
 
82
                            help="Show no nodes farther than this.", type=int),
 
83
                     Option('directory',
 
84
                            help='Source branch to use (default is current'
 
85
                            ' directory).',
 
86
                            short_name='d',
 
87
                            type=unicode),
 
88
                    ]
 
89
    def run(self, file, merge_branch=None, no_collapse=False,
 
90
            no_antialias=False, cluster=False, max_distance=100,
 
91
            directory='.'):
 
92
        if max_distance == -1:
 
93
            max_distance = None
88
94
        import graph
89
95
        if cluster:
90
96
            ranking = "cluster"
91
97
        else:
92
98
            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):
 
99
        graph.write_ancestry_file(directory, file, not no_collapse,
 
100
                                  not no_antialias, merge_branch, ranking,
 
101
                                  max_distance=max_distance)
 
102
 
 
103
 
 
104
class cmd_fetch_ghosts(BzrToolsCommand):
97
105
    """Attempt to retrieve ghosts from another branch.
98
106
    If the other branch is not supplied, the last-pulled branch is used.
99
107
    """
100
108
    aliases = ['fetch-missing']
101
109
    takes_args = ['branch?']
102
 
    takes_options = [Option('no-fix')]
 
110
    takes_options = [Option('no-fix', help="Skip additional synchonization.")]
103
111
    def run(self, branch=None, no_fix=False):
104
112
        from fetch_ghosts import fetch_ghosts
105
 
        fetch_ghosts(branch, no_fix)
 
113
        fetch_ghosts(branch, do_reconcile=not no_fix)
106
114
 
107
115
strip_help="""Strip the smallest prefix containing num leading slashes  from \
108
116
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):
 
117
 
 
118
 
 
119
class cmd_patch(BzrToolsCommand):
113
120
    """Apply a named patch to the current tree.
114
121
    """
115
122
    takes_args = ['filename?']
116
 
    takes_options = ['strip','bzrdiff']
117
 
    def run(self, filename=None, strip=-1, bzrdiff=0):
 
123
    takes_options = [Option('strip', type=int, short_name='p',
 
124
                            help=strip_help),
 
125
                     Option('silent', help='Suppress chatter.')]
 
126
    def run(self, filename=None, strip=None, silent=False):
118
127
        from patch import patch
119
 
        from bzrlib.branch import Branch
120
 
        b = Branch.open_containing('.')[0]
121
 
        if strip == -1:
122
 
            if bzrdiff: strip = 0
123
 
            else:       strip = 1
124
 
 
125
 
        return patch(b, filename, strip, legacy= not bzrdiff)
126
 
 
127
 
class cmd_shelve(bzrlib.commands.Command):
 
128
        from bzrlib.workingtree import WorkingTree
 
129
        wt = WorkingTree.open_containing('.')[0]
 
130
        if strip is None:
 
131
            strip = 0
 
132
        return patch(wt, filename, strip, silent)
 
133
 
 
134
 
 
135
class cmd_shelve1(BzrToolsCommand):
128
136
    """Temporarily set aside some changes from the current tree.
129
137
 
130
138
    Shelve allows you to temporarily put changes you've made "on the shelf",
131
139
    ie. out of the way, until a later time when you can bring them back from
132
 
    the shelf with the 'unshelve' command.
 
140
    the shelf with the 'unshelve1' command.
133
141
 
134
142
    Shelve is intended to help separate several sets of text changes that have
135
143
    been inappropriately mingled.  If you just want to get rid of all changes
136
144
    (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.
 
145
    If you want to shelve all text changes at once, use shelve1 --all.
 
146
 
 
147
    By default shelve1 asks you what you want to shelve, press '?' at the
 
148
    prompt to get help. To shelve everything run shelve1 --all.
144
149
 
145
150
    If filenames are specified, only the changes to those files will be
146
151
    shelved, other files will be left untouched.
147
152
 
148
153
    If a revision is specified, changes since that revision will be shelved.
 
154
 
 
155
    You can put multiple items on the shelf. Normally each time you run
 
156
    unshelve1 the most recently shelved changes will be reinstated. However,
 
157
    you can also unshelve changes in a different order by explicitly
 
158
    specifiying which changes to unshelve1. This works best when the changes
 
159
    don't depend on each other.
 
160
 
 
161
    While you have patches on the shelf you can view and manipulate them with
 
162
    the 'shelf1' command. Run 'bzr shelf1 -h' for more info.
149
163
    """
150
164
 
151
165
    takes_args = ['file*']
152
 
    takes_options = ['message', 'revision',
153
 
            Option('all', help='Shelve all changes without prompting')]
 
166
    takes_options = [Option('message',
 
167
            help='A message to associate with the shelved changes.',
 
168
            short_name='m', type=unicode),
 
169
            'revision',
 
170
            Option('all', help='Shelve all changes without prompting.'),
 
171
            Option('no-color', help='Never display changes in color.')]
154
172
 
155
 
    def run(self, all=False, file_list=None, message=None, revision=None):
 
173
    def run(self, all=False, file_list=None, message=None, revision=None,
 
174
            no_color=False):
156
175
        if revision is not None and revision:
157
176
            if len(revision) == 1:
158
177
                revision = revision[0]
161
180
                                  "parameter.")
162
181
 
163
182
        source = BzrPatchSource(revision, file_list)
164
 
        s = Shelf(source.base)
165
 
        s.shelve(source, all, message)
 
183
        s = shelf.Shelf(source.base)
 
184
        s.shelve(source, all, message, no_color)
166
185
        return 0
167
186
 
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
 
    """
 
187
 
 
188
# The following classes are only used as subcommands for 'shelf1', they're
 
189
# not to be registered directly with bzr.
 
190
 
 
191
class cmd_shelf_list(bzrlib.commands.Command):
 
192
    """List the patches on the current shelf."""
 
193
    aliases = ['list', 'ls']
 
194
    def run(self):
 
195
        self.shelf.list()
 
196
 
 
197
 
 
198
class cmd_shelf_delete(bzrlib.commands.Command):
 
199
    """Delete the patch from the current shelf."""
 
200
    aliases = ['delete', 'del']
 
201
    takes_args = ['patch']
 
202
    def run(self, patch):
 
203
        self.shelf.delete(patch)
 
204
 
 
205
 
 
206
class cmd_shelf_switch(bzrlib.commands.Command):
 
207
    """Switch to the other shelf, create it if necessary."""
 
208
    aliases = ['switch']
 
209
    takes_args = ['othershelf']
 
210
    def run(self, othershelf):
 
211
        s = shelf.Shelf(self.shelf.base, othershelf)
 
212
        s.make_default()
 
213
 
 
214
 
 
215
class cmd_shelf_show(bzrlib.commands.Command):
 
216
    """Show the contents of the specified or topmost patch."""
 
217
    aliases = ['show', 'cat', 'display']
 
218
    takes_args = ['patch?']
 
219
    def run(self, patch=None):
 
220
        self.shelf.display(patch)
 
221
 
 
222
 
 
223
class cmd_shelf_upgrade(bzrlib.commands.Command):
 
224
    """Upgrade old format shelves."""
 
225
    aliases = ['upgrade']
 
226
    def run(self):
 
227
        self.shelf.upgrade()
 
228
 
 
229
 
 
230
class cmd_shelf1(BzrToolsCommand):
 
231
    """Perform various operations on your shelved patches. See also shelve1."""
178
232
    takes_args = ['subcommand', 'args*']
179
233
 
 
234
    subcommands = [cmd_shelf_list, cmd_shelf_delete, cmd_shelf_switch,
 
235
        cmd_shelf_show, cmd_shelf_upgrade]
 
236
 
180
237
    def run(self, subcommand, args_list):
181
238
        import sys
182
239
 
 
240
        if args_list is None:
 
241
            args_list = []
 
242
        cmd = self._get_cmd_object(subcommand)
183
243
        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 the current tree.
217
 
    See 'shelve' for more information.
 
244
        s = shelf.Shelf(source.base)
 
245
        cmd.shelf = s
 
246
 
 
247
        if args_list is None:
 
248
            args_list = []
 
249
        return cmd.run_argv_aliases(args_list)
 
250
 
 
251
    def _get_cmd_object(self, cmd_name):
 
252
        for cmd_class in self.subcommands:
 
253
            for alias in cmd_class.aliases:
 
254
                if alias == cmd_name:
 
255
                    return cmd_class()
 
256
        raise CommandError("Unknown shelf subcommand '%s'" % cmd_name)
 
257
 
 
258
    def help(self):
 
259
        text = ["%s\n\nSubcommands:\n" % self.__doc__]
 
260
 
 
261
        for cmd_class in self.subcommands:
 
262
            text.extend(self.sub_help(cmd_class) + ['\n'])
 
263
 
 
264
        return ''.join(text)
 
265
 
 
266
    def sub_help(self, cmd_class):
 
267
        text = []
 
268
        cmd_obj = cmd_class()
 
269
        indent = 2 * ' '
 
270
 
 
271
        usage = cmd_obj._usage()
 
272
        usage = usage.replace('bzr shelf-', '')
 
273
        text.append('%s%s\n' % (indent, usage))
 
274
 
 
275
        text.append('%s%s\n' % (2 * indent, cmd_class.__doc__))
 
276
 
 
277
        # Somewhat copied from bzrlib.help.help_on_command_options
 
278
        option_help = []
 
279
        for option_name, option in sorted(cmd_obj.options().items()):
 
280
            if option_name == 'help':
 
281
                continue
 
282
            option_help.append('%s--%s' % (3 * indent, option_name))
 
283
            if option.type is not None:
 
284
                option_help.append(' %s' % option.argname.upper())
 
285
            if option.short_name():
 
286
                option_help.append(', -%s' % option.short_name())
 
287
            option_help.append('%s%s\n' % (2 * indent, option.help))
 
288
 
 
289
        if len(option_help) > 0:
 
290
            text.append('%soptions:\n' % (2 * indent))
 
291
            text.extend(option_help)
 
292
 
 
293
        return text
 
294
 
 
295
 
 
296
class cmd_unshelve1(BzrToolsCommand):
 
297
    """Restore shelved changes.
 
298
 
 
299
    By default the most recently shelved changes are restored. However if you
 
300
    specify a patch by name those changes will be restored instead.
 
301
 
 
302
    See 'shelve1' for more information.
218
303
    """
219
304
    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):
 
305
            Option('all', help='Unshelve all changes without prompting.'),
 
306
            Option('force', help='Force unshelving even if errors occur.'),
 
307
            Option('no-color', help='Never display changes in color.')
 
308
        ]
 
309
    takes_args = ['patch?']
 
310
    def run(self, patch=None, all=False, force=False, no_color=False):
224
311
        source = BzrPatchSource()
225
 
        s = Shelf(source.base)
226
 
        s.unshelve(source, all, force)
 
312
        s = shelf.Shelf(source.base)
 
313
        s.unshelve(source, patch, all, force, no_color)
227
314
        return 0
228
315
 
229
316
 
230
 
class cmd_shell(bzrlib.commands.Command):
 
317
class cmd_shell(BzrToolsCommand):
231
318
    """Begin an interactive shell tailored for bzr.
232
319
    Bzr commands can be used without typing bzr first, and will be run natively
233
320
    when possible.  Tab completion is tailored for bzr.  The shell prompt shows
245
332
    --all        --help       --revision   --show-ids
246
333
    bzr bzrtools:287/> status --
247
334
    """
248
 
    def run(self):
 
335
    takes_options = [
 
336
        Option('directory',
 
337
            help='Branch in which to start the shell, '
 
338
                 'rather than the one containing the working directory.',
 
339
            short_name='d',
 
340
            type=unicode,
 
341
            ),
 
342
        ]
 
343
    def run(self, directory=None):
249
344
        import shell
250
 
        return shell.run_shell()
251
 
 
252
 
class cmd_branch_history(bzrlib.commands.Command):
 
345
        return shell.run_shell(directory)
 
346
 
 
347
 
 
348
class cmd_branch_history(BzrToolsCommand):
253
349
    """\
254
 
    Display the revision history with reference to lines of development.
 
350
    Display the development history of a branch.
255
351
 
256
352
    Each different committer or branch nick is considered a different line of
257
353
    development.  Committers are treated as the same if they have the same
259
355
    """
260
356
    takes_args = ["branch?"]
261
357
    def run(self, branch=None):
262
 
        from branchhistory import branch_history 
 
358
        from branchhistory import branch_history
263
359
        return branch_history(branch)
264
360
 
265
 
commands = [cmd_shelve, cmd_unshelve, cmd_shelf, cmd_clean_tree,
266
 
            cmd_graph_ancestry, cmd_fetch_ghosts, cmd_patch, cmd_shell,
267
 
            cmd_fix, cmd_branch_history]
268
 
 
269
 
command_decorators = []
270
 
 
271
 
command_decorators = []
272
 
 
273
 
import bzrlib.builtins
274
 
if not hasattr(bzrlib.builtins, "cmd_push"):
275
 
    commands.append(push.cmd_push)
276
 
else:
277
 
    command_decorators.append(push.cmd_push)
278
 
 
279
 
from errors import NoPyBaz
280
 
try:
281
 
    import baz_import
282
 
    commands.append(baz_import.cmd_baz_import_branch)
283
 
    commands.append(baz_import.cmd_baz_import)
284
 
 
285
 
except NoPyBaz:
286
 
    class cmd_baz_import_branch(bzrlib.commands.Command):
287
 
        """Disabled. (Requires PyBaz)"""
288
 
        takes_args = ['to_location?', 'from_branch?', 'reuse_history*']
289
 
        takes_options = ['verbose', Option('max-count', type=int)]
290
 
        def run(self, to_location=None, from_branch=None, fast=False, 
291
 
                max_count=None, verbose=False, dry_run=False,
292
 
                reuse_history_list=[]):
293
 
            print "This command is disabled.  Please install PyBaz."
294
 
 
295
 
 
296
 
    class cmd_baz_import(bzrlib.commands.Command):
297
 
        """Disabled. (Requires PyBaz)"""
298
 
        takes_args = ['to_root_dir?', 'from_archive?', 'reuse_history*']
299
 
        takes_options = ['verbose', Option('prefixes', type=str,
300
 
                         help="Prefixes of branches to import")]
301
 
        def run(self, to_root_dir=None, from_archive=None, verbose=False,
302
 
                reuse_history_list=[], prefixes=None):
303
 
                print "This command is disabled.  Please install PyBaz."
304
 
    commands.extend((cmd_baz_import_branch, cmd_baz_import))
305
 
 
306
 
 
307
 
if hasattr(bzrlib.commands, 'register_command'):
308
 
    for command in commands:
309
 
        bzrlib.commands.register_command(command)
310
 
    for command in command_decorators:
311
 
        command._original_command = bzrlib.commands.register_command(
312
 
            command, True)
313
 
 
314
 
 
315
 
def test_suite():
316
 
    import baz_import
317
 
    from bzrlib.tests.TestUtil import TestLoader
318
 
    import tests
319
 
    from doctest import DocTestSuite, ELLIPSIS
320
 
    from unittest import TestSuite
321
 
    import clean_tree
322
 
    import blackbox
323
 
    import shelf_tests
324
 
    result = TestSuite()
325
 
    result.addTest(DocTestSuite(bzrtools, optionflags=ELLIPSIS))
326
 
    result.addTest(clean_tree.test_suite())
327
 
    result.addTest(DocTestSuite(baz_import))
328
 
    result.addTest(tests.test_suite())
329
 
    result.addTest(TestLoader().loadTestsFromModule(shelf_tests))
330
 
    result.addTest(blackbox.test_suite())
331
 
    return result
 
361
 
 
362
class cmd_zap(BzrToolsCommand):
 
363
    """\
 
364
    Remove a lightweight checkout, if it can be done safely.
 
365
 
 
366
    This command will remove a lightweight checkout without losing data.  That
 
367
    means it only removes lightweight checkouts, and only if they have no
 
368
    uncommitted changes.
 
369
 
 
370
    If --branch is specified, the branch will be deleted too, but only if the
 
371
    the branch has no new commits (relative to its parent).
 
372
 
 
373
    If bzr-pipeline is also installed, the --store option will store changes
 
374
    in the branch before deleting the tree.  To restore the changes, do::
 
375
 
 
376
      bzr checkout --lightweight $BRANCH $CHECKOUT
 
377
      bzr switch-pipe -d $CHECKOUT `bzr nick -d $CHECKOUT`
 
378
    """
 
379
    takes_options = [Option("branch", help="Remove associated branch from"
 
380
                                           " repository."),
 
381
                     RegistryOption('change_policy',
 
382
                                    'How to handle changed files',
 
383
                                    lazy_registry =
 
384
                                    ('bzrlib.plugins.bzrtools.zap',
 
385
                                        'change_policy_registry'),
 
386
                                    value_switches=True,
 
387
                                    enum_switch=False)]
 
388
    takes_args = ["checkout"]
 
389
    def run(self, checkout, branch=False, change_policy=None):
 
390
        from zap import (
 
391
            change_policy_registry,
 
392
            StoreChanges,
 
393
            zap,
 
394
        )
 
395
        if change_policy is None:
 
396
            change_policy = change_policy_registry.get()
 
397
        if change_policy is StoreChanges:
 
398
            try:
 
399
                import bzrlib.plugins.pipeline
 
400
            except ImportError:
 
401
                raise BzrCommandError('--store requires bzr-pipeline.')
 
402
        return zap(checkout, remove_branch=branch, policy=change_policy)
 
403
 
 
404
 
 
405
class cmd_cbranch(BzrToolsCommand):
 
406
    """
 
407
    Create a new checkout, associated with a new repository branch.
 
408
 
 
409
    When you cbranch, bzr looks up a target location in locations.conf, and
 
410
    creates the branch there.
 
411
 
 
412
    In your locations.conf, add the following lines:
 
413
    [/working_directory_root]
 
414
    cbranch_target = /branch_root
 
415
    cbranch_target:policy = appendpath
 
416
 
 
417
    This will mean that if you run "bzr cbranch foo/bar foo/baz" in the
 
418
    working directory root, the branch will be created in
 
419
    "/branch_root/foo/baz"
 
420
 
 
421
    NOTE: cbranch also supports "cbranch_root", but that behaviour is
 
422
    deprecated.
 
423
    """
 
424
    takes_options = [Option("lightweight",
 
425
                            help="Create a lightweight checkout."), 'revision',
 
426
                     Option('files-from', type=unicode,
 
427
                            help='Accelerate checkout using files from this'
 
428
                                 ' tree.'),
 
429
                     Option('hardlink',
 
430
                            help='Hard-link files from source/files-from tree'
 
431
                            ' where posible.')]
 
432
    takes_args = ["source", "target?"]
 
433
    def run(self, source, target=None, lightweight=False, revision=None,
 
434
            files_from=None, hardlink=False):
 
435
        from cbranch import cbranch
 
436
        return cbranch(source, target, lightweight=lightweight,
 
437
                       revision=revision, files_from=files_from,
 
438
                       hardlink=hardlink)
 
439
 
 
440
 
 
441
class cmd_list_branches(BzrToolsCommand):
 
442
    """Scan a location for branches"""
 
443
    @property
 
444
    def aliases(self):
 
445
        from bzrlib import commands
 
446
        return commands.plugin_cmds.get_info('list-branches').aliases
 
447
 
 
448
    takes_args = ["location?"]
 
449
    def run(self, location=None):
 
450
        from branches import branches
 
451
        return branches(location)
 
452
 
 
453
class cmd_trees(BzrToolsCommand):
 
454
    """Scan a location for trees"""
 
455
    takes_args = ['location?']
 
456
    def run(self, location='.'):
 
457
        from bzrlib.workingtree import WorkingTree
 
458
        from bzrlib.transport import get_transport
 
459
        t = get_transport(location)
 
460
        for tree in WorkingTree.find_trees(location):
 
461
            self.outf.write('%s\n' % t.relpath(
 
462
                tree.bzrdir.root_transport.base))
 
463
 
 
464
class cmd_multi_pull(BzrToolsCommand):
 
465
    """Pull all the branches under a location, e.g. a repository.
 
466
 
 
467
    Both branches present in the directory and the branches of checkouts are
 
468
    pulled.
 
469
    """
 
470
    takes_args = ["location?"]
 
471
    def run(self, location=None):
 
472
        from bzrlib.transport import get_transport
 
473
        from bzrtools import iter_branch_tree
 
474
        if location is None:
 
475
            location = '.'
 
476
        t = get_transport(location)
 
477
        possible_transports = []
 
478
        if not t.listable():
 
479
            print "Can't list this type of location."
 
480
            return 3
 
481
        for branch, wt in iter_branch_tree(t):
 
482
            if wt is None:
 
483
                pullable = branch
 
484
            else:
 
485
                pullable = wt
 
486
            parent = branch.get_parent()
 
487
            if parent is None:
 
488
                continue
 
489
            if wt is not None:
 
490
                base = wt.basedir
 
491
            else:
 
492
                base = branch.base
 
493
            if base.startswith(t.base):
 
494
                relpath = base[len(t.base):].rstrip('/')
 
495
            else:
 
496
                relpath = base
 
497
            print "Pulling %s from %s" % (relpath, parent)
 
498
            try:
 
499
                branch_t = get_transport(parent, possible_transports)
 
500
                pullable.pull(Branch.open_from_transport(branch_t))
 
501
            except Exception, e:
 
502
                print e
 
503
 
 
504
 
 
505
 
 
506
class cmd_import(BzrToolsCommand):
 
507
    """Import sources from a directory, tarball or zip file
 
508
 
 
509
    This command will import a directory, tarball or zip file into a bzr
 
510
    tree, replacing any versioned files already present.  If a directory is
 
511
    specified, it is used as the target.  If the directory does not exist, or
 
512
    is not versioned, it is created.
 
513
 
 
514
    Tarballs may be gzip or bzip2 compressed.  This is autodetected.
 
515
 
 
516
    If the tarball or zip has a single root directory, that directory is
 
517
    stripped when extracting the tarball.  This is not done for directories.
 
518
    """
 
519
 
 
520
    takes_args = ['source', 'tree?']
 
521
    def run(self, source, tree=None):
 
522
        from upstream_import import do_import
 
523
        do_import(source, tree)
 
524
 
 
525
 
 
526
class cmd_cdiff(BzrToolsCommand):
 
527
    """A color version of bzr's diff"""
 
528
    takes_args = property(lambda x: get_cmd_object('diff').takes_args)
 
529
    takes_options = list(get_cmd_object('diff').takes_options) + [
 
530
        RegistryOption.from_kwargs('color',
 
531
            'Color mode to use.',
 
532
            title='Color Mode', value_switches=False, enum_switch=True,
 
533
            never='Never colorize output.',
 
534
            auto='Only colorize output if terminal supports it and STDOUT is a'
 
535
            ' TTY.',
 
536
            always='Always colorize output (default).'),
 
537
        Option('check-style',
 
538
            help='Warn if trailing whitespace or spurious changes have been'
 
539
                 ' added.')]
 
540
 
 
541
    def run(self, color='always', check_style=False, *args, **kwargs):
 
542
        from colordiff import colordiff
 
543
        colordiff(color, check_style, *args, **kwargs)
 
544
 
 
545
 
 
546
class cmd_conflict_diff(BzrToolsCommand):
 
547
 
 
548
    """Compare a conflicted file against BASE."""
 
549
 
 
550
    encoding_type = 'exact'
 
551
    takes_args = ['file*']
 
552
    takes_options = [
 
553
        RegistryOption.from_kwargs('direction', 'Direction of comparison.',
 
554
            value_switches=True, enum_switch=False,
 
555
            other='Compare OTHER against common base.',
 
556
            this='Compare THIS against common base.')]
 
557
 
 
558
    def run(self, file_list, direction='other'):
 
559
        from bzrlib.plugins.bzrtools.colordiff import DiffWriter
 
560
        from conflict_diff import ConflictDiffer
 
561
        dw = DiffWriter(self.outf, check_style=False, color='auto')
 
562
        ConflictDiffer().run(dw, file_list, direction)
 
563
 
 
564
 
 
565
class cmd_rspush(BzrToolsCommand):
 
566
    """Upload this branch to another location using rsync.
 
567
 
 
568
    If no location is specified, the last-used location will be used.  To
 
569
    prevent dirty trees from being uploaded, rspush will error out if there are
 
570
    unknown files or local changes.  It will also error out if the upstream
 
571
    directory is non-empty and not an earlier version of the branch.
 
572
    """
 
573
    takes_args = ['location?']
 
574
    takes_options = [Option('overwrite', help='Ignore differences between'
 
575
                            ' branches and overwrite unconditionally.'),
 
576
                     Option('no-tree', help='Do not push the working tree,'
 
577
                            ' just the .bzr.')]
 
578
 
 
579
    def run(self, location=None, overwrite=False, no_tree=False):
 
580
        from bzrlib import workingtree
 
581
        import bzrtools
 
582
        cur_branch = workingtree.WorkingTree.open_containing(".")[0]
 
583
        bzrtools.rspush(cur_branch, location, overwrite=overwrite,
 
584
                      working_tree=not no_tree)
 
585
 
 
586
 
 
587
class cmd_link_tree(BzrToolsCommand):
 
588
    """Hardlink matching files to another tree.
 
589
 
 
590
    Only files with identical content and execute bit will be linked.
 
591
    """
 
592
    takes_args = ['location']
 
593
 
 
594
    def run(self, location):
 
595
        from bzrlib import workingtree
 
596
        from bzrlib.plugins.bzrtools.link_tree import link_tree
 
597
        target_tree = workingtree.WorkingTree.open_containing(".")[0]
 
598
        source_tree = workingtree.WorkingTree.open(location)
 
599
        target_tree.lock_write()
 
600
        try:
 
601
            source_tree.lock_read()
 
602
            try:
 
603
                link_tree(target_tree, source_tree)
 
604
            finally:
 
605
                source_tree.unlock()
 
606
        finally:
 
607
            target_tree.unlock()
 
608
 
 
609
 
 
610
class cmd_create_mirror(BzrToolsCommand):
 
611
    """Create a mirror of another branch.
 
612
 
 
613
    This is similar to `bzr branch`, but copies more settings, including the
 
614
    submit branch and nickname.
 
615
 
 
616
    It sets the public branch and parent of the target to the source location.
 
617
    """
 
618
 
 
619
    takes_args = ['source', 'target']
 
620
 
 
621
    def run(self, source, target):
 
622
        source_branch = Branch.open(source)
 
623
        from bzrlib.plugins.bzrtools.mirror import create_mirror
 
624
        create_mirror(source_branch, target, [])