/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
329 by Martin Pool
- refactor command functions into command classes
1
# Copyright (C) 2004, 2005 by Canonical Ltd
1 by mbp at sourcefrog
import from baz patch-364
2
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
18
# TODO: Split the command framework away from the actual commands.
19
20
# TODO: probably should say which arguments are candidates for glob
21
# expansion on windows and do that at the command level.
22
1095 by Martin Pool
todo
23
# TODO: Help messages for options.
24
25
# TODO: Define arguments by objects, rather than just using names.
26
# Those objects can specify the expected type of the argument, which
27
# would help with validation and shell completion.
28
29
1092.1.39 by Robert Collins
merge from mpool
30
# TODO: Help messages for options.
31
32
# TODO: Define arguments by objects, rather than just using names.
33
# Those objects can specify the expected type of the argument, which
34
# would help with validation and shell completion.
35
36
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
37
import sys
38
import os
1 by mbp at sourcefrog
import from baz patch-364
39
40
import bzrlib
1112 by Martin Pool
- disable standard logging to .bzr.log and stderr while running
41
import bzrlib.trace
897 by Martin Pool
- merge john's revision-naming code
42
from bzrlib.trace import mutter, note, log_error, warning
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
43
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
800 by Martin Pool
Merge John's import-speedup branch:
44
from bzrlib.branch import find_branch
45
from bzrlib import BZRDIR
1 by mbp at sourcefrog
import from baz patch-364
46
47
731 by Martin Pool
- merge plugin patch from john
48
plugin_cmds = {}
49
50
759 by Martin Pool
- fix up register_command() names
51
def register_command(cmd):
731 by Martin Pool
- merge plugin patch from john
52
    "Utility function to help register a command"
53
    global plugin_cmds
54
    k = cmd.__name__
55
    if k.startswith("cmd_"):
56
        k_unsquished = _unsquish_command_name(k)
57
    else:
58
        k_unsquished = k
59
    if not plugin_cmds.has_key(k_unsquished):
60
        plugin_cmds[k_unsquished] = cmd
61
    else:
62
        log_error('Two plugins defined the same command: %r' % k)
63
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
64
65
350 by Martin Pool
- refactor command aliases into command classes
66
def _squish_command_name(cmd):
67
    return 'cmd_' + cmd.replace('-', '_')
68
69
70
def _unsquish_command_name(cmd):
71
    assert cmd.startswith("cmd_")
72
    return cmd[4:].replace('_','-')
73
914 by Martin Pool
- fix up breakage of 'bzr log -v' by root_id patch
74
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
75
def _parse_revision_str(revstr):
914 by Martin Pool
- fix up breakage of 'bzr log -v' by root_id patch
76
    """This handles a revision string -> revno.
77
78
    This always returns a list.  The list will have one element for 
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
79
897 by Martin Pool
- merge john's revision-naming code
80
    It supports integers directly, but everything else it
81
    defers for passing to Branch.get_revision_info()
82
83
    >>> _parse_revision_str('234')
84
    [234]
85
    >>> _parse_revision_str('234..567')
86
    [234, 567]
87
    >>> _parse_revision_str('..')
88
    [None, None]
89
    >>> _parse_revision_str('..234')
90
    [None, 234]
91
    >>> _parse_revision_str('234..')
92
    [234, None]
93
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
94
    [234, 456, 789]
95
    >>> _parse_revision_str('234....789') # Error?
96
    [234, None, 789]
97
    >>> _parse_revision_str('revid:test@other.com-234234')
98
    ['revid:test@other.com-234234']
99
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
100
    ['revid:test@other.com-234234', 'revid:test@other.com-234235']
101
    >>> _parse_revision_str('revid:test@other.com-234234..23')
102
    ['revid:test@other.com-234234', 23]
103
    >>> _parse_revision_str('date:2005-04-12')
104
    ['date:2005-04-12']
105
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
106
    ['date:2005-04-12 12:24:33']
107
    >>> _parse_revision_str('date:2005-04-12T12:24:33')
108
    ['date:2005-04-12T12:24:33']
109
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
110
    ['date:2005-04-12,12:24:33']
111
    >>> _parse_revision_str('-5..23')
112
    [-5, 23]
113
    >>> _parse_revision_str('-5')
114
    [-5]
115
    >>> _parse_revision_str('123a')
116
    ['123a']
117
    >>> _parse_revision_str('abc')
118
    ['abc']
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
119
    """
897 by Martin Pool
- merge john's revision-naming code
120
    import re
121
    old_format_re = re.compile('\d*:\d*')
122
    m = old_format_re.match(revstr)
123
    if m:
124
        warning('Colon separator for revision numbers is deprecated.'
125
                ' Use .. instead')
126
        revs = []
127
        for rev in revstr.split(':'):
128
            if rev:
129
                revs.append(int(rev))
130
            else:
131
                revs.append(None)
132
        return revs
133
    revs = []
134
    for x in revstr.split('..'):
135
        if not x:
136
            revs.append(None)
137
        else:
138
            try:
139
                revs.append(int(x))
140
            except ValueError:
141
                revs.append(x)
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
142
    return revs
143
731 by Martin Pool
- merge plugin patch from john
144
974.1.9 by Aaron Bentley
Added merge-type parameter to merge.
145
def get_merge_type(typestring):
146
    """Attempt to find the merge class/factory associated with a string."""
147
    from merge import merge_types
148
    try:
149
        return merge_types[typestring][0]
150
    except KeyError:
151
        templ = '%s%%7s: %%s' % (' '*12)
152
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
153
        type_list = '\n'.join(lines)
154
        msg = "No known merge type %s. Supported types are:\n%s" %\
155
            (typestring, type_list)
156
        raise BzrCommandError(msg)
157
    
158
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
159
def get_merge_type(typestring):
160
    """Attempt to find the merge class/factory associated with a string."""
161
    from merge import merge_types
162
    try:
163
        return merge_types[typestring][0]
164
    except KeyError:
165
        templ = '%s%%7s: %%s' % (' '*12)
166
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
167
        type_list = '\n'.join(lines)
168
        msg = "No known merge type %s. Supported types are:\n%s" %\
169
            (typestring, type_list)
170
        raise BzrCommandError(msg)
171
    
172
731 by Martin Pool
- merge plugin patch from john
173
174
def _get_cmd_dict(plugins_override=True):
641 by Martin Pool
- improved external-command patch from john
175
    d = {}
350 by Martin Pool
- refactor command aliases into command classes
176
    for k, v in globals().iteritems():
177
        if k.startswith("cmd_"):
641 by Martin Pool
- improved external-command patch from john
178
            d[_unsquish_command_name(k)] = v
731 by Martin Pool
- merge plugin patch from john
179
    # If we didn't load plugins, the plugin_cmds dict will be empty
180
    if plugins_override:
181
        d.update(plugin_cmds)
182
    else:
183
        d2 = plugin_cmds.copy()
184
        d2.update(d)
185
        d = d2
641 by Martin Pool
- improved external-command patch from john
186
    return d
731 by Martin Pool
- merge plugin patch from john
187
641 by Martin Pool
- improved external-command patch from john
188
    
731 by Martin Pool
- merge plugin patch from john
189
def get_all_cmds(plugins_override=True):
641 by Martin Pool
- improved external-command patch from john
190
    """Return canonical name and class for all registered commands."""
731 by Martin Pool
- merge plugin patch from john
191
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
641 by Martin Pool
- improved external-command patch from john
192
        yield k,v
193
194
731 by Martin Pool
- merge plugin patch from john
195
def get_cmd_class(cmd, plugins_override=True):
350 by Martin Pool
- refactor command aliases into command classes
196
    """Return the canonical name and command class for a command.
197
    """
198
    cmd = str(cmd)                      # not unicode
199
200
    # first look up this command under the specified name
731 by Martin Pool
- merge plugin patch from john
201
    cmds = _get_cmd_dict(plugins_override=plugins_override)
272 by Martin Pool
- Add command aliases
202
    try:
641 by Martin Pool
- improved external-command patch from john
203
        return cmd, cmds[cmd]
272 by Martin Pool
- Add command aliases
204
    except KeyError:
350 by Martin Pool
- refactor command aliases into command classes
205
        pass
206
207
    # look for any command which claims this as an alias
641 by Martin Pool
- improved external-command patch from john
208
    for cmdname, cmdclass in cmds.iteritems():
350 by Martin Pool
- refactor command aliases into command classes
209
        if cmd in cmdclass.aliases:
210
            return cmdname, cmdclass
422 by Martin Pool
- External-command patch from mpe
211
212
    cmdclass = ExternalCommand.find_command(cmd)
213
    if cmdclass:
214
        return cmd, cmdclass
215
216
    raise BzrCommandError("unknown command %r" % cmd)
272 by Martin Pool
- Add command aliases
217
329 by Martin Pool
- refactor command functions into command classes
218
558 by Martin Pool
- All top-level classes inherit from object
219
class Command(object):
329 by Martin Pool
- refactor command functions into command classes
220
    """Base class for commands.
221
222
    The docstring for an actual command should give a single-line
223
    summary, then a complete description of the command.  A grammar
224
    description will be inserted.
225
226
    takes_args
227
        List of argument forms, marked with whether they are optional,
228
        repeated, etc.
229
230
    takes_options
231
        List of options that may be given for this command.
232
233
    hidden
234
        If true, this command isn't advertised.
235
    """
236
    aliases = []
237
    
238
    takes_args = []
239
    takes_options = []
240
241
    hidden = False
242
    
243
    def __init__(self, options, arguments):
244
        """Construct and run the command.
245
246
        Sets self.status to the return value of run()."""
247
        assert isinstance(options, dict)
248
        assert isinstance(arguments, dict)
249
        cmdargs = options.copy()
250
        cmdargs.update(arguments)
973 by Martin Pool
- various refactorings of command interpreter
251
        if self.__doc__ == Command.__doc__:
252
            from warnings import warn
253
            warn("No help message set for %r" % self)
329 by Martin Pool
- refactor command functions into command classes
254
        self.status = self.run(**cmdargs)
974 by Martin Pool
- start adding tests for commit in subdir
255
        if self.status is None:
256
            self.status = 0
329 by Martin Pool
- refactor command functions into command classes
257
258
    
259
    def run(self):
260
        """Override this in sub-classes.
261
262
        This is invoked with the options and arguments bound to
263
        keyword parameters.
264
337 by Martin Pool
- Clarify return codes from command objects
265
        Return 0 or None if the command was successful, or a shell
266
        error code if not.
329 by Martin Pool
- refactor command functions into command classes
267
        """
337 by Martin Pool
- Clarify return codes from command objects
268
        return 0
329 by Martin Pool
- refactor command functions into command classes
269
270
422 by Martin Pool
- External-command patch from mpe
271
class ExternalCommand(Command):
272
    """Class to wrap external commands.
273
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
274
    We cheat a little here, when get_cmd_class() calls us we actually
275
    give it back an object we construct that has the appropriate path,
276
    help, options etc for the specified command.
277
278
    When run_bzr() tries to instantiate that 'class' it gets caught by
279
    the __call__ method, which we override to call the Command.__init__
280
    method. That then calls our run method which is pretty straight
281
    forward.
282
283
    The only wrinkle is that we have to map bzr's dictionary of options
284
    and arguments back into command line options and arguments for the
285
    script.
422 by Martin Pool
- External-command patch from mpe
286
    """
287
288
    def find_command(cls, cmd):
572 by Martin Pool
- trim imports
289
        import os.path
422 by Martin Pool
- External-command patch from mpe
290
        bzrpath = os.environ.get('BZRPATH', '')
291
641 by Martin Pool
- improved external-command patch from john
292
        for dir in bzrpath.split(os.pathsep):
422 by Martin Pool
- External-command patch from mpe
293
            path = os.path.join(dir, cmd)
294
            if os.path.isfile(path):
295
                return ExternalCommand(path)
296
297
        return None
298
299
    find_command = classmethod(find_command)
300
301
    def __init__(self, path):
302
        self.path = path
303
304
        pipe = os.popen('%s --bzr-usage' % path, 'r')
305
        self.takes_options = pipe.readline().split()
687 by Martin Pool
- trap more errors from external commands
306
307
        for opt in self.takes_options:
308
            if not opt in OPTIONS:
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
309
                raise BzrError("Unknown option '%s' returned by external command %s"
310
                               % (opt, path))
687 by Martin Pool
- trap more errors from external commands
311
312
        # TODO: Is there any way to check takes_args is valid here?
422 by Martin Pool
- External-command patch from mpe
313
        self.takes_args = pipe.readline().split()
687 by Martin Pool
- trap more errors from external commands
314
315
        if pipe.close() is not None:
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
316
            raise BzrError("Failed funning '%s --bzr-usage'" % path)
422 by Martin Pool
- External-command patch from mpe
317
318
        pipe = os.popen('%s --bzr-help' % path, 'r')
319
        self.__doc__ = pipe.read()
687 by Martin Pool
- trap more errors from external commands
320
        if pipe.close() is not None:
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
321
            raise BzrError("Failed funning '%s --bzr-help'" % path)
422 by Martin Pool
- External-command patch from mpe
322
323
    def __call__(self, options, arguments):
324
        Command.__init__(self, options, arguments)
325
        return self
326
327
    def run(self, **kargs):
328
        opts = []
329
        args = []
330
331
        keys = kargs.keys()
332
        keys.sort()
333
        for name in keys:
689 by Martin Pool
- make options with - work with external commands
334
            optname = name.replace('_','-')
422 by Martin Pool
- External-command patch from mpe
335
            value = kargs[name]
689 by Martin Pool
- make options with - work with external commands
336
            if OPTIONS.has_key(optname):
422 by Martin Pool
- External-command patch from mpe
337
                # it's an option
689 by Martin Pool
- make options with - work with external commands
338
                opts.append('--%s' % optname)
422 by Martin Pool
- External-command patch from mpe
339
                if value is not None and value is not True:
340
                    opts.append(str(value))
341
            else:
342
                # it's an arg, or arg list
343
                if type(value) is not list:
344
                    value = [value]
345
                for v in value:
346
                    if v is not None:
347
                        args.append(str(v))
348
349
        self.status = os.spawnv(os.P_WAIT, self.path, [self.path] + opts + args)
350
        return self.status
351
329 by Martin Pool
- refactor command functions into command classes
352
353
class cmd_status(Command):
1 by mbp at sourcefrog
import from baz patch-364
354
    """Display status summary.
355
466 by Martin Pool
- doc for status command
356
    This reports on versioned and unknown files, reporting them
357
    grouped by state.  Possible states are:
358
359
    added
360
        Versioned in the working copy but not in the previous revision.
361
362
    removed
467 by Martin Pool
- doc for status command
363
        Versioned in the previous revision but removed or deleted
466 by Martin Pool
- doc for status command
364
        in the working copy.
365
366
    renamed
367
        Path of this file changed from the previous revision;
368
        the text may also have changed.  This includes files whose
467 by Martin Pool
- doc for status command
369
        parent directory was renamed.
466 by Martin Pool
- doc for status command
370
371
    modified
372
        Text has changed since the previous revision.
373
374
    unchanged
467 by Martin Pool
- doc for status command
375
        Nothing about this file has changed since the previous revision.
376
        Only shown with --all.
466 by Martin Pool
- doc for status command
377
378
    unknown
379
        Not versioned and not matching an ignore pattern.
380
381
    To see ignored files use 'bzr ignored'.  For details in the
382
    changes to file texts, use 'bzr diff'.
468 by Martin Pool
- Interpret arguments to bzr status
383
384
    If no arguments are specified, the status of the entire working
385
    directory is shown.  Otherwise, only the status of the specified
386
    files or directories is reported.  If a directory is given, status
387
    is reported for everything inside that directory.
914 by Martin Pool
- fix up breakage of 'bzr log -v' by root_id patch
388
389
    If a revision is specified, the changes since that revision are shown.
1 by mbp at sourcefrog
import from baz patch-364
390
    """
404 by Martin Pool
- bzr status now optionally takes filenames to check
391
    takes_args = ['file*']
914 by Martin Pool
- fix up breakage of 'bzr log -v' by root_id patch
392
    takes_options = ['all', 'show-ids', 'revision']
350 by Martin Pool
- refactor command aliases into command classes
393
    aliases = ['st', 'stat']
329 by Martin Pool
- refactor command functions into command classes
394
    
465 by Martin Pool
- Move show_status() out of Branch into a new function in
395
    def run(self, all=False, show_ids=False, file_list=None):
468 by Martin Pool
- Interpret arguments to bzr status
396
        if file_list:
800 by Martin Pool
Merge John's import-speedup branch:
397
            b = find_branch(file_list[0])
468 by Martin Pool
- Interpret arguments to bzr status
398
            file_list = [b.relpath(x) for x in file_list]
399
            # special case: only one path was given and it's the root
400
            # of the branch
401
            if file_list == ['']:
402
                file_list = None
403
        else:
800 by Martin Pool
Merge John's import-speedup branch:
404
            b = find_branch('.')
914 by Martin Pool
- fix up breakage of 'bzr log -v' by root_id patch
405
            
406
        from bzrlib.status import show_status
407
        show_status(b, show_unchanged=all, show_ids=show_ids,
408
                    specific_files=file_list)
329 by Martin Pool
- refactor command functions into command classes
409
410
411
class cmd_cat_revision(Command):
412
    """Write out metadata for a revision."""
413
414
    hidden = True
415
    takes_args = ['revision_id']
416
    
417
    def run(self, revision_id):
802 by Martin Pool
- Remove XMLMixin class in favour of simple pack_xml, unpack_xml functions
418
        from bzrlib.xml import pack_xml
419
        pack_xml(find_branch('.').get_revision(revision_id), sys.stdout)
329 by Martin Pool
- refactor command functions into command classes
420
421
422
class cmd_revno(Command):
423
    """Show current revision number.
424
425
    This is equal to the number of revisions on this branch."""
426
    def run(self):
800 by Martin Pool
Merge John's import-speedup branch:
427
        print find_branch('.').revno()
329 by Martin Pool
- refactor command functions into command classes
428
897 by Martin Pool
- merge john's revision-naming code
429
class cmd_revision_info(Command):
430
    """Show revision number and revision id for a given revision identifier.
431
    """
432
    hidden = True
433
    takes_args = ['revision_info*']
434
    takes_options = ['revision']
435
    def run(self, revision=None, revision_info_list=None):
436
        from bzrlib.branch import find_branch
437
438
        revs = []
439
        if revision is not None:
440
            revs.extend(revision)
441
        if revision_info_list is not None:
442
            revs.extend(revision_info_list)
443
        if len(revs) == 0:
444
            raise BzrCommandError('You must supply a revision identifier')
445
446
        b = find_branch('.')
447
448
        for rev in revs:
449
            print '%4d %s' % b.get_revision_info(rev)
450
329 by Martin Pool
- refactor command functions into command classes
451
    
452
class cmd_add(Command):
70 by mbp at sourcefrog
Prepare for smart recursive add.
453
    """Add specified files or directories.
454
455
    In non-recursive mode, all the named items are added, regardless
456
    of whether they were previously ignored.  A warning is given if
457
    any of the named files are already versioned.
458
459
    In recursive mode (the default), files are treated the same way
460
    but the behaviour for directories is different.  Directories that
461
    are already versioned do not give a warning.  All directories,
462
    whether already versioned or not, are searched for files or
463
    subdirectories that are neither versioned or ignored, and these
464
    are added.  This search proceeds recursively into versioned
973 by Martin Pool
- various refactorings of command interpreter
465
    directories.  If no names are given '.' is assumed.
70 by mbp at sourcefrog
Prepare for smart recursive add.
466
973 by Martin Pool
- various refactorings of command interpreter
467
    Therefore simply saying 'bzr add' will version all files that
70 by mbp at sourcefrog
Prepare for smart recursive add.
468
    are currently unknown.
279 by Martin Pool
todo
469
470
    TODO: Perhaps adding a file whose directly is not versioned should
471
    recursively add that parent, rather than giving an error?
70 by mbp at sourcefrog
Prepare for smart recursive add.
472
    """
973 by Martin Pool
- various refactorings of command interpreter
473
    takes_args = ['file*']
594 by Martin Pool
- add --no-recurse option for add command
474
    takes_options = ['verbose', 'no-recurse']
329 by Martin Pool
- refactor command functions into command classes
475
    
594 by Martin Pool
- add --no-recurse option for add command
476
    def run(self, file_list, verbose=False, no_recurse=False):
1092.1.30 by Robert Collins
change smart_add reporting of added files to callback with the entry, and change the inventory.add signature to return the added entry
477
        from bzrlib.add import smart_add, _PrintAddCallback
478
        smart_add(file_list, verbose, not no_recurse,
479
                  callback=_PrintAddCallback)
329 by Martin Pool
- refactor command functions into command classes
480
481
742 by Martin Pool
- new mkdir command
482
483
class cmd_mkdir(Command):
484
    """Create a new versioned directory.
485
486
    This is equivalent to creating the directory and then adding it.
487
    """
488
    takes_args = ['dir+']
489
490
    def run(self, dir_list):
491
        b = None
492
        
493
        for d in dir_list:
494
            os.mkdir(d)
495
            if not b:
800 by Martin Pool
Merge John's import-speedup branch:
496
                b = find_branch(d)
742 by Martin Pool
- new mkdir command
497
            b.add([d], verbose=True)
498
499
386 by Martin Pool
- Typo (reported by uws)
500
class cmd_relpath(Command):
329 by Martin Pool
- refactor command functions into command classes
501
    """Show path of a file relative to root"""
392 by Martin Pool
- fix relpath and add tests
502
    takes_args = ['filename']
584 by Martin Pool
- make relpath and revision-history hidden commands
503
    hidden = True
329 by Martin Pool
- refactor command functions into command classes
504
    
392 by Martin Pool
- fix relpath and add tests
505
    def run(self, filename):
800 by Martin Pool
Merge John's import-speedup branch:
506
        print find_branch(filename).relpath(filename)
329 by Martin Pool
- refactor command functions into command classes
507
508
509
510
class cmd_inventory(Command):
511
    """Show inventory of the current working copy or a revision."""
588 by Martin Pool
- change inventory command to not show ids by default
512
    takes_options = ['revision', 'show-ids']
329 by Martin Pool
- refactor command functions into command classes
513
    
588 by Martin Pool
- change inventory command to not show ids by default
514
    def run(self, revision=None, show_ids=False):
800 by Martin Pool
Merge John's import-speedup branch:
515
        b = find_branch('.')
329 by Martin Pool
- refactor command functions into command classes
516
        if revision == None:
517
            inv = b.read_working_inventory()
518
        else:
897 by Martin Pool
- merge john's revision-naming code
519
            if len(revision) > 1:
520
                raise BzrCommandError('bzr inventory --revision takes'
521
                    ' exactly one revision identifier')
522
            inv = b.get_revision_inventory(b.lookup_revision(revision[0]))
329 by Martin Pool
- refactor command functions into command classes
523
556 by Martin Pool
- fix up Inventory.entries()
524
        for path, entry in inv.entries():
588 by Martin Pool
- change inventory command to not show ids by default
525
            if show_ids:
526
                print '%-50s %s' % (path, entry.file_id)
527
            else:
528
                print path
329 by Martin Pool
- refactor command functions into command classes
529
530
531
class cmd_move(Command):
532
    """Move files to a different directory.
533
534
    examples:
535
        bzr move *.txt doc
536
537
    The destination must be a versioned directory in the same branch.
538
    """
539
    takes_args = ['source$', 'dest']
540
    def run(self, source_list, dest):
800 by Martin Pool
Merge John's import-speedup branch:
541
        b = find_branch('.')
329 by Martin Pool
- refactor command functions into command classes
542
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
543
        # TODO: glob expansion on windows?
329 by Martin Pool
- refactor command functions into command classes
544
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
545
546
547
class cmd_rename(Command):
168 by mbp at sourcefrog
new "rename" command
548
    """Change the name of an entry.
549
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
550
    examples:
551
      bzr rename frob.c frobber.c
552
      bzr rename src/frob.c lib/frob.c
553
554
    It is an error if the destination name exists.
555
556
    See also the 'move' command, which moves files into a different
557
    directory without changing their name.
558
559
    TODO: Some way to rename multiple files without invoking bzr for each
560
    one?"""
329 by Martin Pool
- refactor command functions into command classes
561
    takes_args = ['from_name', 'to_name']
168 by mbp at sourcefrog
new "rename" command
562
    
329 by Martin Pool
- refactor command functions into command classes
563
    def run(self, from_name, to_name):
800 by Martin Pool
Merge John's import-speedup branch:
564
        b = find_branch('.')
329 by Martin Pool
- refactor command functions into command classes
565
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
566
567
568
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
569
class cmd_mv(Command):
570
    """Move or rename a file.
571
572
    usage:
573
        bzr mv OLDNAME NEWNAME
574
        bzr mv SOURCE... DESTINATION
575
576
    If the last argument is a versioned directory, all the other names
577
    are moved into it.  Otherwise, there must be exactly two arguments
578
    and the file is changed to a new name, which must not already exist.
579
580
    Files cannot be moved between branches.
581
    """
582
    takes_args = ['names*']
583
    def run(self, names_list):
584
        if len(names_list) < 2:
585
            raise BzrCommandError("missing file argument")
586
        b = find_branch(names_list[0])
587
588
        rel_names = [b.relpath(x) for x in names_list]
589
        
590
        if os.path.isdir(names_list[-1]):
591
            # move into existing directory
592
            b.move(rel_names[:-1], rel_names[-1])
593
        else:
594
            if len(names_list) != 2:
595
                raise BzrCommandError('to mv multiple files the destination '
596
                                      'must be a versioned directory')
597
            b.move(rel_names[0], rel_names[1])
598
            
599
    
628 by Martin Pool
- merge aaron's updated merge/pull code
600
601
602
class cmd_pull(Command):
603
    """Pull any changes from another branch into the current one.
604
605
    If the location is omitted, the last-used location will be used.
606
    Both the revision history and the working directory will be
607
    updated.
608
609
    This command only works on branches that have not diverged.  Branches are
610
    considered diverged if both branches have had commits without first
611
    pulling from the other.
612
613
    If branches have diverged, you can use 'bzr merge' to pull the text changes
614
    from one into the other.
615
    """
616
    takes_args = ['location?']
617
618
    def run(self, location=None):
619
        from bzrlib.merge import merge
790 by Martin Pool
Merge from aaron:
620
        import tempfile
621
        from shutil import rmtree
628 by Martin Pool
- merge aaron's updated merge/pull code
622
        import errno
1092.1.34 by Robert Collins
unbreak cmd_branch now that something tests the core of it..
623
        from bzrlib.branch import pull_loc
628 by Martin Pool
- merge aaron's updated merge/pull code
624
        
800 by Martin Pool
Merge John's import-speedup branch:
625
        br_to = find_branch('.')
628 by Martin Pool
- merge aaron's updated merge/pull code
626
        stored_loc = None
627
        try:
628
            stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
629
        except IOError, e:
789 by Martin Pool
- patch from john to cope with branches with missing x-pull file
630
            if e.errno != errno.ENOENT:
628 by Martin Pool
- merge aaron's updated merge/pull code
631
                raise
632
        if location is None:
729 by Martin Pool
- pull shows location being used
633
            if stored_loc is None:
634
                raise BzrCommandError("No pull location known or specified.")
635
            else:
636
                print "Using last location: %s" % stored_loc
637
                location = stored_loc
790 by Martin Pool
Merge from aaron:
638
        cache_root = tempfile.mkdtemp()
800 by Martin Pool
Merge John's import-speedup branch:
639
        from bzrlib.branch import DivergedBranches
640
        br_from = find_branch(location)
641
        location = pull_loc(br_from)
642
        old_revno = br_to.revno()
628 by Martin Pool
- merge aaron's updated merge/pull code
643
        try:
790 by Martin Pool
Merge from aaron:
644
            from branch import find_cached_branch, DivergedBranches
645
            br_from = find_cached_branch(location, cache_root)
646
            location = pull_loc(br_from)
647
            old_revno = br_to.revno()
648
            try:
649
                br_to.update_revisions(br_from)
650
            except DivergedBranches:
651
                raise BzrCommandError("These branches have diverged."
652
                    "  Try merge.")
653
                
654
            merge(('.', -1), ('.', old_revno), check_clean=False)
655
            if location != stored_loc:
656
                br_to.controlfile("x-pull", "wb").write(location + "\n")
657
        finally:
658
            rmtree(cache_root)
628 by Martin Pool
- merge aaron's updated merge/pull code
659
660
661
662
class cmd_branch(Command):
663
    """Create a new copy of a branch.
664
685 by Martin Pool
- add -r option to the branch command
665
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
666
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
667
668
    To retrieve the branch as of a particular revision, supply the --revision
669
    parameter, as in "branch foo/bar -r 5".
628 by Martin Pool
- merge aaron's updated merge/pull code
670
    """
671
    takes_args = ['from_location', 'to_location?']
685 by Martin Pool
- add -r option to the branch command
672
    takes_options = ['revision']
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
673
    aliases = ['get', 'clone']
628 by Martin Pool
- merge aaron's updated merge/pull code
674
685 by Martin Pool
- add -r option to the branch command
675
    def run(self, from_location, to_location=None, revision=None):
1092.1.33 by Robert Collins
pull the important stuff out of cmd_branch.run to branch.copy_branch
676
        from bzrlib.branch import copy_branch, find_cached_branch
677
        import tempfile
628 by Martin Pool
- merge aaron's updated merge/pull code
678
        import errno
1092.1.36 by Robert Collins
should run tests before committing, tsk. move an import to fix
679
        from shutil import rmtree
790 by Martin Pool
Merge from aaron:
680
        cache_root = tempfile.mkdtemp()
681
        try:
1092.1.33 by Robert Collins
pull the important stuff out of cmd_branch.run to branch.copy_branch
682
            if revision is None:
683
                revision = [None]
684
            elif len(revision) > 1:
685
                raise BzrCommandError(
686
                    'bzr branch --revision takes exactly 1 revision value')
790 by Martin Pool
Merge from aaron:
687
            try:
688
                br_from = find_cached_branch(from_location, cache_root)
689
            except OSError, e:
690
                if e.errno == errno.ENOENT:
691
                    raise BzrCommandError('Source location "%s" does not'
692
                                          ' exist.' % to_location)
693
                else:
694
                    raise
695
            if to_location is None:
696
                to_location = os.path.basename(from_location.rstrip("/\\"))
697
            try:
698
                os.mkdir(to_location)
699
            except OSError, e:
700
                if e.errno == errno.EEXIST:
701
                    raise BzrCommandError('Target directory "%s" already'
702
                                          ' exists.' % to_location)
703
                if e.errno == errno.ENOENT:
704
                    raise BzrCommandError('Parent of "%s" does not exist.' %
705
                                          to_location)
706
                else:
707
                    raise
1092.1.33 by Robert Collins
pull the important stuff out of cmd_branch.run to branch.copy_branch
708
            try:
709
                copy_branch(br_from, to_location, revision[0])
710
            except bzrlib.errors.NoSuchRevision:
711
                rmtree(to_location)
712
                msg = "The branch %s has no revision %d." % (from_location, revision[0])
713
                raise BzrCommandError(msg)
790 by Martin Pool
Merge from aaron:
714
        finally:
715
            rmtree(cache_root)
628 by Martin Pool
- merge aaron's updated merge/pull code
716
717
329 by Martin Pool
- refactor command functions into command classes
718
class cmd_renames(Command):
164 by mbp at sourcefrog
new 'renames' command
719
    """Show list of renamed files.
720
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
721
    TODO: Option to show renames between two historical versions.
722
723
    TODO: Only show renames under dir, rather than in the whole branch.
724
    """
329 by Martin Pool
- refactor command functions into command classes
725
    takes_args = ['dir?']
726
727
    def run(self, dir='.'):
800 by Martin Pool
Merge John's import-speedup branch:
728
        b = find_branch(dir)
329 by Martin Pool
- refactor command functions into command classes
729
        old_inv = b.basis_tree().inventory
730
        new_inv = b.read_working_inventory()
731
732
        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
733
        renames.sort()
734
        for old_name, new_name in renames:
735
            print "%s => %s" % (old_name, new_name)        
736
737
738
class cmd_info(Command):
472 by Martin Pool
- Optional branch parameter to info command
739
    """Show statistical information about a branch."""
740
    takes_args = ['branch?']
741
    
742
    def run(self, branch=None):
329 by Martin Pool
- refactor command functions into command classes
743
        import info
472 by Martin Pool
- Optional branch parameter to info command
744
745
        b = find_branch(branch)
746
        info.show_info(b)
329 by Martin Pool
- refactor command functions into command classes
747
748
749
class cmd_remove(Command):
750
    """Make a file unversioned.
751
752
    This makes bzr stop tracking changes to a versioned file.  It does
753
    not delete the working copy.
754
    """
755
    takes_args = ['file+']
756
    takes_options = ['verbose']
757
    
758
    def run(self, file_list, verbose=False):
800 by Martin Pool
Merge John's import-speedup branch:
759
        b = find_branch(file_list[0])
329 by Martin Pool
- refactor command functions into command classes
760
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
761
762
763
class cmd_file_id(Command):
178 by mbp at sourcefrog
- Use a non-null file_id for the branch root directory. At the moment
764
    """Print file_id of a particular file or directory.
765
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
766
    The file_id is assigned when the file is first added and remains the
767
    same through all revisions where the file exists, even when it is
768
    moved or renamed.
769
    """
329 by Martin Pool
- refactor command functions into command classes
770
    hidden = True
771
    takes_args = ['filename']
772
    def run(self, filename):
800 by Martin Pool
Merge John's import-speedup branch:
773
        b = find_branch(filename)
329 by Martin Pool
- refactor command functions into command classes
774
        i = b.inventory.path2id(b.relpath(filename))
775
        if i == None:
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
776
            raise BzrError("%r is not a versioned file" % filename)
329 by Martin Pool
- refactor command functions into command classes
777
        else:
778
            print i
779
780
781
class cmd_file_path(Command):
178 by mbp at sourcefrog
- Use a non-null file_id for the branch root directory. At the moment
782
    """Print path of file_ids to a file or directory.
783
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
784
    This prints one line for each directory down to the target,
785
    starting at the branch root."""
329 by Martin Pool
- refactor command functions into command classes
786
    hidden = True
787
    takes_args = ['filename']
788
    def run(self, filename):
800 by Martin Pool
Merge John's import-speedup branch:
789
        b = find_branch(filename)
329 by Martin Pool
- refactor command functions into command classes
790
        inv = b.inventory
791
        fid = inv.path2id(b.relpath(filename))
792
        if fid == None:
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
793
            raise BzrError("%r is not a versioned file" % filename)
329 by Martin Pool
- refactor command functions into command classes
794
        for fip in inv.get_idpath(fid):
795
            print fip
796
797
798
class cmd_revision_history(Command):
799
    """Display list of revision ids on this branch."""
584 by Martin Pool
- make relpath and revision-history hidden commands
800
    hidden = True
329 by Martin Pool
- refactor command functions into command classes
801
    def run(self):
800 by Martin Pool
Merge John's import-speedup branch:
802
        for patchid in find_branch('.').revision_history():
329 by Martin Pool
- refactor command functions into command classes
803
            print patchid
804
805
806
class cmd_directories(Command):
807
    """Display list of versioned directories in this branch."""
808
    def run(self):
800 by Martin Pool
Merge John's import-speedup branch:
809
        for name, ie in find_branch('.').read_working_inventory().directories():
329 by Martin Pool
- refactor command functions into command classes
810
            if name == '':
811
                print '.'
812
            else:
813
                print name
814
815
816
class cmd_init(Command):
817
    """Make a directory into a versioned branch.
818
819
    Use this to create an empty branch, or before importing an
820
    existing project.
821
822
    Recipe for importing a tree of files:
823
        cd ~/project
824
        bzr init
825
        bzr add -v .
826
        bzr status
827
        bzr commit -m 'imported project'
828
    """
829
    def run(self):
800 by Martin Pool
Merge John's import-speedup branch:
830
        from bzrlib.branch import Branch
329 by Martin Pool
- refactor command functions into command classes
831
        Branch('.', init=True)
832
833
834
class cmd_diff(Command):
835
    """Show differences in working tree.
836
    
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
837
    If files are listed, only the changes in those files are listed.
838
    Otherwise, all changes for the tree are listed.
839
840
    TODO: Allow diff across branches.
841
842
    TODO: Option to use external diff command; could be GNU diff, wdiff,
843
          or a graphical diff.
844
276 by Martin Pool
Doc
845
    TODO: Python difflib is not exactly the same as unidiff; should
846
          either fix it up or prefer to use an external diff.
847
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
848
    TODO: If a directory is given, diff everything under that.
849
276 by Martin Pool
Doc
850
    TODO: Selected-file diff is inefficient and doesn't show you
851
          deleted files.
278 by Martin Pool
- Better workaround for trailing newlines in diffs
852
853
    TODO: This probably handles non-Unix newlines poorly.
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
854
855
    examples:
856
        bzr diff
857
        bzr diff -r1
858
        bzr diff -r1:2
329 by Martin Pool
- refactor command functions into command classes
859
    """
860
    
861
    takes_args = ['file*']
571 by Martin Pool
- new --diff-options to pass options through to external
862
    takes_options = ['revision', 'diff-options']
638 by Martin Pool
- add 'dif' as alias for 'diff' command
863
    aliases = ['di', 'dif']
329 by Martin Pool
- refactor command functions into command classes
864
571 by Martin Pool
- new --diff-options to pass options through to external
865
    def run(self, revision=None, file_list=None, diff_options=None):
329 by Martin Pool
- refactor command functions into command classes
866
        from bzrlib.diff import show_diff
547 by Martin Pool
- bzr diff finds a branch from the first parameter,
867
868
        if file_list:
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
869
            b = find_branch(file_list[0])
547 by Martin Pool
- bzr diff finds a branch from the first parameter,
870
            file_list = [b.relpath(f) for f in file_list]
871
            if file_list == ['']:
872
                # just pointing to top-of-tree
873
                file_list = None
874
        else:
800 by Martin Pool
Merge John's import-speedup branch:
875
            b = find_branch('.')
897 by Martin Pool
- merge john's revision-naming code
876
877
        if revision is not None:
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
878
            if len(revision) == 1:
879
                show_diff(b, revision[0], specific_files=file_list,
880
                          external_diff_options=diff_options)
881
            elif len(revision) == 2:
882
                show_diff(b, revision[0], specific_files=file_list,
883
                          external_diff_options=diff_options,
884
                          revision2=revision[1])
885
            else:
886
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
887
        else:
888
            show_diff(b, None, specific_files=file_list,
889
                      external_diff_options=diff_options)
329 by Martin Pool
- refactor command functions into command classes
890
437 by Martin Pool
- new command 'bzr modified' to exercise the statcache
891
        
892
893
329 by Martin Pool
- refactor command functions into command classes
894
class cmd_deleted(Command):
135 by mbp at sourcefrog
Simple new 'deleted' command
895
    """List files deleted in the working tree.
896
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
897
    TODO: Show files deleted since a previous revision, or between two revisions.
135 by mbp at sourcefrog
Simple new 'deleted' command
898
    """
329 by Martin Pool
- refactor command functions into command classes
899
    def run(self, show_ids=False):
800 by Martin Pool
Merge John's import-speedup branch:
900
        b = find_branch('.')
329 by Martin Pool
- refactor command functions into command classes
901
        old = b.basis_tree()
902
        new = b.working_tree()
903
904
        ## TODO: Much more efficient way to do this: read in new
905
        ## directories with readdir, rather than stating each one.  Same
906
        ## level of effort but possibly much less IO.  (Or possibly not,
907
        ## if the directories are very large...)
908
909
        for path, ie in old.inventory.iter_entries():
910
            if not new.has_id(ie.file_id):
911
                if show_ids:
912
                    print '%-50s %s' % (path, ie.file_id)
913
                else:
914
                    print path
915
437 by Martin Pool
- new command 'bzr modified' to exercise the statcache
916
917
class cmd_modified(Command):
918
    """List files modified in working tree."""
919
    hidden = True
920
    def run(self):
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
921
        from bzrlib.delta import compare_trees
865 by Martin Pool
- cleaner 'modified 'command
922
800 by Martin Pool
Merge John's import-speedup branch:
923
        b = find_branch('.')
865 by Martin Pool
- cleaner 'modified 'command
924
        td = compare_trees(b.basis_tree(), b.working_tree())
438 by Martin Pool
- Avoid calling Inventory.iter_entries() when finding modified
925
865 by Martin Pool
- cleaner 'modified 'command
926
        for path, id, kind in td.modified:
927
            print path
439 by Martin Pool
- new command 'bzr added'
928
929
930
931
class cmd_added(Command):
932
    """List files added in working tree."""
933
    hidden = True
934
    def run(self):
800 by Martin Pool
Merge John's import-speedup branch:
935
        b = find_branch('.')
439 by Martin Pool
- new command 'bzr added'
936
        wt = b.working_tree()
937
        basis_inv = b.basis_tree().inventory
938
        inv = wt.inventory
939
        for file_id in inv:
940
            if file_id in basis_inv:
941
                continue
942
            path = inv.id2path(file_id)
943
            if not os.access(b.abspath(path), os.F_OK):
944
                continue
945
            print path
437 by Martin Pool
- new command 'bzr modified' to exercise the statcache
946
                
947
        
948
329 by Martin Pool
- refactor command functions into command classes
949
class cmd_root(Command):
950
    """Show the tree root directory.
951
952
    The root is the nearest enclosing directory with a .bzr control
953
    directory."""
954
    takes_args = ['filename?']
955
    def run(self, filename=None):
956
        """Print the branch root."""
416 by Martin Pool
- bzr log and bzr root now accept an http URL
957
        b = find_branch(filename)
958
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
329 by Martin Pool
- refactor command functions into command classes
959
960
961
class cmd_log(Command):
1 by mbp at sourcefrog
import from baz patch-364
962
    """Show log of this branch.
963
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
964
    To request a range of logs, you can use the command -r begin:end
965
    -r revision requests a specific revision, -r :end or -r begin: are
966
    also valid.
967
900 by Martin Pool
- patch from john to search for matching commits
968
    --message allows you to give a regular expression, which will be evaluated
969
    so that only matching entries will be displayed.
970
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
971
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
972
  
545 by Martin Pool
- --forward option for log
973
    """
367 by Martin Pool
- New --show-ids option for bzr log
974
378 by Martin Pool
- New usage bzr log FILENAME
975
    takes_args = ['filename?']
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
976
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision',
977
                     'long', 'message', 'short',]
545 by Martin Pool
- --forward option for log
978
    
979
    def run(self, filename=None, timezone='original',
980
            verbose=False,
981
            show_ids=False,
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
982
            forward=False,
807 by Martin Pool
- New log --long option
983
            revision=None,
900 by Martin Pool
- patch from john to search for matching commits
984
            message=None,
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
985
            long=False,
986
            short=False):
800 by Martin Pool
Merge John's import-speedup branch:
987
        from bzrlib.branch import find_branch
988
        from bzrlib.log import log_formatter, show_log
562 by Martin Pool
- bug fix for printing logs containing unicode
989
        import codecs
545 by Martin Pool
- --forward option for log
990
991
        direction = (forward and 'forward') or 'reverse'
527 by Martin Pool
- refactor log command
992
        
378 by Martin Pool
- New usage bzr log FILENAME
993
        if filename:
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
994
            b = find_branch(filename)
527 by Martin Pool
- refactor log command
995
            fp = b.relpath(filename)
533 by Martin Pool
- fix up asking for the log for the root of a remote branch
996
            if fp:
997
                file_id = b.read_working_inventory().path2id(fp)
998
            else:
999
                file_id = None  # points to branch root
527 by Martin Pool
- refactor log command
1000
        else:
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
1001
            b = find_branch('.')
527 by Martin Pool
- refactor log command
1002
            file_id = None
1003
897 by Martin Pool
- merge john's revision-naming code
1004
        if revision is None:
1005
            rev1 = None
1006
            rev2 = None
1007
        elif len(revision) == 1:
1008
            rev1 = rev2 = b.get_revision_info(revision[0])[0]
1009
        elif len(revision) == 2:
1010
            rev1 = b.get_revision_info(revision[0])[0]
1011
            rev2 = b.get_revision_info(revision[1])[0]
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
1012
        else:
897 by Martin Pool
- merge john's revision-naming code
1013
            raise BzrCommandError('bzr log --revision takes one or two values.')
1014
1015
        if rev1 == 0:
1016
            rev1 = None
1017
        if rev2 == 0:
1018
            rev2 = None
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
1019
562 by Martin Pool
- bug fix for printing logs containing unicode
1020
        mutter('encoding log as %r' % bzrlib.user_encoding)
610 by Martin Pool
- replace Branch.lock(mode) with separate lock_read and lock_write
1021
1022
        # use 'replace' so that we don't abort if trying to write out
1023
        # in e.g. the default C locale.
1024
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
562 by Martin Pool
- bug fix for printing logs containing unicode
1025
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1026
        if not short:
807 by Martin Pool
- New log --long option
1027
            log_format = 'long'
1028
        else:
1029
            log_format = 'short'
1030
        lf = log_formatter(log_format,
794 by Martin Pool
- Merge John's nice short-log format.
1031
                           show_ids=show_ids,
1032
                           to_file=outf,
1033
                           show_timezone=timezone)
1034
1035
        show_log(b,
1036
                 lf,
1037
                 file_id,
527 by Martin Pool
- refactor log command
1038
                 verbose=verbose,
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
1039
                 direction=direction,
897 by Martin Pool
- merge john's revision-naming code
1040
                 start_revision=rev1,
900 by Martin Pool
- patch from john to search for matching commits
1041
                 end_revision=rev2,
1042
                 search=message)
329 by Martin Pool
- refactor command functions into command classes
1043
1044
375 by Martin Pool
- New command touching-revisions and function to trace
1045
1046
class cmd_touching_revisions(Command):
523 by Martin Pool
doc
1047
    """Return revision-ids which affected a particular file.
1048
1049
    A more user-friendly interface is "bzr log FILE"."""
375 by Martin Pool
- New command touching-revisions and function to trace
1050
    hidden = True
1051
    takes_args = ["filename"]
1052
    def run(self, filename):
800 by Martin Pool
Merge John's import-speedup branch:
1053
        b = find_branch(filename)
375 by Martin Pool
- New command touching-revisions and function to trace
1054
        inv = b.read_working_inventory()
1055
        file_id = inv.path2id(b.relpath(filename))
1056
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
1057
            print "%6d %s" % (revno, what)
1058
1059
329 by Martin Pool
- refactor command functions into command classes
1060
class cmd_ls(Command):
1 by mbp at sourcefrog
import from baz patch-364
1061
    """List files in a tree.
1062
254 by Martin Pool
- Doc cleanups from Magnus Therning
1063
    TODO: Take a revision or remote path and list that tree instead.
1 by mbp at sourcefrog
import from baz patch-364
1064
    """
329 by Martin Pool
- refactor command functions into command classes
1065
    hidden = True
1066
    def run(self, revision=None, verbose=False):
800 by Martin Pool
Merge John's import-speedup branch:
1067
        b = find_branch('.')
329 by Martin Pool
- refactor command functions into command classes
1068
        if revision == None:
1069
            tree = b.working_tree()
1070
        else:
1071
            tree = b.revision_tree(b.lookup_revision(revision))
1072
1073
        for fp, fc, kind, fid in tree.list_files():
1074
            if verbose:
1075
                if kind == 'directory':
1076
                    kindch = '/'
1077
                elif kind == 'file':
1078
                    kindch = ''
1079
                else:
1080
                    kindch = '???'
1081
1082
                print '%-8s %s%s' % (fc, fp, kindch)
1 by mbp at sourcefrog
import from baz patch-364
1083
            else:
329 by Martin Pool
- refactor command functions into command classes
1084
                print fp
1085
1086
1087
1088
class cmd_unknowns(Command):
634 by Martin Pool
- Tidy help messages
1089
    """List unknown files."""
329 by Martin Pool
- refactor command functions into command classes
1090
    def run(self):
800 by Martin Pool
Merge John's import-speedup branch:
1091
        from bzrlib.osutils import quotefn
1092
        for f in find_branch('.').unknowns():
329 by Martin Pool
- refactor command functions into command classes
1093
            print quotefn(f)
1094
1095
1096
1097
class cmd_ignore(Command):
634 by Martin Pool
- Tidy help messages
1098
    """Ignore a command or pattern.
420 by Martin Pool
Doc
1099
1100
    To remove patterns from the ignore list, edit the .bzrignore file.
1101
1102
    If the pattern contains a slash, it is compared to the whole path
1103
    from the branch root.  Otherwise, it is comapred to only the last
1104
    component of the path.
1105
1106
    Ignore patterns are case-insensitive on case-insensitive systems.
1107
1108
    Note: wildcards must be quoted from the shell on Unix.
1109
1110
    examples:
1111
        bzr ignore ./Makefile
1112
        bzr ignore '*.class'
1113
    """
329 by Martin Pool
- refactor command functions into command classes
1114
    takes_args = ['name_pattern']
310 by Martin Pool
- new 'bzr ignored' command!
1115
    
329 by Martin Pool
- refactor command functions into command classes
1116
    def run(self, name_pattern):
409 by Martin Pool
- New AtomicFile class
1117
        from bzrlib.atomicfile import AtomicFile
575 by Martin Pool
- cleanup imports
1118
        import os.path
409 by Martin Pool
- New AtomicFile class
1119
800 by Martin Pool
Merge John's import-speedup branch:
1120
        b = find_branch('.')
410 by Martin Pool
- Fix ignore command and add tests
1121
        ifn = b.abspath('.bzrignore')
329 by Martin Pool
- refactor command functions into command classes
1122
410 by Martin Pool
- Fix ignore command and add tests
1123
        if os.path.exists(ifn):
498 by Martin Pool
bugfix for bzr ignore reported by ddaa:
1124
            f = open(ifn, 'rt')
1125
            try:
1126
                igns = f.read().decode('utf-8')
1127
            finally:
1128
                f.close()
409 by Martin Pool
- New AtomicFile class
1129
        else:
1130
            igns = ''
1131
575 by Martin Pool
- cleanup imports
1132
        # TODO: If the file already uses crlf-style termination, maybe
1133
        # we should use that for the newly added lines?
1134
409 by Martin Pool
- New AtomicFile class
1135
        if igns and igns[-1] != '\n':
1136
            igns += '\n'
1137
        igns += name_pattern + '\n'
1138
498 by Martin Pool
bugfix for bzr ignore reported by ddaa:
1139
        try:
1140
            f = AtomicFile(ifn, 'wt')
1141
            f.write(igns.encode('utf-8'))
1142
            f.commit()
1143
        finally:
1144
            f.close()
329 by Martin Pool
- refactor command functions into command classes
1145
1146
        inv = b.working_tree().inventory
1147
        if inv.path2id('.bzrignore'):
1148
            mutter('.bzrignore is already versioned')
1149
        else:
1150
            mutter('need to make new .bzrignore file versioned')
1151
            b.add(['.bzrignore'])
1152
1153
1154
1155
class cmd_ignored(Command):
421 by Martin Pool
doc
1156
    """List ignored files and the patterns that matched them.
1157
1158
    See also: bzr ignore"""
329 by Martin Pool
- refactor command functions into command classes
1159
    def run(self):
800 by Martin Pool
Merge John's import-speedup branch:
1160
        tree = find_branch('.').working_tree()
329 by Martin Pool
- refactor command functions into command classes
1161
        for path, file_class, kind, file_id in tree.list_files():
1162
            if file_class != 'I':
1163
                continue
1164
            ## XXX: Slightly inefficient since this was already calculated
1165
            pat = tree.is_ignored(path)
1166
            print '%-50s %s' % (path, pat)
1167
1168
1169
class cmd_lookup_revision(Command):
1170
    """Lookup the revision-id from a revision-number
1171
1172
    example:
1173
        bzr lookup-revision 33
421 by Martin Pool
doc
1174
    """
329 by Martin Pool
- refactor command functions into command classes
1175
    hidden = True
338 by Martin Pool
- cleanup of some imports
1176
    takes_args = ['revno']
1177
    
329 by Martin Pool
- refactor command functions into command classes
1178
    def run(self, revno):
1179
        try:
1180
            revno = int(revno)
1181
        except ValueError:
338 by Martin Pool
- cleanup of some imports
1182
            raise BzrCommandError("not a valid revision-number: %r" % revno)
1183
800 by Martin Pool
Merge John's import-speedup branch:
1184
        print find_branch('.').lookup_revision(revno)
329 by Martin Pool
- refactor command functions into command classes
1185
1186
1187
class cmd_export(Command):
1188
    """Export past revision to destination directory.
1189
678 by Martin Pool
- export to tarballs
1190
    If no revision is specified this exports the last committed revision.
1191
1192
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
857 by Martin Pool
- If export filename ends in .tar, etc, then make a tarball instead of a directory
1193
    given, try to find the format with the extension. If no extension
1194
    is found exports to a directory (equivalent to --format=dir).
849 by Martin Pool
- Put files inside an exported tarball into a top-level directory rather than
1195
857 by Martin Pool
- If export filename ends in .tar, etc, then make a tarball instead of a directory
1196
    Root may be the top directory for tar, tgz and tbz2 formats. If none
1197
    is given, the top directory will be the root name of the file."""
678 by Martin Pool
- export to tarballs
1198
    # TODO: list known exporters
329 by Martin Pool
- refactor command functions into command classes
1199
    takes_args = ['dest']
849 by Martin Pool
- Put files inside an exported tarball into a top-level directory rather than
1200
    takes_options = ['revision', 'format', 'root']
857 by Martin Pool
- If export filename ends in .tar, etc, then make a tarball instead of a directory
1201
    def run(self, dest, revision=None, format=None, root=None):
1202
        import os.path
800 by Martin Pool
Merge John's import-speedup branch:
1203
        b = find_branch('.')
897 by Martin Pool
- merge john's revision-naming code
1204
        if revision is None:
1205
            rev_id = b.last_patch()
329 by Martin Pool
- refactor command functions into command classes
1206
        else:
897 by Martin Pool
- merge john's revision-naming code
1207
            if len(revision) != 1:
1208
                raise BzrError('bzr export --revision takes exactly 1 argument')
1209
            revno, rev_id = b.get_revision_info(revision[0])
1210
        t = b.revision_tree(rev_id)
857 by Martin Pool
- If export filename ends in .tar, etc, then make a tarball instead of a directory
1211
        root, ext = os.path.splitext(dest)
1212
        if not format:
1213
            if ext in (".tar",):
1214
                format = "tar"
1215
            elif ext in (".gz", ".tgz"):
1216
                format = "tgz"
1217
            elif ext in (".bz2", ".tbz2"):
1218
                format = "tbz2"
1219
            else:
1220
                format = "dir"
849 by Martin Pool
- Put files inside an exported tarball into a top-level directory rather than
1221
        t.export(dest, format, root)
329 by Martin Pool
- refactor command functions into command classes
1222
1223
1224
class cmd_cat(Command):
1225
    """Write a file's text from a previous revision."""
1226
1227
    takes_options = ['revision']
1228
    takes_args = ['filename']
1229
1230
    def run(self, filename, revision=None):
1231
        if revision == None:
1232
            raise BzrCommandError("bzr cat requires a revision number")
897 by Martin Pool
- merge john's revision-naming code
1233
        elif len(revision) != 1:
1234
            raise BzrCommandError("bzr cat --revision takes exactly one number")
800 by Martin Pool
Merge John's import-speedup branch:
1235
        b = find_branch('.')
897 by Martin Pool
- merge john's revision-naming code
1236
        b.print_file(b.relpath(filename), revision[0])
329 by Martin Pool
- refactor command functions into command classes
1237
1238
1239
class cmd_local_time_offset(Command):
1240
    """Show the offset in seconds from GMT to local time."""
1241
    hidden = True    
1242
    def run(self):
1243
        print bzrlib.osutils.local_time_offset()
1244
1245
1246
1247
class cmd_commit(Command):
1248
    """Commit changes into a new revision.
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1249
    
1250
    If no arguments are given, the entire tree is committed.
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
1251
491 by Martin Pool
- Selective commit!
1252
    If selected files are specified, only changes to those files are
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1253
    committed.  If a directory is specified then the directory and everything 
1254
    within it is committed.
491 by Martin Pool
- Selective commit!
1255
1256
    A selected-file commit may fail in some cases where the committed
1257
    tree would be invalid, such as trying to commit a file in a
1258
    newly-added directory that is not itself committed.
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
1259
1260
    TODO: Run hooks on tree to-be-committed, and after commit.
1261
1262
    TODO: Strict commit that fails if there are unknown or deleted files.
1263
    """
491 by Martin Pool
- Selective commit!
1264
    takes_args = ['selected*']
885 by Martin Pool
- commit command refuses unless something is changed or --unchanged is given
1265
    takes_options = ['message', 'file', 'verbose', 'unchanged']
350 by Martin Pool
- refactor command aliases into command classes
1266
    aliases = ['ci', 'checkin']
1267
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1268
    # TODO: Give better message for -s, --summary, used by tla people
1269
    
885 by Martin Pool
- commit command refuses unless something is changed or --unchanged is given
1270
    def run(self, message=None, file=None, verbose=True, selected_list=None,
1271
            unchanged=False):
1272
        from bzrlib.errors import PointlessCommit
763 by Martin Pool
- Patch from Torsten Marek to take commit messages through an
1273
        from bzrlib.osutils import get_text_message
485 by Martin Pool
- move commit code into its own module
1274
389 by Martin Pool
- new commit --file option!
1275
        ## Warning: shadows builtin file()
1276
        if not message and not file:
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1277
            # FIXME: Ugly; change status code to send to a provided function?
1278
            
763 by Martin Pool
- Patch from Torsten Marek to take commit messages through an
1279
            import cStringIO
1280
            stdout = sys.stdout
1281
            catcher = cStringIO.StringIO()
1282
            sys.stdout = catcher
1283
            cmd_status({"file_list":selected_list}, {})
1284
            info = catcher.getvalue()
1285
            sys.stdout = stdout
1286
            message = get_text_message(info)
1287
            
1288
            if message is None:
1289
                raise BzrCommandError("please specify a commit message",
1290
                                      ["use either --message or --file"])
389 by Martin Pool
- new commit --file option!
1291
        elif message and file:
1292
            raise BzrCommandError("please specify either --message or --file")
1293
        
1294
        if file:
1295
            import codecs
1296
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1297
800 by Martin Pool
Merge John's import-speedup branch:
1298
        b = find_branch('.')
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1299
        if selected_list:
1300
            selected_list = [b.relpath(s) for s in selected_list]
1301
            
885 by Martin Pool
- commit command refuses unless something is changed or --unchanged is given
1302
        try:
1303
            b.commit(message, verbose=verbose,
1304
                     specific_files=selected_list,
1305
                     allow_pointless=unchanged)
1306
        except PointlessCommit:
886 by Martin Pool
doc
1307
            # FIXME: This should really happen before the file is read in;
1308
            # perhaps prepare the commit; get the message; then actually commit
885 by Martin Pool
- commit command refuses unless something is changed or --unchanged is given
1309
            raise BzrCommandError("no changes to commit",
1310
                                  ["use --unchanged to commit anyhow"])
329 by Martin Pool
- refactor command functions into command classes
1311
1312
1313
class cmd_check(Command):
1314
    """Validate consistency of branch history.
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
1315
1316
    This command checks various invariants about the branch storage to
1317
    detect data corruption or bzr bugs.
674 by Martin Pool
- check command now also checks new inventory_sha1 and
1318
1319
    If given the --update flag, it will update some optional fields
1320
    to help ensure data consistency.
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
1321
    """
329 by Martin Pool
- refactor command functions into command classes
1322
    takes_args = ['dir?']
674 by Martin Pool
- check command now also checks new inventory_sha1 and
1323
703 by Martin Pool
- split out a new 'bzr upgrade' command separate from
1324
    def run(self, dir='.'):
800 by Martin Pool
Merge John's import-speedup branch:
1325
        from bzrlib.check import check
1104 by Martin Pool
- Add a simple UIFactory
1326
800 by Martin Pool
Merge John's import-speedup branch:
1327
        check(find_branch(dir))
703 by Martin Pool
- split out a new 'bzr upgrade' command separate from
1328
1329
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
1330
class cmd_scan_cache(Command):
949 by Martin Pool
- add back update-hashes command for testing/profiling
1331
    hidden = True
1332
    def run(self):
1333
        from bzrlib.hashcache import HashCache
952 by Martin Pool
- bzr update-hashes shows some stats on what it did
1334
        import os
949 by Martin Pool
- add back update-hashes command for testing/profiling
1335
1336
        c = HashCache('.')
1337
        c.read()
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
1338
        c.scan()
949 by Martin Pool
- add back update-hashes command for testing/profiling
1339
            
952 by Martin Pool
- bzr update-hashes shows some stats on what it did
1340
        print '%6d stats' % c.stat_count
1341
        print '%6d in hashcache' % len(c._cache)
954 by Martin Pool
- separate out code that just scans the hash cache to find files that are possibly
1342
        print '%6d files removed from cache' % c.removed_count
1343
        print '%6d hashes updated' % c.update_count
952 by Martin Pool
- bzr update-hashes shows some stats on what it did
1344
        print '%6d files changed too recently to cache' % c.danger_count
949 by Martin Pool
- add back update-hashes command for testing/profiling
1345
952 by Martin Pool
- bzr update-hashes shows some stats on what it did
1346
        if c.needs_write:
1347
            c.write()
1348
            
949 by Martin Pool
- add back update-hashes command for testing/profiling
1349
1350
703 by Martin Pool
- split out a new 'bzr upgrade' command separate from
1351
class cmd_upgrade(Command):
1352
    """Upgrade branch storage to current format.
1353
1354
    This should normally be used only after the check command tells
1355
    you to run it.
1356
    """
1357
    takes_args = ['dir?']
1358
1359
    def run(self, dir='.'):
1360
        from bzrlib.upgrade import upgrade
800 by Martin Pool
Merge John's import-speedup branch:
1361
        upgrade(find_branch(dir))
329 by Martin Pool
- refactor command functions into command classes
1362
1363
1364
1365
class cmd_whoami(Command):
1366
    """Show bzr user id."""
1367
    takes_options = ['email']
286 by Martin Pool
- New bzr whoami --email option
1368
    
329 by Martin Pool
- refactor command functions into command classes
1369
    def run(self, email=False):
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
1370
        try:
1371
            b = bzrlib.branch.find_branch('.')
1372
        except:
1373
            b = None
1374
        
329 by Martin Pool
- refactor command functions into command classes
1375
        if email:
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
1376
            print bzrlib.osutils.user_email(b)
329 by Martin Pool
- refactor command functions into command classes
1377
        else:
1074 by Martin Pool
- check for email address in BRANCH_ROOT/.bzr/email, so you can
1378
            print bzrlib.osutils.username(b)
329 by Martin Pool
- refactor command functions into command classes
1379
1380
1381
class cmd_selftest(Command):
55 by mbp at sourcefrog
bzr selftest shows some counts of tests
1382
    """Run internal test suite"""
329 by Martin Pool
- refactor command functions into command classes
1383
    hidden = True
1092.1.20 by Robert Collins
import and use TestUtil to do regex based partial test runs
1384
    takes_options = ['verbose', 'pattern']
1385
    def run(self, verbose=False, pattern=".*"):
1104 by Martin Pool
- Add a simple UIFactory
1386
        import bzrlib.ui
608 by Martin Pool
- Split selftests out into a new module and start changing them
1387
        from bzrlib.selftest import selftest
1104 by Martin Pool
- Add a simple UIFactory
1388
        # we don't want progress meters from the tests to go to the
1112 by Martin Pool
- disable standard logging to .bzr.log and stderr while running
1389
        # real output; and we don't want log messages cluttering up
1390
        # the real logs.
1104 by Martin Pool
- Add a simple UIFactory
1391
        save_ui = bzrlib.ui.ui_factory
1112 by Martin Pool
- disable standard logging to .bzr.log and stderr while running
1392
        bzrlib.trace.info('running tests...')
1393
        bzrlib.trace.disable_default_logging()
1104 by Martin Pool
- Add a simple UIFactory
1394
        try:
1395
            bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
1092.1.39 by Robert Collins
merge from mpool
1396
            result = selftest(verbose=verbose, pattern=pattern)
1112 by Martin Pool
- disable standard logging to .bzr.log and stderr while running
1397
            if result:
1398
                bzrlib.trace.info('tests passed')
1399
            else:
1400
                bzrlib.trace.info('tests failed')
1401
            return int(not result)
1104 by Martin Pool
- Add a simple UIFactory
1402
        finally:
1112 by Martin Pool
- disable standard logging to .bzr.log and stderr while running
1403
            bzrlib.trace.enable_default_logging()
1104 by Martin Pool
- Add a simple UIFactory
1404
            bzrlib.ui.ui_factory = save_ui
329 by Martin Pool
- refactor command functions into command classes
1405
1406
1407
class cmd_version(Command):
634 by Martin Pool
- Tidy help messages
1408
    """Show version of bzr."""
329 by Martin Pool
- refactor command functions into command classes
1409
    def run(self):
1410
        show_version()
1411
1412
def show_version():
1413
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
605 by Martin Pool
- patch from Lalo Martins to show version of bzr itself
1414
    # is bzrlib itself in a branch?
606 by Martin Pool
- new bzrlib.get_bzr_revision() tells about the history of
1415
    bzrrev = bzrlib.get_bzr_revision()
1416
    if bzrrev:
1417
        print "  (bzr checkout, revision %d {%s})" % bzrrev
329 by Martin Pool
- refactor command functions into command classes
1418
    print bzrlib.__copyright__
1419
    print "http://bazaar-ng.org/"
1420
    print
1421
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
1422
    print "you may use, modify and redistribute it under the terms of the GNU"
1423
    print "General Public License version 2 or later."
1424
1425
1426
class cmd_rocks(Command):
1427
    """Statement of optimism."""
1428
    hidden = True
1429
    def run(self):
1430
        print "it sure does!"
1431
493 by Martin Pool
- Merge aaron's merge command
1432
def parse_spec(spec):
622 by Martin Pool
Updated merge patch from Aaron
1433
    """
1434
    >>> parse_spec(None)
1435
    [None, None]
1436
    >>> parse_spec("./")
1437
    ['./', None]
1438
    >>> parse_spec("../@")
1439
    ['..', -1]
1440
    >>> parse_spec("../f/@35")
1441
    ['../f', 35]
897 by Martin Pool
- merge john's revision-naming code
1442
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
1443
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
622 by Martin Pool
Updated merge patch from Aaron
1444
    """
1445
    if spec is None:
1446
        return [None, None]
493 by Martin Pool
- Merge aaron's merge command
1447
    if '/@' in spec:
1448
        parsed = spec.split('/@')
1449
        assert len(parsed) == 2
1450
        if parsed[1] == "":
1451
            parsed[1] = -1
1452
        else:
897 by Martin Pool
- merge john's revision-naming code
1453
            try:
1454
                parsed[1] = int(parsed[1])
1455
            except ValueError:
1456
                pass # We can allow stuff like ./@revid:blahblahblah
1457
            else:
1458
                assert parsed[1] >=0
493 by Martin Pool
- Merge aaron's merge command
1459
    else:
1460
        parsed = [spec, None]
1461
    return parsed
1462
628 by Martin Pool
- merge aaron's updated merge/pull code
1463
1464
1105 by Martin Pool
- expose 'find-merge-base' as a new expert command,
1465
class cmd_find_merge_base(Command):
1466
    """Find and print a base revision for merging two branches.
1467
1468
    TODO: Options to specify revisions on either side, as if
1469
          merging only part of the history.
1470
    """
1471
    takes_args = ['branch', 'other']
1472
    hidden = True
1473
    
1474
    def run(self, branch, other):
1475
        branch1 = find_branch(branch)
1476
        branch2 = find_branch(other)
1477
1478
        base_revno, base_revid = branch1.common_ancestor(branch2)
1479
1480
        if base_revno is None:
1481
            raise bzrlib.errors.UnrelatedBranches()
1482
1483
        print 'merge base is revision %s' % base_revid
1484
        print ' r%-6d in %s' % (base_revno, branch)
1485
1486
        other_revno = branch2.revision_id_to_revno(base_revid)
1487
        
1488
        print ' r%-6d in %s' % (other_revno, other)
1489
1490
1491
493 by Martin Pool
- Merge aaron's merge command
1492
class cmd_merge(Command):
974.1.25 by Aaron Bentley
Changed merge to take a branch and revision instead of a tree-spec.
1493
    """Perform a three-way merge.
1494
    
1495
    The branch is the branch you will merge from.  By default, it will merge
1496
    the latest revision.  If you specify a revision, that revision will be
1497
    merged.  If you specify two revisions, the first will be used as a BASE, 
1498
    and the second one as OTHER.  Revision numbers are always relative to the
1499
    specified branch.
1500
    
1501
    Examples:
1502
1503
    To merge the latest revision from bzr.dev
1504
    bzr merge ../bzr.dev
1505
1506
    To merge changes up to and including revision 82 from bzr.dev
1507
    bzr merge -r 82 ../bzr.dev
1508
1509
    To merge the changes introduced by 82, without previous changes:
1510
    bzr merge -r 81..82 ../bzr.dev
1511
    
628 by Martin Pool
- merge aaron's updated merge/pull code
1512
    merge refuses to run if there are any uncommitted changes, unless
1513
    --force is given.
622 by Martin Pool
Updated merge patch from Aaron
1514
    """
974.1.25 by Aaron Bentley
Changed merge to take a branch and revision instead of a tree-spec.
1515
    takes_args = ['branch?']
1516
    takes_options = ['revision', 'force', 'merge-type']
622 by Martin Pool
Updated merge patch from Aaron
1517
974.1.25 by Aaron Bentley
Changed merge to take a branch and revision instead of a tree-spec.
1518
    def run(self, branch='.', revision=None, force=False, 
1519
            merge_type=None):
591 by Martin Pool
- trim imports
1520
        from bzrlib.merge import merge
974.1.9 by Aaron Bentley
Added merge-type parameter to merge.
1521
        from bzrlib.merge_core import ApplyMerge3
1522
        if merge_type is None:
1523
            merge_type = ApplyMerge3
974.1.25 by Aaron Bentley
Changed merge to take a branch and revision instead of a tree-spec.
1524
1525
        if revision is None or len(revision) < 1:
974.1.37 by aaron.bentley at utoronto
pending merges, common ancestor work properly
1526
            base = [None, None]
974.1.46 by Aaron Bentley
Fixed ancestor-picking when -r is specified
1527
            other = [branch, -1]
974.1.25 by Aaron Bentley
Changed merge to take a branch and revision instead of a tree-spec.
1528
        else:
1529
            if len(revision) == 1:
974.1.46 by Aaron Bentley
Fixed ancestor-picking when -r is specified
1530
                other = [branch, revision[0]]
1531
                base = [None, None]
974.1.25 by Aaron Bentley
Changed merge to take a branch and revision instead of a tree-spec.
1532
            else:
1533
                assert len(revision) == 2
1534
                if None in revision:
1535
                    raise BzrCommandError(
1536
                        "Merge doesn't permit that revision specifier.")
1537
                base = (branch, revision[0])
1538
                other = (branch, revision[1])
1539
            
1540
        merge(other, base, check_clean=(not force), merge_type=merge_type)
622 by Martin Pool
Updated merge patch from Aaron
1541
778 by Martin Pool
- simple revert of text files
1542
784 by Martin Pool
- rename merge-based revert command to 'merge-revert'
1543
class cmd_revert(Command):
628 by Martin Pool
- merge aaron's updated merge/pull code
1544
    """Reverse all changes since the last commit.
1545
974.1.10 by aaron.bentley at utoronto
Added file-selection to merge-revert
1546
    Only versioned files are affected.  Specify filenames to revert only 
1547
    those files.  By default, any files that are changed will be backed up
1548
    first.  Backup files have a '~' appended to their name.
622 by Martin Pool
Updated merge patch from Aaron
1549
    """
974.1.8 by Aaron Bentley
Added default backups for merge-revert
1550
    takes_options = ['revision', 'no-backup']
974.1.10 by aaron.bentley at utoronto
Added file-selection to merge-revert
1551
    takes_args = ['file*']
974.1.11 by aaron.bentley at utoronto
replaced revert with merge-revert
1552
    aliases = ['merge-revert']
622 by Martin Pool
Updated merge patch from Aaron
1553
974.1.10 by aaron.bentley at utoronto
Added file-selection to merge-revert
1554
    def run(self, revision=None, no_backup=False, file_list=None):
636 by Martin Pool
- fix missing import in revert
1555
        from bzrlib.merge import merge
974.1.38 by aaron.bentley at utoronto
Made revert clear pending-merges
1556
        from bzrlib.branch import Branch
974.1.10 by aaron.bentley at utoronto
Added file-selection to merge-revert
1557
        if file_list is not None:
1558
            if len(file_list) == 0:
1559
                raise BzrCommandError("No files specified")
897 by Martin Pool
- merge john's revision-naming code
1560
        if revision is None:
909.1.1 by aaron.bentley at utoronto
Fixed handling of merge-revert with no --revision
1561
            revision = [-1]
897 by Martin Pool
- merge john's revision-naming code
1562
        elif len(revision) != 1:
974.1.11 by aaron.bentley at utoronto
replaced revert with merge-revert
1563
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
897 by Martin Pool
- merge john's revision-naming code
1564
        merge(('.', revision[0]), parse_spec('.'),
628 by Martin Pool
- merge aaron's updated merge/pull code
1565
              check_clean=False,
974.1.8 by Aaron Bentley
Added default backups for merge-revert
1566
              ignore_zero=True,
974.1.10 by aaron.bentley at utoronto
Added file-selection to merge-revert
1567
              backup_files=not no_backup,
1568
              file_list=file_list)
974.1.38 by aaron.bentley at utoronto
Made revert clear pending-merges
1569
        if not file_list:
1570
            Branch('.').set_pending_merges([])
622 by Martin Pool
Updated merge patch from Aaron
1571
1572
329 by Martin Pool
- refactor command functions into command classes
1573
class cmd_assert_fail(Command):
1574
    """Test reporting of assertion failures"""
1575
    hidden = True
1576
    def run(self):
1577
        assert False, "always fails"
1578
1579
1580
class cmd_help(Command):
1581
    """Show help on a command or other topic.
1582
1583
    For a list of all available commands, say 'bzr help commands'."""
1109 by Martin Pool
- remove accidental breakage of diff command
1584
    takes_options = ['long']
329 by Martin Pool
- refactor command functions into command classes
1585
    takes_args = ['topic?']
350 by Martin Pool
- refactor command aliases into command classes
1586
    aliases = ['?']
329 by Martin Pool
- refactor command functions into command classes
1587
    
1109 by Martin Pool
- remove accidental breakage of diff command
1588
    def run(self, topic=None, long=False):
351 by Martin Pool
- Split out help functions into bzrlib.help
1589
        import help
1109 by Martin Pool
- remove accidental breakage of diff command
1590
        if topic is None and long:
1591
            topic = "commands"
351 by Martin Pool
- Split out help functions into bzrlib.help
1592
        help.help(topic)
1593
1 by mbp at sourcefrog
import from baz patch-364
1594
1091 by Martin Pool
- new shell-complete command to help zsh completion
1595
class cmd_shell_complete(Command):
1596
    """Show appropriate completions for context.
1597
1598
    For a list of all available commands, say 'bzr shell-complete'."""
1599
    takes_args = ['context?']
1600
    aliases = ['s-c']
1601
    hidden = True
1602
    
1603
    def run(self, context=None):
1604
        import shellcomplete
1605
        shellcomplete.shellcomplete(context)
429 by Martin Pool
- New command update-stat-cache for testing
1606
1 by mbp at sourcefrog
import from baz patch-364
1607
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1608
class cmd_missing(Command):
1609
    """What is missing in this branch relative to other branch.
1610
    """
1611
    takes_args = ['remote?']
1612
    aliases = ['mis', 'miss']
1613
    # We don't have to add quiet to the list, because 
1614
    # unknown options are parsed as booleans
1615
    takes_options = ['verbose', 'quiet']
1616
1617
    def run(self, remote=None, verbose=False, quiet=False):
1618
        from bzrlib.branch import find_branch, DivergedBranches
1619
        from bzrlib.errors import BzrCommandError
1620
        from bzrlib.missing import get_parent, show_missing
1621
1622
        if verbose and quiet:
1623
            raise BzrCommandError('Cannot pass both quiet and verbose')
1624
1625
        b = find_branch('.')
1626
        parent = get_parent(b)
1627
        if remote is None:
1628
            if parent is None:
1629
                raise BzrCommandError("No missing location known or specified.")
1630
            else:
1631
                if not quiet:
1632
                    print "Using last location: %s" % parent
1633
                remote = parent
1634
        elif parent is None:
1635
            # We only update x-pull if it did not exist, missing should not change the parent
1636
            b.controlfile('x-pull', 'wb').write(remote + '\n')
1637
        br_remote = find_branch(remote)
1638
1639
        return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
1640
1641
1094 by Martin Pool
- merge aaron's merge improvements 999..1008
1642
755 by Martin Pool
- new 'plugins' command
1643
class cmd_plugins(Command):
1644
    """List plugins"""
1645
    hidden = True
1646
    def run(self):
1647
        import bzrlib.plugin
908 by Martin Pool
- merge john's plugins-have-test_suite.patch:
1648
        from inspect import getdoc
756 by Martin Pool
- plugins documentation; better error reporting when failing to
1649
        from pprint import pprint
908 by Martin Pool
- merge john's plugins-have-test_suite.patch:
1650
        for plugin in bzrlib.plugin.all_plugins:
1651
            print plugin.__path__[0]
1652
            d = getdoc(plugin)
1653
            if d:
1654
                print '\t', d.split('\n')[0]
1655
1656
        #pprint(bzrlib.plugin.all_plugins)
755 by Martin Pool
- new 'plugins' command
1657
1658
1659
1 by mbp at sourcefrog
import from baz patch-364
1660
# list of all available options; the rhs can be either None for an
1661
# option that takes no argument, or a constructor function that checks
1662
# the type.
1663
OPTIONS = {
1664
    'all':                    None,
571 by Martin Pool
- new --diff-options to pass options through to external
1665
    'diff-options':           str,
1 by mbp at sourcefrog
import from baz patch-364
1666
    'help':                   None,
389 by Martin Pool
- new commit --file option!
1667
    'file':                   unicode,
628 by Martin Pool
- merge aaron's updated merge/pull code
1668
    'force':                  None,
678 by Martin Pool
- export to tarballs
1669
    'format':                 unicode,
545 by Martin Pool
- --forward option for log
1670
    'forward':                None,
1 by mbp at sourcefrog
import from baz patch-364
1671
    'message':                unicode,
594 by Martin Pool
- add --no-recurse option for add command
1672
    'no-recurse':             None,
137 by mbp at sourcefrog
new --profile option
1673
    'profile':                None,
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
1674
    'revision':               _parse_revision_str,
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1675
    'short':                  None,
1 by mbp at sourcefrog
import from baz patch-364
1676
    'show-ids':               None,
12 by mbp at sourcefrog
new --timezone option for bzr log
1677
    'timezone':               str,
1 by mbp at sourcefrog
import from baz patch-364
1678
    'verbose':                None,
1679
    'version':                None,
286 by Martin Pool
- New bzr whoami --email option
1680
    'email':                  None,
885 by Martin Pool
- commit command refuses unless something is changed or --unchanged is given
1681
    'unchanged':              None,
674 by Martin Pool
- check command now also checks new inventory_sha1 and
1682
    'update':                 None,
807 by Martin Pool
- New log --long option
1683
    'long':                   None,
849 by Martin Pool
- Put files inside an exported tarball into a top-level directory rather than
1684
    'root':                   str,
974.1.8 by Aaron Bentley
Added default backups for merge-revert
1685
    'no-backup':              None,
974.1.9 by Aaron Bentley
Added merge-type parameter to merge.
1686
    'merge-type':             get_merge_type,
1092.1.20 by Robert Collins
import and use TestUtil to do regex based partial test runs
1687
    'pattern':                str,
1 by mbp at sourcefrog
import from baz patch-364
1688
    }
1689
1690
SHORT_OPTIONS = {
583 by Martin Pool
- add -h as short name for --help
1691
    'F':                      'file', 
1692
    'h':                      'help',
1 by mbp at sourcefrog
import from baz patch-364
1693
    'm':                      'message',
1694
    'r':                      'revision',
1695
    'v':                      'verbose',
807 by Martin Pool
- New log --long option
1696
    'l':                      'long',
1 by mbp at sourcefrog
import from baz patch-364
1697
}
1698
1699
1700
def parse_args(argv):
1701
    """Parse command line.
1702
    
1703
    Arguments and options are parsed at this level before being passed
1704
    down to specific command handlers.  This routine knows, from a
1705
    lookup table, something about the available options, what optargs
1706
    they take, and which commands will accept them.
1707
31 by Martin Pool
fix up parse_args doctest
1708
    >>> parse_args('--help'.split())
1 by mbp at sourcefrog
import from baz patch-364
1709
    ([], {'help': True})
31 by Martin Pool
fix up parse_args doctest
1710
    >>> parse_args('--version'.split())
1 by mbp at sourcefrog
import from baz patch-364
1711
    ([], {'version': True})
31 by Martin Pool
fix up parse_args doctest
1712
    >>> parse_args('status --all'.split())
1 by mbp at sourcefrog
import from baz patch-364
1713
    (['status'], {'all': True})
31 by Martin Pool
fix up parse_args doctest
1714
    >>> parse_args('commit --message=biter'.split())
17 by mbp at sourcefrog
allow --option=ARG syntax
1715
    (['commit'], {'message': u'biter'})
683 by Martin Pool
- short option stacking patch from John A Meinel
1716
    >>> parse_args('log -r 500'.split())
897 by Martin Pool
- merge john's revision-naming code
1717
    (['log'], {'revision': [500]})
1718
    >>> parse_args('log -r500..600'.split())
683 by Martin Pool
- short option stacking patch from John A Meinel
1719
    (['log'], {'revision': [500, 600]})
897 by Martin Pool
- merge john's revision-naming code
1720
    >>> parse_args('log -vr500..600'.split())
683 by Martin Pool
- short option stacking patch from John A Meinel
1721
    (['log'], {'verbose': True, 'revision': [500, 600]})
897 by Martin Pool
- merge john's revision-naming code
1722
    >>> parse_args('log -rv500..600'.split()) #the r takes an argument
1723
    (['log'], {'revision': ['v500', 600]})
1 by mbp at sourcefrog
import from baz patch-364
1724
    """
1725
    args = []
1726
    opts = {}
1727
1728
    # TODO: Maybe handle '--' to end options?
1729
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
1730
    while argv:
1731
        a = argv.pop(0)
1 by mbp at sourcefrog
import from baz patch-364
1732
        if a[0] == '-':
264 by Martin Pool
parse_args: option names must be ascii
1733
            # option names must not be unicode
1734
            a = str(a)
17 by mbp at sourcefrog
allow --option=ARG syntax
1735
            optarg = None
1 by mbp at sourcefrog
import from baz patch-364
1736
            if a[1] == '-':
1737
                mutter("  got option %r" % a)
17 by mbp at sourcefrog
allow --option=ARG syntax
1738
                if '=' in a:
1739
                    optname, optarg = a[2:].split('=', 1)
1740
                else:
1741
                    optname = a[2:]
1 by mbp at sourcefrog
import from baz patch-364
1742
                if optname not in OPTIONS:
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
1743
                    raise BzrError('unknown long option %r' % a)
1 by mbp at sourcefrog
import from baz patch-364
1744
            else:
1745
                shortopt = a[1:]
683 by Martin Pool
- short option stacking patch from John A Meinel
1746
                if shortopt in SHORT_OPTIONS:
1747
                    # Multi-character options must have a space to delimit
1748
                    # their value
1749
                    optname = SHORT_OPTIONS[shortopt]
1750
                else:
1751
                    # Single character short options, can be chained,
1752
                    # and have their value appended to their name
1753
                    shortopt = a[1:2]
1754
                    if shortopt not in SHORT_OPTIONS:
1755
                        # We didn't find the multi-character name, and we
1756
                        # didn't find the single char name
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
1757
                        raise BzrError('unknown short option %r' % a)
683 by Martin Pool
- short option stacking patch from John A Meinel
1758
                    optname = SHORT_OPTIONS[shortopt]
1759
1760
                    if a[2:]:
1761
                        # There are extra things on this option
1762
                        # see if it is the value, or if it is another
1763
                        # short option
1764
                        optargfn = OPTIONS[optname]
1765
                        if optargfn is None:
1766
                            # This option does not take an argument, so the
1767
                            # next entry is another short option, pack it back
1768
                            # into the list
1769
                            argv.insert(0, '-' + a[2:])
1770
                        else:
1771
                            # This option takes an argument, so pack it
1772
                            # into the array
1773
                            optarg = a[2:]
1 by mbp at sourcefrog
import from baz patch-364
1774
            
1775
            if optname in opts:
1776
                # XXX: Do we ever want to support this, e.g. for -r?
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
1777
                raise BzrError('repeated option %r' % a)
17 by mbp at sourcefrog
allow --option=ARG syntax
1778
                
1 by mbp at sourcefrog
import from baz patch-364
1779
            optargfn = OPTIONS[optname]
1780
            if optargfn:
17 by mbp at sourcefrog
allow --option=ARG syntax
1781
                if optarg == None:
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
1782
                    if not argv:
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
1783
                        raise BzrError('option %r needs an argument' % a)
17 by mbp at sourcefrog
allow --option=ARG syntax
1784
                    else:
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
1785
                        optarg = argv.pop(0)
17 by mbp at sourcefrog
allow --option=ARG syntax
1786
                opts[optname] = optargfn(optarg)
1 by mbp at sourcefrog
import from baz patch-364
1787
            else:
17 by mbp at sourcefrog
allow --option=ARG syntax
1788
                if optarg != None:
694 by Martin Pool
- weed out all remaining calls to bailout() and remove the function
1789
                    raise BzrError('option %r takes no argument' % optname)
1 by mbp at sourcefrog
import from baz patch-364
1790
                opts[optname] = True
1791
        else:
1792
            args.append(a)
1793
1794
    return args, opts
1795
1796
1797
1798
329 by Martin Pool
- refactor command functions into command classes
1799
def _match_argform(cmd, takes_args, args):
1 by mbp at sourcefrog
import from baz patch-364
1800
    argdict = {}
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
1801
329 by Martin Pool
- refactor command functions into command classes
1802
    # step through args and takes_args, allowing appropriate 0-many matches
1803
    for ap in takes_args:
1 by mbp at sourcefrog
import from baz patch-364
1804
        argname = ap[:-1]
1805
        if ap[-1] == '?':
62 by mbp at sourcefrog
- new find_branch_root function; based on suggestion from aaron
1806
            if args:
1807
                argdict[argname] = args.pop(0)
196 by mbp at sourcefrog
selected-file diff
1808
        elif ap[-1] == '*': # all remaining arguments
1809
            if args:
1810
                argdict[argname + '_list'] = args[:]
1811
                args = []
1812
            else:
1813
                argdict[argname + '_list'] = None
1 by mbp at sourcefrog
import from baz patch-364
1814
        elif ap[-1] == '+':
1815
            if not args:
329 by Martin Pool
- refactor command functions into command classes
1816
                raise BzrCommandError("command %r needs one or more %s"
1 by mbp at sourcefrog
import from baz patch-364
1817
                        % (cmd, argname.upper()))
1818
            else:
1819
                argdict[argname + '_list'] = args[:]
1820
                args = []
160 by mbp at sourcefrog
- basic support for moving files to different directories - have not done support for renaming them yet, but should be straightforward - some tests, but many cases are not handled yet i think
1821
        elif ap[-1] == '$': # all but one
1822
            if len(args) < 2:
329 by Martin Pool
- refactor command functions into command classes
1823
                raise BzrCommandError("command %r needs one or more %s"
160 by mbp at sourcefrog
- basic support for moving files to different directories - have not done support for renaming them yet, but should be straightforward - some tests, but many cases are not handled yet i think
1824
                        % (cmd, argname.upper()))
1825
            argdict[argname + '_list'] = args[:-1]
1826
            args[:-1] = []                
1 by mbp at sourcefrog
import from baz patch-364
1827
        else:
1828
            # just a plain arg
1829
            argname = ap
1830
            if not args:
329 by Martin Pool
- refactor command functions into command classes
1831
                raise BzrCommandError("command %r requires argument %s"
1 by mbp at sourcefrog
import from baz patch-364
1832
                        % (cmd, argname.upper()))
1833
            else:
1834
                argdict[argname] = args.pop(0)
1835
            
1836
    if args:
329 by Martin Pool
- refactor command functions into command classes
1837
        raise BzrCommandError("extra argument to command %s: %s"
1838
                              % (cmd, args[0]))
1 by mbp at sourcefrog
import from baz patch-364
1839
1840
    return argdict
1841
1842
1843
1844
def run_bzr(argv):
1845
    """Execute a command.
1846
1847
    This is similar to main(), but without all the trappings for
245 by mbp at sourcefrog
- control files always in utf-8-unix format
1848
    logging and error handling.  
973 by Martin Pool
- various refactorings of command interpreter
1849
    
1850
    argv
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1851
       The command-line arguments, without the program name from argv[0]
973 by Martin Pool
- various refactorings of command interpreter
1852
    
1853
    Returns a command status or raises an exception.
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1854
1855
    Special master options: these must come before the command because
1856
    they control how the command is interpreted.
1857
1858
    --no-plugins
1859
        Do not load plugin modules at all
1860
1861
    --builtin
1862
        Only use builtin commands.  (Plugins are still allowed to change
1863
        other behaviour.)
1864
1865
    --profile
1866
        Run under the Python profiler.
1 by mbp at sourcefrog
import from baz patch-364
1867
    """
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1868
    
251 by mbp at sourcefrog
- factor out locale.getpreferredencoding()
1869
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
973 by Martin Pool
- various refactorings of command interpreter
1870
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1871
    opt_profile = opt_no_plugins = opt_builtin = False
1872
1873
    # --no-plugins is handled specially at a very early stage. We need
1874
    # to load plugins before doing other command parsing so that they
1875
    # can override commands, but this needs to happen first.
1876
1877
    for a in argv[:]:
1878
        if a == '--profile':
1879
            opt_profile = True
1880
        elif a == '--no-plugins':
1881
            opt_no_plugins = True
1882
        elif a == '--builtin':
1883
            opt_builtin = True
1884
        else:
1885
            break
1886
        argv.remove(a)
1887
1888
    if not opt_no_plugins:
973 by Martin Pool
- various refactorings of command interpreter
1889
        from bzrlib.plugin import load_plugins
1890
        load_plugins()
1891
1892
    args, opts = parse_args(argv)
1893
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1894
    if 'help' in opts:
973 by Martin Pool
- various refactorings of command interpreter
1895
        from bzrlib.help import help
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1896
        if args:
1897
            help(args[0])
973 by Martin Pool
- various refactorings of command interpreter
1898
        else:
1899
            help()
1900
        return 0            
1901
        
1902
    if 'version' in opts:
1903
        show_version()
1904
        return 0
1905
    
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1906
    if not args:
1099 by Martin Pool
- 'bzr' with no arguments shows the summary help.
1907
        from bzrlib.help import help
1908
        help(None)
1909
        return 0
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1910
    
1911
    cmd = str(args.pop(0))
1912
1913
    canonical_cmd, cmd_class = \
1914
                   get_cmd_class(cmd, plugins_override=not opt_builtin)
1 by mbp at sourcefrog
import from baz patch-364
1915
1916
    # check options are reasonable
329 by Martin Pool
- refactor command functions into command classes
1917
    allowed = cmd_class.takes_options
1 by mbp at sourcefrog
import from baz patch-364
1918
    for oname in opts:
1919
        if oname not in allowed:
381 by Martin Pool
- Better message when a wrong argument is given
1920
            raise BzrCommandError("option '--%s' is not allowed for command %r"
329 by Martin Pool
- refactor command functions into command classes
1921
                                  % (oname, cmd))
176 by mbp at sourcefrog
New cat command contributed by janmar.
1922
137 by mbp at sourcefrog
new --profile option
1923
    # mix arguments and options into one dictionary
329 by Martin Pool
- refactor command functions into command classes
1924
    cmdargs = _match_argform(cmd, cmd_class.takes_args, args)
1925
    cmdopts = {}
136 by mbp at sourcefrog
new --show-ids option for 'deleted' command
1926
    for k, v in opts.items():
329 by Martin Pool
- refactor command functions into command classes
1927
        cmdopts[k.replace('-', '_')] = v
1 by mbp at sourcefrog
import from baz patch-364
1928
974.1.26 by aaron.bentley at utoronto
merged mbp@sourcefrog.net-20050817233101-0939da1cf91f2472
1929
    if opt_profile:
338 by Martin Pool
- cleanup of some imports
1930
        import hotshot, tempfile
239 by mbp at sourcefrog
- remove profiler temporary file when done
1931
        pffileno, pfname = tempfile.mkstemp()
1932
        try:
1933
            prof = hotshot.Profile(pfname)
329 by Martin Pool
- refactor command functions into command classes
1934
            ret = prof.runcall(cmd_class, cmdopts, cmdargs) or 0
239 by mbp at sourcefrog
- remove profiler temporary file when done
1935
            prof.close()
1936
1937
            import hotshot.stats
1938
            stats = hotshot.stats.load(pfname)
1939
            #stats.strip_dirs()
1940
            stats.sort_stats('time')
1941
            ## XXX: Might like to write to stderr or the trace file instead but
1942
            ## print_stats seems hardcoded to stdout
1943
            stats.print_stats(20)
1944
            
337 by Martin Pool
- Clarify return codes from command objects
1945
            return ret.status
239 by mbp at sourcefrog
- remove profiler temporary file when done
1946
1947
        finally:
1948
            os.close(pffileno)
1949
            os.remove(pfname)
137 by mbp at sourcefrog
new --profile option
1950
    else:
500 by Martin Pool
- fix return value from run_bzr
1951
        return cmd_class(cmdopts, cmdargs).status 
1 by mbp at sourcefrog
import from baz patch-364
1952
1953
1954
def main(argv):
1104 by Martin Pool
- Add a simple UIFactory
1955
    import bzrlib.ui
1111 by Martin Pool
- add functions to enable and disable default logging, so that we can
1956
    bzrlib.trace.log_startup(argv)
1104 by Martin Pool
- Add a simple UIFactory
1957
    bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory()
1958
1 by mbp at sourcefrog
import from baz patch-364
1959
    try:
260 by Martin Pool
- remove atexit() dependency for writing out execution times
1960
        try:
1097 by Martin Pool
- send trace messages out through python logging module
1961
            return run_bzr(argv[1:])
1962
        finally:
1963
            # do this here inside the exception wrappers to catch EPIPE
1964
            sys.stdout.flush()
1965
    except BzrCommandError, e:
1966
        # command line syntax error, etc
1967
        log_error(str(e))
1968
        return 1
1969
    except BzrError, e:
1970
        bzrlib.trace.log_exception()
1971
        return 1
1972
    except AssertionError, e:
1973
        bzrlib.trace.log_exception('assertion failed: ' + str(e))
1974
        return 3
1975
    except KeyboardInterrupt, e:
1976
        bzrlib.trace.note('interrupted')
1977
        return 2
1978
    except Exception, e:
1979
        import errno
1980
        if (isinstance(e, IOError) 
1981
            and hasattr(e, 'errno')
1982
            and e.errno == errno.EPIPE):
1983
            bzrlib.trace.note('broken pipe')
1984
            return 2
1985
        else:
1108 by Martin Pool
- more cleanups of error reporting
1986
            bzrlib.trace.log_exception()
1097 by Martin Pool
- send trace messages out through python logging module
1987
            return 2
1 by mbp at sourcefrog
import from baz patch-364
1988
1989
1990
if __name__ == '__main__':
1991
    sys.exit(main(sys.argv))