~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-05-03 07:48:54 UTC
  • Revision ID: mbp@sourcefrog.net-20050503074854-adb6f9d6382e27a9
- sketchy experiments in bash and zsh completion

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
 
 
18
 
 
19
 
import sys, os
 
17
"""Bazaar-NG -- a free distributed version-control tool
 
18
http://bazaar-ng.org/
 
19
 
 
20
**WARNING: THIS IS AN UNSTABLE DEVELOPMENT VERSION**
 
21
 
 
22
* Metadata format is not stable yet -- you may need to
 
23
  discard history in the future.
 
24
 
 
25
* Many commands unimplemented or partially implemented.
 
26
 
 
27
* Space-inefficient storage.
 
28
 
 
29
* No merge operators yet.
 
30
 
 
31
Interesting commands:
 
32
 
 
33
  bzr help [COMMAND]
 
34
      Show help screen
 
35
  bzr version
 
36
      Show software version/licence/non-warranty.
 
37
  bzr init
 
38
      Start versioning the current directory
 
39
  bzr add FILE...
 
40
      Make files versioned.
 
41
  bzr log
 
42
      Show revision history.
 
43
  bzr rename FROM TO
 
44
      Rename one file.
 
45
  bzr move FROM... DESTDIR
 
46
      Move one or more files to a different directory.
 
47
  bzr diff [FILE...]
 
48
      Show changes from last revision to working copy.
 
49
  bzr commit -m 'MESSAGE'
 
50
      Store current state as new revision.
 
51
  bzr export [-r REVNO] DESTINATION
 
52
      Export the branch state at a previous version.
 
53
  bzr status
 
54
      Show summary of pending changes.
 
55
  bzr remove FILE...
 
56
      Make a file not versioned.
 
57
  bzr info
 
58
      Show statistics about this branch.
 
59
  bzr check
 
60
      Verify history is stored safely. 
 
61
  (for more type 'bzr help commands')
 
62
"""
 
63
 
 
64
 
 
65
 
 
66
 
 
67
import sys, os, time, types, shutil, tempfile, fnmatch, difflib, os.path
 
68
from sets import Set
 
69
from pprint import pprint
 
70
from stat import *
 
71
from glob import glob
20
72
 
21
73
import bzrlib
 
74
from bzrlib.store import ImmutableStore
22
75
from bzrlib.trace import mutter, note, log_error
23
 
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
24
 
from bzrlib.branch import find_branch
25
 
from bzrlib import BZRDIR
26
 
 
27
 
 
28
 
plugin_cmds = {}
29
 
 
30
 
 
31
 
def register_command(cmd):
32
 
    "Utility function to help register a command"
33
 
    global plugin_cmds
34
 
    k = cmd.__name__
35
 
    if k.startswith("cmd_"):
36
 
        k_unsquished = _unsquish_command_name(k)
37
 
    else:
38
 
        k_unsquished = k
39
 
    if not plugin_cmds.has_key(k_unsquished):
40
 
        plugin_cmds[k_unsquished] = cmd
41
 
    else:
42
 
        log_error('Two plugins defined the same command: %r' % k)
43
 
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
44
 
 
45
 
 
46
 
def _squish_command_name(cmd):
47
 
    return 'cmd_' + cmd.replace('-', '_')
48
 
 
49
 
 
50
 
def _unsquish_command_name(cmd):
51
 
    assert cmd.startswith("cmd_")
52
 
    return cmd[4:].replace('_','-')
53
 
 
54
 
def _parse_revision_str(revstr):
55
 
    """This handles a revision string -> revno. 
56
 
 
57
 
    There are several possibilities:
58
 
 
59
 
        '234'       -> 234
60
 
        '234:345'   -> [234, 345]
61
 
        ':234'      -> [None, 234]
62
 
        '234:'      -> [234, None]
63
 
 
64
 
    In the future we will also support:
65
 
        'uuid:blah-blah-blah'   -> ?
66
 
        'hash:blahblahblah'     -> ?
67
 
        potentially:
68
 
        'tag:mytag'             -> ?
69
 
    """
70
 
    if revstr.find(':') != -1:
71
 
        revs = revstr.split(':')
72
 
        if len(revs) > 2:
73
 
            raise ValueError('More than 2 pieces not supported for --revision: %r' % revstr)
74
 
 
75
 
        if not revs[0]:
76
 
            revs[0] = None
77
 
        else:
78
 
            revs[0] = int(revs[0])
79
 
 
80
 
        if not revs[1]:
81
 
            revs[1] = None
82
 
        else:
83
 
            revs[1] = int(revs[1])
84
 
    else:
85
 
        revs = int(revstr)
86
 
    return revs
87
 
 
88
 
 
89
 
 
90
 
def _get_cmd_dict(plugins_override=True):
91
 
    d = {}
92
 
    for k, v in globals().iteritems():
93
 
        if k.startswith("cmd_"):
94
 
            d[_unsquish_command_name(k)] = v
95
 
    # If we didn't load plugins, the plugin_cmds dict will be empty
96
 
    if plugins_override:
97
 
        d.update(plugin_cmds)
98
 
    else:
99
 
        d2 = plugin_cmds.copy()
100
 
        d2.update(d)
101
 
        d = d2
102
 
    return d
103
 
 
104
 
    
105
 
def get_all_cmds(plugins_override=True):
106
 
    """Return canonical name and class for all registered commands."""
107
 
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
108
 
        yield k,v
109
 
 
110
 
 
111
 
def get_cmd_class(cmd, plugins_override=True):
112
 
    """Return the canonical name and command class for a command.
113
 
    """
114
 
    cmd = str(cmd)                      # not unicode
115
 
 
116
 
    # first look up this command under the specified name
117
 
    cmds = _get_cmd_dict(plugins_override=plugins_override)
 
76
from bzrlib.errors import bailout, BzrError, BzrCheckError, BzrCommandError
 
77
from bzrlib.osutils import quotefn, pumpfile, isdir, isfile
 
78
from bzrlib.tree import RevisionTree, EmptyTree, WorkingTree, Tree
 
79
from bzrlib.revision import Revision
 
80
from bzrlib import Branch, Inventory, InventoryEntry, ScratchBranch, BZRDIR, \
 
81
     format_date
 
82
 
 
83
BZR_DIFF_FORMAT = "## Bazaar-NG diff, format 0 ##\n"
 
84
BZR_PATCHNAME_FORMAT = 'cset:sha1:%s'
 
85
 
 
86
## standard representation
 
87
NONE_STRING = '(none)'
 
88
EMPTY = 'empty'
 
89
 
 
90
 
 
91
CMD_ALIASES = {
 
92
    '?':         'help',
 
93
    'ci':        'commit',
 
94
    'checkin':   'commit',
 
95
    'di':        'diff',
 
96
    'st':        'status',
 
97
    'stat':      'status',
 
98
    }
 
99
 
 
100
 
 
101
def get_cmd_class(cmd):
 
102
    cmd = str(cmd)
 
103
    
 
104
    cmd = CMD_ALIASES.get(cmd, cmd)
 
105
    
118
106
    try:
119
 
        return cmd, cmds[cmd]
 
107
        cmd_class = globals()['cmd_' + cmd.replace('-', '_')]
120
108
    except KeyError:
121
 
        pass
122
 
 
123
 
    # look for any command which claims this as an alias
124
 
    for cmdname, cmdclass in cmds.iteritems():
125
 
        if cmd in cmdclass.aliases:
126
 
            return cmdname, cmdclass
127
 
 
128
 
    cmdclass = ExternalCommand.find_command(cmd)
129
 
    if cmdclass:
130
 
        return cmd, cmdclass
131
 
 
132
 
    raise BzrCommandError("unknown command %r" % cmd)
133
 
 
134
 
 
135
 
class Command(object):
 
109
        raise BzrError("unknown command %r" % cmd)
 
110
 
 
111
    return cmd, cmd_class
 
112
 
 
113
 
 
114
 
 
115
class Command:
136
116
    """Base class for commands.
137
117
 
138
118
    The docstring for an actual command should give a single-line
175
155
        This is invoked with the options and arguments bound to
176
156
        keyword parameters.
177
157
 
178
 
        Return 0 or None if the command was successful, or a shell
179
 
        error code if not.
 
158
        Return True if the command was successful, False if not.
180
159
        """
181
 
        return 0
182
 
 
183
 
 
184
 
class ExternalCommand(Command):
185
 
    """Class to wrap external commands.
186
 
 
187
 
    We cheat a little here, when get_cmd_class() calls us we actually give it back
188
 
    an object we construct that has the appropriate path, help, options etc for the
189
 
    specified command.
190
 
 
191
 
    When run_bzr() tries to instantiate that 'class' it gets caught by the __call__
192
 
    method, which we override to call the Command.__init__ method. That then calls
193
 
    our run method which is pretty straight forward.
194
 
 
195
 
    The only wrinkle is that we have to map bzr's dictionary of options and arguments
196
 
    back into command line options and arguments for the script.
197
 
    """
198
 
 
199
 
    def find_command(cls, cmd):
200
 
        import os.path
201
 
        bzrpath = os.environ.get('BZRPATH', '')
202
 
 
203
 
        for dir in bzrpath.split(os.pathsep):
204
 
            path = os.path.join(dir, cmd)
205
 
            if os.path.isfile(path):
206
 
                return ExternalCommand(path)
207
 
 
208
 
        return None
209
 
 
210
 
    find_command = classmethod(find_command)
211
 
 
212
 
    def __init__(self, path):
213
 
        self.path = path
214
 
 
215
 
        pipe = os.popen('%s --bzr-usage' % path, 'r')
216
 
        self.takes_options = pipe.readline().split()
217
 
 
218
 
        for opt in self.takes_options:
219
 
            if not opt in OPTIONS:
220
 
                raise BzrError("Unknown option '%s' returned by external command %s"
221
 
                               % (opt, path))
222
 
 
223
 
        # TODO: Is there any way to check takes_args is valid here?
224
 
        self.takes_args = pipe.readline().split()
225
 
 
226
 
        if pipe.close() is not None:
227
 
            raise BzrError("Failed funning '%s --bzr-usage'" % path)
228
 
 
229
 
        pipe = os.popen('%s --bzr-help' % path, 'r')
230
 
        self.__doc__ = pipe.read()
231
 
        if pipe.close() is not None:
232
 
            raise BzrError("Failed funning '%s --bzr-help'" % path)
233
 
 
234
 
    def __call__(self, options, arguments):
235
 
        Command.__init__(self, options, arguments)
236
 
        return self
237
 
 
238
 
    def run(self, **kargs):
239
 
        opts = []
240
 
        args = []
241
 
 
242
 
        keys = kargs.keys()
243
 
        keys.sort()
244
 
        for name in keys:
245
 
            optname = name.replace('_','-')
246
 
            value = kargs[name]
247
 
            if OPTIONS.has_key(optname):
248
 
                # it's an option
249
 
                opts.append('--%s' % optname)
250
 
                if value is not None and value is not True:
251
 
                    opts.append(str(value))
252
 
            else:
253
 
                # it's an arg, or arg list
254
 
                if type(value) is not list:
255
 
                    value = [value]
256
 
                for v in value:
257
 
                    if v is not None:
258
 
                        args.append(str(v))
259
 
 
260
 
        self.status = os.spawnv(os.P_WAIT, self.path, [self.path] + opts + args)
261
 
        return self.status
 
160
        return True
 
161
 
262
162
 
263
163
 
264
164
class cmd_status(Command):
265
165
    """Display status summary.
266
166
 
267
 
    This reports on versioned and unknown files, reporting them
268
 
    grouped by state.  Possible states are:
269
 
 
270
 
    added
271
 
        Versioned in the working copy but not in the previous revision.
272
 
 
273
 
    removed
274
 
        Versioned in the previous revision but removed or deleted
275
 
        in the working copy.
276
 
 
277
 
    renamed
278
 
        Path of this file changed from the previous revision;
279
 
        the text may also have changed.  This includes files whose
280
 
        parent directory was renamed.
281
 
 
282
 
    modified
283
 
        Text has changed since the previous revision.
284
 
 
285
 
    unchanged
286
 
        Nothing about this file has changed since the previous revision.
287
 
        Only shown with --all.
288
 
 
289
 
    unknown
290
 
        Not versioned and not matching an ignore pattern.
291
 
 
292
 
    To see ignored files use 'bzr ignored'.  For details in the
293
 
    changes to file texts, use 'bzr diff'.
294
 
 
295
 
    If no arguments are specified, the status of the entire working
296
 
    directory is shown.  Otherwise, only the status of the specified
297
 
    files or directories is reported.  If a directory is given, status
298
 
    is reported for everything inside that directory.
 
167
    For each file there is a single line giving its file state and name.
 
168
    The name is that in the current revision unless it is deleted or
 
169
    missing, in which case the old name is shown.
299
170
    """
300
 
    takes_args = ['file*']
301
 
    takes_options = ['all', 'show-ids']
302
 
    aliases = ['st', 'stat']
 
171
    takes_options = ['all']
303
172
    
304
 
    def run(self, all=False, show_ids=False, file_list=None):
305
 
        if file_list:
306
 
            b = find_branch(file_list[0])
307
 
            file_list = [b.relpath(x) for x in file_list]
308
 
            # special case: only one path was given and it's the root
309
 
            # of the branch
310
 
            if file_list == ['']:
311
 
                file_list = None
312
 
        else:
313
 
            b = find_branch('.')
314
 
        import status
315
 
        status.show_status(b, show_unchanged=all, show_ids=show_ids,
316
 
                           specific_files=file_list)
 
173
    def run(self, all=False):
 
174
        #import bzrlib.status
 
175
        #bzrlib.status.tree_status(Branch('.'))
 
176
        Branch('.').show_status(show_all=all)
317
177
 
318
178
 
319
179
class cmd_cat_revision(Command):
323
183
    takes_args = ['revision_id']
324
184
    
325
185
    def run(self, revision_id):
326
 
        from bzrlib.xml import pack_xml
327
 
        pack_xml(find_branch('.').get_revision(revision_id), sys.stdout)
 
186
        Branch('.').get_revision(revision_id).write_xml(sys.stdout)
328
187
 
329
188
 
330
189
class cmd_revno(Command):
332
191
 
333
192
    This is equal to the number of revisions on this branch."""
334
193
    def run(self):
335
 
        print find_branch('.').revno()
 
194
        print Branch('.').revno()
336
195
 
337
196
    
338
197
class cmd_add(Command):
357
216
    recursively add that parent, rather than giving an error?
358
217
    """
359
218
    takes_args = ['file+']
360
 
    takes_options = ['verbose', 'no-recurse']
 
219
    takes_options = ['verbose']
361
220
    
362
 
    def run(self, file_list, verbose=False, no_recurse=False):
363
 
        from bzrlib.add import smart_add
364
 
        smart_add(file_list, verbose, not no_recurse)
365
 
 
366
 
 
367
 
 
368
 
class cmd_mkdir(Command):
369
 
    """Create a new versioned directory.
370
 
 
371
 
    This is equivalent to creating the directory and then adding it.
372
 
    """
373
 
    takes_args = ['dir+']
374
 
 
375
 
    def run(self, dir_list):
376
 
        b = None
377
 
        
378
 
        for d in dir_list:
379
 
            os.mkdir(d)
380
 
            if not b:
381
 
                b = find_branch(d)
382
 
            b.add([d], verbose=True)
383
 
 
384
 
 
385
 
class cmd_relpath(Command):
 
221
    def run(self, file_list, verbose=False):
 
222
        bzrlib.add.smart_add(file_list, verbose)
 
223
 
 
224
 
 
225
def Relpath(Command):
386
226
    """Show path of a file relative to root"""
387
 
    takes_args = ['filename']
388
 
    hidden = True
 
227
    takes_args = ('filename')
389
228
    
390
 
    def run(self, filename):
391
 
        print find_branch(filename).relpath(filename)
 
229
    def run(self):
 
230
        print Branch(self.args['filename']).relpath(filename)
392
231
 
393
232
 
394
233
 
395
234
class cmd_inventory(Command):
396
235
    """Show inventory of the current working copy or a revision."""
397
 
    takes_options = ['revision', 'show-ids']
 
236
    takes_options = ['revision']
398
237
    
399
 
    def run(self, revision=None, show_ids=False):
400
 
        b = find_branch('.')
 
238
    def run(self, revision=None):
 
239
        b = Branch('.')
401
240
        if revision == None:
402
241
            inv = b.read_working_inventory()
403
242
        else:
404
243
            inv = b.get_revision_inventory(b.lookup_revision(revision))
405
244
 
406
 
        for path, entry in inv.entries():
407
 
            if show_ids:
408
 
                print '%-50s %s' % (path, entry.file_id)
409
 
            else:
410
 
                print path
 
245
        for path, entry in inv.iter_entries():
 
246
            print '%-50s %s' % (entry.file_id, path)
411
247
 
412
248
 
413
249
class cmd_move(Command):
420
256
    """
421
257
    takes_args = ['source$', 'dest']
422
258
    def run(self, source_list, dest):
423
 
        b = find_branch('.')
 
259
        b = Branch('.')
424
260
 
425
261
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
426
262
 
442
278
    takes_args = ['from_name', 'to_name']
443
279
    
444
280
    def run(self, from_name, to_name):
445
 
        b = find_branch('.')
 
281
        b = Branch('.')
446
282
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
447
283
 
448
284
 
449
285
 
450
 
 
451
 
 
452
 
class cmd_pull(Command):
453
 
    """Pull any changes from another branch into the current one.
454
 
 
455
 
    If the location is omitted, the last-used location will be used.
456
 
    Both the revision history and the working directory will be
457
 
    updated.
458
 
 
459
 
    This command only works on branches that have not diverged.  Branches are
460
 
    considered diverged if both branches have had commits without first
461
 
    pulling from the other.
462
 
 
463
 
    If branches have diverged, you can use 'bzr merge' to pull the text changes
464
 
    from one into the other.
465
 
    """
466
 
    takes_args = ['location?']
467
 
 
468
 
    def run(self, location=None):
469
 
        from bzrlib.merge import merge
470
 
        import tempfile
471
 
        from shutil import rmtree
472
 
        import errno
473
 
        
474
 
        br_to = find_branch('.')
475
 
        stored_loc = None
476
 
        try:
477
 
            stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
478
 
        except IOError, e:
479
 
            if e.errno != errno.ENOENT:
480
 
                raise
481
 
        if location is None:
482
 
            if stored_loc is None:
483
 
                raise BzrCommandError("No pull location known or specified.")
484
 
            else:
485
 
                print "Using last location: %s" % stored_loc
486
 
                location = stored_loc
487
 
        cache_root = tempfile.mkdtemp()
488
 
        from bzrlib.branch import DivergedBranches
489
 
        br_from = find_branch(location)
490
 
        location = pull_loc(br_from)
491
 
        old_revno = br_to.revno()
492
 
        try:
493
 
            from branch import find_cached_branch, DivergedBranches
494
 
            br_from = find_cached_branch(location, cache_root)
495
 
            location = pull_loc(br_from)
496
 
            old_revno = br_to.revno()
497
 
            try:
498
 
                br_to.update_revisions(br_from)
499
 
            except DivergedBranches:
500
 
                raise BzrCommandError("These branches have diverged."
501
 
                    "  Try merge.")
502
 
                
503
 
            merge(('.', -1), ('.', old_revno), check_clean=False)
504
 
            if location != stored_loc:
505
 
                br_to.controlfile("x-pull", "wb").write(location + "\n")
506
 
        finally:
507
 
            rmtree(cache_root)
508
 
 
509
 
 
510
 
 
511
 
class cmd_branch(Command):
512
 
    """Create a new copy of a branch.
513
 
 
514
 
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
515
 
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
516
 
 
517
 
    To retrieve the branch as of a particular revision, supply the --revision
518
 
    parameter, as in "branch foo/bar -r 5".
519
 
    """
520
 
    takes_args = ['from_location', 'to_location?']
521
 
    takes_options = ['revision']
522
 
 
523
 
    def run(self, from_location, to_location=None, revision=None):
524
 
        import errno
525
 
        from bzrlib.merge import merge
526
 
        from bzrlib.branch import DivergedBranches, NoSuchRevision, \
527
 
             find_cached_branch, Branch
528
 
        from shutil import rmtree
529
 
        from meta_store import CachedStore
530
 
        import tempfile
531
 
        cache_root = tempfile.mkdtemp()
532
 
        try:
533
 
            try:
534
 
                br_from = find_cached_branch(from_location, cache_root)
535
 
            except OSError, e:
536
 
                if e.errno == errno.ENOENT:
537
 
                    raise BzrCommandError('Source location "%s" does not'
538
 
                                          ' exist.' % to_location)
539
 
                else:
540
 
                    raise
541
 
 
542
 
            if to_location is None:
543
 
                to_location = os.path.basename(from_location.rstrip("/\\"))
544
 
 
545
 
            try:
546
 
                os.mkdir(to_location)
547
 
            except OSError, e:
548
 
                if e.errno == errno.EEXIST:
549
 
                    raise BzrCommandError('Target directory "%s" already'
550
 
                                          ' exists.' % to_location)
551
 
                if e.errno == errno.ENOENT:
552
 
                    raise BzrCommandError('Parent of "%s" does not exist.' %
553
 
                                          to_location)
554
 
                else:
555
 
                    raise
556
 
            br_to = Branch(to_location, init=True)
557
 
 
558
 
            try:
559
 
                br_to.update_revisions(br_from, stop_revision=revision)
560
 
            except NoSuchRevision:
561
 
                rmtree(to_location)
562
 
                msg = "The branch %s has no revision %d." % (from_location,
563
 
                                                             revision)
564
 
                raise BzrCommandError(msg)
565
 
            merge((to_location, -1), (to_location, 0), this_dir=to_location,
566
 
                  check_clean=False, ignore_zero=True)
567
 
            from_location = pull_loc(br_from)
568
 
            br_to.controlfile("x-pull", "wb").write(from_location + "\n")
569
 
        finally:
570
 
            rmtree(cache_root)
571
 
 
572
 
 
573
 
def pull_loc(branch):
574
 
    # TODO: Should perhaps just make attribute be 'base' in
575
 
    # RemoteBranch and Branch?
576
 
    if hasattr(branch, "baseurl"):
577
 
        return branch.baseurl
578
 
    else:
579
 
        return branch.base
580
 
 
581
 
 
582
 
 
583
286
class cmd_renames(Command):
584
287
    """Show list of renamed files.
585
288
 
590
293
    takes_args = ['dir?']
591
294
 
592
295
    def run(self, dir='.'):
593
 
        b = find_branch(dir)
 
296
        b = Branch(dir)
594
297
        old_inv = b.basis_tree().inventory
595
298
        new_inv = b.read_working_inventory()
596
299
 
601
304
 
602
305
 
603
306
class cmd_info(Command):
604
 
    """Show statistical information about a branch."""
605
 
    takes_args = ['branch?']
606
 
    
607
 
    def run(self, branch=None):
 
307
    """Show statistical information for this branch"""
 
308
    def run(self):
608
309
        import info
609
 
 
610
 
        b = find_branch(branch)
611
 
        info.show_info(b)
 
310
        info.show_info(Branch('.'))        
612
311
 
613
312
 
614
313
class cmd_remove(Command):
621
320
    takes_options = ['verbose']
622
321
    
623
322
    def run(self, file_list, verbose=False):
624
 
        b = find_branch(file_list[0])
 
323
        b = Branch(file_list[0])
625
324
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
626
325
 
627
326
 
635
334
    hidden = True
636
335
    takes_args = ['filename']
637
336
    def run(self, filename):
638
 
        b = find_branch(filename)
 
337
        b = Branch(filename)
639
338
        i = b.inventory.path2id(b.relpath(filename))
640
339
        if i == None:
641
 
            raise BzrError("%r is not a versioned file" % filename)
 
340
            bailout("%r is not a versioned file" % filename)
642
341
        else:
643
342
            print i
644
343
 
651
350
    hidden = True
652
351
    takes_args = ['filename']
653
352
    def run(self, filename):
654
 
        b = find_branch(filename)
 
353
        b = Branch(filename)
655
354
        inv = b.inventory
656
355
        fid = inv.path2id(b.relpath(filename))
657
356
        if fid == None:
658
 
            raise BzrError("%r is not a versioned file" % filename)
 
357
            bailout("%r is not a versioned file" % filename)
659
358
        for fip in inv.get_idpath(fid):
660
359
            print fip
661
360
 
662
361
 
663
362
class cmd_revision_history(Command):
664
363
    """Display list of revision ids on this branch."""
665
 
    hidden = True
666
364
    def run(self):
667
 
        for patchid in find_branch('.').revision_history():
 
365
        for patchid in Branch('.').revision_history():
668
366
            print patchid
669
367
 
670
368
 
671
369
class cmd_directories(Command):
672
370
    """Display list of versioned directories in this branch."""
673
371
    def run(self):
674
 
        for name, ie in find_branch('.').read_working_inventory().directories():
 
372
        for name, ie in Branch('.').read_working_inventory().directories():
675
373
            if name == '':
676
374
                print '.'
677
375
            else:
692
390
        bzr commit -m 'imported project'
693
391
    """
694
392
    def run(self):
695
 
        from bzrlib.branch import Branch
696
393
        Branch('.', init=True)
697
394
 
698
395
 
721
418
    """
722
419
    
723
420
    takes_args = ['file*']
724
 
    takes_options = ['revision', 'diff-options']
725
 
    aliases = ['di', 'dif']
 
421
    takes_options = ['revision']
726
422
 
727
 
    def run(self, revision=None, file_list=None, diff_options=None):
 
423
    def run(self, revision=None, file_list=None):
728
424
        from bzrlib.diff import show_diff
729
 
 
730
 
        if file_list:
731
 
            b = find_branch(file_list[0])
732
 
            file_list = [b.relpath(f) for f in file_list]
733
 
            if file_list == ['']:
734
 
                # just pointing to top-of-tree
735
 
                file_list = None
736
 
        else:
737
 
            b = find_branch('.')
738
425
    
739
 
        show_diff(b, revision, specific_files=file_list,
740
 
                  external_diff_options=diff_options)
741
 
 
742
 
 
743
 
        
 
426
        show_diff(Branch('.'), revision, file_list)
744
427
 
745
428
 
746
429
class cmd_deleted(Command):
749
432
    TODO: Show files deleted since a previous revision, or between two revisions.
750
433
    """
751
434
    def run(self, show_ids=False):
752
 
        b = find_branch('.')
 
435
        b = Branch('.')
753
436
        old = b.basis_tree()
754
437
        new = b.working_tree()
755
438
 
765
448
                else:
766
449
                    print path
767
450
 
768
 
 
769
 
class cmd_modified(Command):
770
 
    """List files modified in working tree."""
771
 
    hidden = True
772
 
    def run(self):
773
 
        import statcache
774
 
        b = find_branch('.')
775
 
        inv = b.read_working_inventory()
776
 
        sc = statcache.update_cache(b, inv)
777
 
        basis = b.basis_tree()
778
 
        basis_inv = basis.inventory
779
 
        
780
 
        # We used to do this through iter_entries(), but that's slow
781
 
        # when most of the files are unmodified, as is usually the
782
 
        # case.  So instead we iterate by inventory entry, and only
783
 
        # calculate paths as necessary.
784
 
 
785
 
        for file_id in basis_inv:
786
 
            cacheentry = sc.get(file_id)
787
 
            if not cacheentry:                 # deleted
788
 
                continue
789
 
            ie = basis_inv[file_id]
790
 
            if cacheentry[statcache.SC_SHA1] != ie.text_sha1:
791
 
                path = inv.id2path(file_id)
792
 
                print path
793
 
 
794
 
 
795
 
 
796
 
class cmd_added(Command):
797
 
    """List files added in working tree."""
798
 
    hidden = True
799
 
    def run(self):
800
 
        b = find_branch('.')
801
 
        wt = b.working_tree()
802
 
        basis_inv = b.basis_tree().inventory
803
 
        inv = wt.inventory
804
 
        for file_id in inv:
805
 
            if file_id in basis_inv:
806
 
                continue
807
 
            path = inv.id2path(file_id)
808
 
            if not os.access(b.abspath(path), os.F_OK):
809
 
                continue
810
 
            print path
811
 
                
812
 
        
813
 
 
814
451
class cmd_root(Command):
815
452
    """Show the tree root directory.
816
453
 
819
456
    takes_args = ['filename?']
820
457
    def run(self, filename=None):
821
458
        """Print the branch root."""
822
 
        b = find_branch(filename)
823
 
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
 
459
        print bzrlib.branch.find_branch_root(filename)
 
460
 
824
461
 
825
462
 
826
463
class cmd_log(Command):
827
464
    """Show log of this branch.
828
465
 
829
 
    To request a range of logs, you can use the command -r begin:end
830
 
    -r revision requests a specific revision, -r :end or -r begin: are
831
 
    also valid.
832
 
 
833
 
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
834
 
  
 
466
    TODO: Options to show ids; to limit range; etc.
835
467
    """
836
 
 
837
 
    takes_args = ['filename?']
838
 
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision']
839
 
    
840
 
    def run(self, filename=None, timezone='original',
841
 
            verbose=False,
842
 
            show_ids=False,
843
 
            forward=False,
844
 
            revision=None):
845
 
        from bzrlib.branch import find_branch
846
 
        from bzrlib.log import log_formatter, show_log
847
 
        import codecs
848
 
 
849
 
        direction = (forward and 'forward') or 'reverse'
850
 
        
851
 
        if filename:
852
 
            b = find_branch(filename)
853
 
            fp = b.relpath(filename)
854
 
            if fp:
855
 
                file_id = b.read_working_inventory().path2id(fp)
856
 
            else:
857
 
                file_id = None  # points to branch root
858
 
        else:
859
 
            b = find_branch('.')
860
 
            file_id = None
861
 
 
862
 
        if revision == None:
863
 
            revision = [None, None]
864
 
        elif isinstance(revision, int):
865
 
            revision = [revision, revision]
866
 
        else:
867
 
            # pair of revisions?
868
 
            pass
869
 
            
870
 
        assert len(revision) == 2
871
 
 
872
 
        mutter('encoding log as %r' % bzrlib.user_encoding)
873
 
 
874
 
        # use 'replace' so that we don't abort if trying to write out
875
 
        # in e.g. the default C locale.
876
 
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
877
 
 
878
 
        lf = log_formatter('short',
879
 
                           show_ids=show_ids,
880
 
                           to_file=outf,
881
 
                           show_timezone=timezone)
882
 
 
883
 
        show_log(b,
884
 
                 lf,
885
 
                 file_id,
886
 
                 verbose=verbose,
887
 
                 direction=direction,
888
 
                 start_revision=revision[0],
889
 
                 end_revision=revision[1])
890
 
 
891
 
 
892
 
 
893
 
class cmd_touching_revisions(Command):
894
 
    """Return revision-ids which affected a particular file.
895
 
 
896
 
    A more user-friendly interface is "bzr log FILE"."""
897
 
    hidden = True
898
 
    takes_args = ["filename"]
899
 
    def run(self, filename):
900
 
        b = find_branch(filename)
901
 
        inv = b.read_working_inventory()
902
 
        file_id = inv.path2id(b.relpath(filename))
903
 
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
904
 
            print "%6d %s" % (revno, what)
 
468
    takes_options = ['timezone', 'verbose']
 
469
    def run(self, timezone='original', verbose=False):
 
470
        Branch('.').write_log(show_timezone=timezone, verbose=verbose)
905
471
 
906
472
 
907
473
class cmd_ls(Command):
911
477
    """
912
478
    hidden = True
913
479
    def run(self, revision=None, verbose=False):
914
 
        b = find_branch('.')
 
480
        b = Branch('.')
915
481
        if revision == None:
916
482
            tree = b.working_tree()
917
483
        else:
933
499
 
934
500
 
935
501
class cmd_unknowns(Command):
936
 
    """List unknown files."""
 
502
    """List unknown files"""
937
503
    def run(self):
938
 
        from bzrlib.osutils import quotefn
939
 
        for f in find_branch('.').unknowns():
 
504
        for f in Branch('.').unknowns():
940
505
            print quotefn(f)
941
506
 
942
507
 
943
508
 
944
509
class cmd_ignore(Command):
945
 
    """Ignore a command or pattern.
946
 
 
947
 
    To remove patterns from the ignore list, edit the .bzrignore file.
948
 
 
949
 
    If the pattern contains a slash, it is compared to the whole path
950
 
    from the branch root.  Otherwise, it is comapred to only the last
951
 
    component of the path.
952
 
 
953
 
    Ignore patterns are case-insensitive on case-insensitive systems.
954
 
 
955
 
    Note: wildcards must be quoted from the shell on Unix.
956
 
 
957
 
    examples:
958
 
        bzr ignore ./Makefile
959
 
        bzr ignore '*.class'
960
 
    """
 
510
    """Ignore a command or pattern"""
961
511
    takes_args = ['name_pattern']
962
512
    
963
513
    def run(self, name_pattern):
964
 
        from bzrlib.atomicfile import AtomicFile
965
 
        import os.path
966
 
 
967
 
        b = find_branch('.')
968
 
        ifn = b.abspath('.bzrignore')
969
 
 
970
 
        if os.path.exists(ifn):
971
 
            f = open(ifn, 'rt')
972
 
            try:
973
 
                igns = f.read().decode('utf-8')
974
 
            finally:
975
 
                f.close()
976
 
        else:
977
 
            igns = ''
978
 
 
979
 
        # TODO: If the file already uses crlf-style termination, maybe
980
 
        # we should use that for the newly added lines?
981
 
 
982
 
        if igns and igns[-1] != '\n':
983
 
            igns += '\n'
984
 
        igns += name_pattern + '\n'
985
 
 
986
 
        try:
987
 
            f = AtomicFile(ifn, 'wt')
988
 
            f.write(igns.encode('utf-8'))
989
 
            f.commit()
990
 
        finally:
991
 
            f.close()
 
514
        b = Branch('.')
 
515
 
 
516
        # XXX: This will fail if it's a hardlink; should use an AtomicFile class.
 
517
        f = open(b.abspath('.bzrignore'), 'at')
 
518
        f.write(name_pattern + '\n')
 
519
        f.close()
992
520
 
993
521
        inv = b.working_tree().inventory
994
522
        if inv.path2id('.bzrignore'):
1000
528
 
1001
529
 
1002
530
class cmd_ignored(Command):
1003
 
    """List ignored files and the patterns that matched them.
1004
 
 
1005
 
    See also: bzr ignore"""
 
531
    """List ignored files and the patterns that matched them."""
1006
532
    def run(self):
1007
 
        tree = find_branch('.').working_tree()
 
533
        tree = Branch('.').working_tree()
1008
534
        for path, file_class, kind, file_id in tree.list_files():
1009
535
            if file_class != 'I':
1010
536
                continue
1018
544
 
1019
545
    example:
1020
546
        bzr lookup-revision 33
1021
 
    """
 
547
        """
1022
548
    hidden = True
1023
 
    takes_args = ['revno']
1024
 
    
1025
549
    def run(self, revno):
1026
550
        try:
1027
551
            revno = int(revno)
1028
552
        except ValueError:
1029
 
            raise BzrCommandError("not a valid revision-number: %r" % revno)
1030
 
 
1031
 
        print find_branch('.').lookup_revision(revno)
 
553
            raise BzrError("not a valid revision-number: %r" % revno)
 
554
 
 
555
        print Branch('.').lookup_revision(revno) or NONE_STRING
 
556
 
1032
557
 
1033
558
 
1034
559
class cmd_export(Command):
1035
560
    """Export past revision to destination directory.
1036
561
 
1037
 
    If no revision is specified this exports the last committed revision.
1038
 
 
1039
 
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
1040
 
    given, exports to a directory (equivalent to --format=dir)."""
1041
 
    # TODO: list known exporters
 
562
    If no revision is specified this exports the last committed revision."""
1042
563
    takes_args = ['dest']
1043
 
    takes_options = ['revision', 'format']
1044
 
    def run(self, dest, revision=None, format='dir'):
1045
 
        b = find_branch('.')
1046
 
        if revision == None:
1047
 
            rh = b.revision_history()[-1]
 
564
    takes_options = ['revision']
 
565
    def run(self, dest, revno=None):
 
566
        b = Branch('.')
 
567
        if revno == None:
 
568
            rh = b.revision_history[-1]
1048
569
        else:
1049
 
            rh = b.lookup_revision(int(revision))
 
570
            rh = b.lookup_revision(int(revno))
1050
571
        t = b.revision_tree(rh)
1051
 
        t.export(dest, format)
 
572
        t.export(dest)
1052
573
 
1053
574
 
1054
575
class cmd_cat(Command):
1060
581
    def run(self, filename, revision=None):
1061
582
        if revision == None:
1062
583
            raise BzrCommandError("bzr cat requires a revision number")
1063
 
        b = find_branch('.')
 
584
        b = Branch('.')
1064
585
        b.print_file(b.relpath(filename), int(revision))
1065
586
 
1066
587
 
1075
596
class cmd_commit(Command):
1076
597
    """Commit changes into a new revision.
1077
598
 
1078
 
    If selected files are specified, only changes to those files are
1079
 
    committed.  If a directory is specified then its contents are also
1080
 
    committed.
1081
 
 
1082
 
    A selected-file commit may fail in some cases where the committed
1083
 
    tree would be invalid, such as trying to commit a file in a
1084
 
    newly-added directory that is not itself committed.
 
599
    TODO: Commit only selected files.
1085
600
 
1086
601
    TODO: Run hooks on tree to-be-committed, and after commit.
1087
602
 
1088
603
    TODO: Strict commit that fails if there are unknown or deleted files.
1089
604
    """
1090
 
    takes_args = ['selected*']
1091
 
    takes_options = ['message', 'file', 'verbose']
1092
 
    aliases = ['ci', 'checkin']
1093
 
 
1094
 
    def run(self, message=None, file=None, verbose=True, selected_list=None):
1095
 
        from bzrlib.commit import commit
1096
 
        from bzrlib.osutils import get_text_message
1097
 
 
1098
 
        ## Warning: shadows builtin file()
1099
 
        if not message and not file:
1100
 
            import cStringIO
1101
 
            stdout = sys.stdout
1102
 
            catcher = cStringIO.StringIO()
1103
 
            sys.stdout = catcher
1104
 
            cmd_status({"file_list":selected_list}, {})
1105
 
            info = catcher.getvalue()
1106
 
            sys.stdout = stdout
1107
 
            message = get_text_message(info)
1108
 
            
1109
 
            if message is None:
1110
 
                raise BzrCommandError("please specify a commit message",
1111
 
                                      ["use either --message or --file"])
1112
 
        elif message and file:
1113
 
            raise BzrCommandError("please specify either --message or --file")
1114
 
        
1115
 
        if file:
1116
 
            import codecs
1117
 
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1118
 
 
1119
 
        b = find_branch('.')
1120
 
        commit(b, message, verbose=verbose, specific_files=selected_list)
 
605
    takes_options = ['message', 'verbose']
 
606
    
 
607
    def run(self, message=None, verbose=False):
 
608
        if not message:
 
609
            raise BzrCommandError("please specify a commit message")
 
610
        Branch('.').commit(message, verbose=verbose)
1121
611
 
1122
612
 
1123
613
class cmd_check(Command):
1125
615
 
1126
616
    This command checks various invariants about the branch storage to
1127
617
    detect data corruption or bzr bugs.
1128
 
 
1129
 
    If given the --update flag, it will update some optional fields
1130
 
    to help ensure data consistency.
1131
 
    """
1132
 
    takes_args = ['dir?']
1133
 
 
1134
 
    def run(self, dir='.'):
1135
 
        from bzrlib.check import check
1136
 
        check(find_branch(dir))
1137
 
 
1138
 
 
1139
 
 
1140
 
class cmd_upgrade(Command):
1141
 
    """Upgrade branch storage to current format.
1142
 
 
1143
 
    This should normally be used only after the check command tells
1144
 
    you to run it.
1145
 
    """
1146
 
    takes_args = ['dir?']
1147
 
 
1148
 
    def run(self, dir='.'):
1149
 
        from bzrlib.upgrade import upgrade
1150
 
        upgrade(find_branch(dir))
 
618
    """
 
619
    takes_args = ['dir?']
 
620
    def run(self, dir='.'):
 
621
        import bzrlib.check
 
622
        bzrlib.check.check(Branch(dir, find_root=False))
1151
623
 
1152
624
 
1153
625
 
1166
638
    """Run internal test suite"""
1167
639
    hidden = True
1168
640
    def run(self):
1169
 
        from bzrlib.selftest import selftest
1170
 
        return int(not selftest())
 
641
        failures, tests = 0, 0
 
642
 
 
643
        import doctest, bzrlib.store, bzrlib.tests
 
644
        bzrlib.trace.verbose = False
 
645
 
 
646
        for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
 
647
            bzrlib.tree, bzrlib.tests, bzrlib.commands, bzrlib.add:
 
648
            mf, mt = doctest.testmod(m)
 
649
            failures += mf
 
650
            tests += mt
 
651
            print '%-40s %3d tests' % (m.__name__, mt),
 
652
            if mf:
 
653
                print '%3d FAILED!' % mf
 
654
            else:
 
655
                print
 
656
 
 
657
        print '%-40s %3d tests' % ('total', tests),
 
658
        if failures:
 
659
            print '%3d FAILED!' % failures
 
660
        else:
 
661
            print
 
662
 
1171
663
 
1172
664
 
1173
665
class cmd_version(Command):
1174
 
    """Show version of bzr."""
 
666
    """Show version of bzr"""
1175
667
    def run(self):
1176
668
        show_version()
1177
669
 
1178
670
def show_version():
1179
671
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
1180
 
    # is bzrlib itself in a branch?
1181
 
    bzrrev = bzrlib.get_bzr_revision()
1182
 
    if bzrrev:
1183
 
        print "  (bzr checkout, revision %d {%s})" % bzrrev
1184
672
    print bzrlib.__copyright__
1185
673
    print "http://bazaar-ng.org/"
1186
674
    print
1195
683
    def run(self):
1196
684
        print "it sure does!"
1197
685
 
1198
 
def parse_spec(spec):
1199
 
    """
1200
 
    >>> parse_spec(None)
1201
 
    [None, None]
1202
 
    >>> parse_spec("./")
1203
 
    ['./', None]
1204
 
    >>> parse_spec("../@")
1205
 
    ['..', -1]
1206
 
    >>> parse_spec("../f/@35")
1207
 
    ['../f', 35]
1208
 
    """
1209
 
    if spec is None:
1210
 
        return [None, None]
1211
 
    if '/@' in spec:
1212
 
        parsed = spec.split('/@')
1213
 
        assert len(parsed) == 2
1214
 
        if parsed[1] == "":
1215
 
            parsed[1] = -1
1216
 
        else:
1217
 
            parsed[1] = int(parsed[1])
1218
 
            assert parsed[1] >=0
1219
 
    else:
1220
 
        parsed = [spec, None]
1221
 
    return parsed
1222
 
 
1223
 
 
1224
 
 
1225
 
class cmd_merge(Command):
1226
 
    """Perform a three-way merge of trees.
1227
 
    
1228
 
    The SPEC parameters are working tree or revision specifiers.  Working trees
1229
 
    are specified using standard paths or urls.  No component of a directory
1230
 
    path may begin with '@'.
1231
 
    
1232
 
    Working tree examples: '.', '..', 'foo@', but NOT 'foo/@bar'
1233
 
 
1234
 
    Revisions are specified using a dirname/@revno pair, where dirname is the
1235
 
    branch directory and revno is the revision within that branch.  If no revno
1236
 
    is specified, the latest revision is used.
1237
 
 
1238
 
    Revision examples: './@127', 'foo/@', '../@1'
1239
 
 
1240
 
    The OTHER_SPEC parameter is required.  If the BASE_SPEC parameter is
1241
 
    not supplied, the common ancestor of OTHER_SPEC the current branch is used
1242
 
    as the BASE.
1243
 
 
1244
 
    merge refuses to run if there are any uncommitted changes, unless
1245
 
    --force is given.
1246
 
    """
1247
 
    takes_args = ['other_spec', 'base_spec?']
1248
 
    takes_options = ['force']
1249
 
 
1250
 
    def run(self, other_spec, base_spec=None, force=False):
1251
 
        from bzrlib.merge import merge
1252
 
        merge(parse_spec(other_spec), parse_spec(base_spec),
1253
 
              check_clean=(not force))
1254
 
 
1255
 
 
1256
 
 
1257
 
class cmd_revert(Command):
1258
 
    """Restore selected files from a previous revision.
1259
 
    """
1260
 
    takes_args = ['file+']
1261
 
    def run(self, file_list):
1262
 
        from bzrlib.branch import find_branch
1263
 
        
1264
 
        if not file_list:
1265
 
            file_list = ['.']
1266
 
            
1267
 
        b = find_branch(file_list[0])
1268
 
 
1269
 
        b.revert([b.relpath(f) for f in file_list])
1270
 
 
1271
 
 
1272
 
class cmd_merge_revert(Command):
1273
 
    """Reverse all changes since the last commit.
1274
 
 
1275
 
    Only versioned files are affected.
1276
 
 
1277
 
    TODO: Store backups of any files that will be reverted, so
1278
 
          that the revert can be undone.          
1279
 
    """
1280
 
    takes_options = ['revision']
1281
 
 
1282
 
    def run(self, revision=-1):
1283
 
        from bzrlib.merge import merge
1284
 
        merge(('.', revision), parse_spec('.'),
1285
 
              check_clean=False,
1286
 
              ignore_zero=True)
1287
 
 
1288
686
 
1289
687
class cmd_assert_fail(Command):
1290
688
    """Test reporting of assertion failures"""
1298
696
 
1299
697
    For a list of all available commands, say 'bzr help commands'."""
1300
698
    takes_args = ['topic?']
1301
 
    aliases = ['?']
1302
699
    
1303
700
    def run(self, topic=None):
1304
 
        import help
1305
 
        help.help(topic)
1306
 
 
1307
 
 
1308
 
class cmd_update_stat_cache(Command):
1309
 
    """Update stat-cache mapping inodes to SHA-1 hashes.
1310
 
 
1311
 
    For testing only."""
1312
 
    hidden = True
1313
 
    def run(self):
1314
 
        import statcache
1315
 
        b = find_branch('.')
1316
 
        statcache.update_cache(b.base, b.read_working_inventory())
1317
 
 
1318
 
 
1319
 
 
1320
 
class cmd_plugins(Command):
1321
 
    """List plugins"""
1322
 
    hidden = True
1323
 
    def run(self):
1324
 
        import bzrlib.plugin
1325
 
        from pprint import pprint
1326
 
        pprint(bzrlib.plugin.all_plugins)
1327
 
 
 
701
        help(topic)
 
702
 
 
703
 
 
704
def help(topic=None):
 
705
    if topic == None:
 
706
        print __doc__
 
707
    elif topic == 'commands':
 
708
        help_commands()
 
709
    else:
 
710
        help_on_command(topic)
 
711
 
 
712
 
 
713
def help_on_command(cmdname):
 
714
    cmdname = str(cmdname)
 
715
 
 
716
    from inspect import getdoc
 
717
    topic, cmdclass = get_cmd_class(cmdname)
 
718
 
 
719
    doc = getdoc(cmdclass)
 
720
    if doc == None:
 
721
        raise NotImplementedError("sorry, no detailed help yet for %r" % cmdname)
 
722
 
 
723
    if '\n' in doc:
 
724
        short, rest = doc.split('\n', 1)
 
725
    else:
 
726
        short = doc
 
727
        rest = ''
 
728
 
 
729
    print 'usage: bzr ' + topic,
 
730
    for aname in cmdclass.takes_args:
 
731
        aname = aname.upper()
 
732
        if aname[-1] in ['$', '+']:
 
733
            aname = aname[:-1] + '...'
 
734
        elif aname[-1] == '?':
 
735
            aname = '[' + aname[:-1] + ']'
 
736
        elif aname[-1] == '*':
 
737
            aname = '[' + aname[:-1] + '...]'
 
738
        print aname,
 
739
    print 
 
740
    print short
 
741
    if rest:
 
742
        print rest
 
743
 
 
744
    if cmdclass.takes_options:
 
745
        print
 
746
        print 'options:'
 
747
        for on in cmdclass.takes_options:
 
748
            print '    --%s' % on
 
749
 
 
750
 
 
751
def help_commands():
 
752
    """List all commands"""
 
753
    import inspect
 
754
    
 
755
    accu = []
 
756
    for k, v in globals().items():
 
757
        if k.startswith('cmd_'):
 
758
            accu.append((k[4:].replace('_','-'), v))
 
759
    accu.sort()
 
760
    for cmdname, cmdclass in accu:
 
761
        if cmdclass.hidden:
 
762
            continue
 
763
        print cmdname
 
764
        help = inspect.getdoc(cmdclass)
 
765
        if help:
 
766
            print "    " + help.split('\n', 1)[0]
 
767
 
 
768
 
 
769
######################################################################
 
770
# main routine
1328
771
 
1329
772
 
1330
773
# list of all available options; the rhs can be either None for an
1332
775
# the type.
1333
776
OPTIONS = {
1334
777
    'all':                    None,
1335
 
    'diff-options':           str,
1336
778
    'help':                   None,
1337
 
    'file':                   unicode,
1338
 
    'force':                  None,
1339
 
    'format':                 unicode,
1340
 
    'forward':                None,
1341
779
    'message':                unicode,
1342
 
    'no-recurse':             None,
1343
780
    'profile':                None,
1344
 
    'revision':               _parse_revision_str,
 
781
    'revision':               int,
1345
782
    'show-ids':               None,
1346
783
    'timezone':               str,
1347
784
    'verbose':                None,
1348
785
    'version':                None,
1349
786
    'email':                  None,
1350
 
    'update':                 None,
1351
787
    }
1352
788
 
1353
789
SHORT_OPTIONS = {
1354
 
    'F':                      'file', 
1355
 
    'h':                      'help',
1356
790
    'm':                      'message',
1357
791
    'r':                      'revision',
1358
792
    'v':                      'verbose',
1375
809
    (['status'], {'all': True})
1376
810
    >>> parse_args('commit --message=biter'.split())
1377
811
    (['commit'], {'message': u'biter'})
1378
 
    >>> parse_args('log -r 500'.split())
1379
 
    (['log'], {'revision': 500})
1380
 
    >>> parse_args('log -r500:600'.split())
1381
 
    (['log'], {'revision': [500, 600]})
1382
 
    >>> parse_args('log -vr500:600'.split())
1383
 
    (['log'], {'verbose': True, 'revision': [500, 600]})
1384
 
    >>> parse_args('log -rv500:600'.split()) #the r takes an argument
1385
 
    Traceback (most recent call last):
1386
 
    ...
1387
 
    ValueError: invalid literal for int(): v500
1388
812
    """
1389
813
    args = []
1390
814
    opts = {}
1404
828
                else:
1405
829
                    optname = a[2:]
1406
830
                if optname not in OPTIONS:
1407
 
                    raise BzrError('unknown long option %r' % a)
 
831
                    bailout('unknown long option %r' % a)
1408
832
            else:
1409
833
                shortopt = a[1:]
1410
 
                if shortopt in SHORT_OPTIONS:
1411
 
                    # Multi-character options must have a space to delimit
1412
 
                    # their value
1413
 
                    optname = SHORT_OPTIONS[shortopt]
1414
 
                else:
1415
 
                    # Single character short options, can be chained,
1416
 
                    # and have their value appended to their name
1417
 
                    shortopt = a[1:2]
1418
 
                    if shortopt not in SHORT_OPTIONS:
1419
 
                        # We didn't find the multi-character name, and we
1420
 
                        # didn't find the single char name
1421
 
                        raise BzrError('unknown short option %r' % a)
1422
 
                    optname = SHORT_OPTIONS[shortopt]
1423
 
 
1424
 
                    if a[2:]:
1425
 
                        # There are extra things on this option
1426
 
                        # see if it is the value, or if it is another
1427
 
                        # short option
1428
 
                        optargfn = OPTIONS[optname]
1429
 
                        if optargfn is None:
1430
 
                            # This option does not take an argument, so the
1431
 
                            # next entry is another short option, pack it back
1432
 
                            # into the list
1433
 
                            argv.insert(0, '-' + a[2:])
1434
 
                        else:
1435
 
                            # This option takes an argument, so pack it
1436
 
                            # into the array
1437
 
                            optarg = a[2:]
 
834
                if shortopt not in SHORT_OPTIONS:
 
835
                    bailout('unknown short option %r' % a)
 
836
                optname = SHORT_OPTIONS[shortopt]
1438
837
            
1439
838
            if optname in opts:
1440
839
                # XXX: Do we ever want to support this, e.g. for -r?
1441
 
                raise BzrError('repeated option %r' % a)
 
840
                bailout('repeated option %r' % a)
1442
841
                
1443
842
            optargfn = OPTIONS[optname]
1444
843
            if optargfn:
1445
844
                if optarg == None:
1446
845
                    if not argv:
1447
 
                        raise BzrError('option %r needs an argument' % a)
 
846
                        bailout('option %r needs an argument' % a)
1448
847
                    else:
1449
848
                        optarg = argv.pop(0)
1450
849
                opts[optname] = optargfn(optarg)
1451
850
            else:
1452
851
                if optarg != None:
1453
 
                    raise BzrError('option %r takes no argument' % optname)
 
852
                    bailout('option %r takes no argument' % optname)
1454
853
                opts[optname] = True
1455
854
        else:
1456
855
            args.append(a)
1504
903
    return argdict
1505
904
 
1506
905
 
1507
 
def _parse_master_args(argv):
1508
 
    """Parse the arguments that always go with the original command.
1509
 
    These are things like bzr --no-plugins, etc.
1510
 
 
1511
 
    There are now 2 types of option flags. Ones that come *before* the command,
1512
 
    and ones that come *after* the command.
1513
 
    Ones coming *before* the command are applied against all possible commands.
1514
 
    And are generally applied before plugins are loaded.
1515
 
 
1516
 
    The current list are:
1517
 
        --builtin   Allow plugins to load, but don't let them override builtin commands,
1518
 
                    they will still be allowed if they do not override a builtin.
1519
 
        --no-plugins    Don't load any plugins. This lets you get back to official source
1520
 
                        behavior.
1521
 
        --profile   Enable the hotspot profile before running the command.
1522
 
                    For backwards compatibility, this is also a non-master option.
1523
 
        --version   Spit out the version of bzr that is running and exit.
1524
 
                    This is also a non-master option.
1525
 
        --help      Run help and exit, also a non-master option (I think that should stay, though)
1526
 
 
1527
 
    >>> argv, opts = _parse_master_args(['bzr', '--test'])
1528
 
    Traceback (most recent call last):
1529
 
    ...
1530
 
    BzrCommandError: Invalid master option: 'test'
1531
 
    >>> argv, opts = _parse_master_args(['bzr', '--version', 'command'])
1532
 
    >>> print argv
1533
 
    ['command']
1534
 
    >>> print opts['version']
1535
 
    True
1536
 
    >>> argv, opts = _parse_master_args(['bzr', '--profile', 'command', '--more-options'])
1537
 
    >>> print argv
1538
 
    ['command', '--more-options']
1539
 
    >>> print opts['profile']
1540
 
    True
1541
 
    >>> argv, opts = _parse_master_args(['bzr', '--no-plugins', 'command'])
1542
 
    >>> print argv
1543
 
    ['command']
1544
 
    >>> print opts['no-plugins']
1545
 
    True
1546
 
    >>> print opts['profile']
1547
 
    False
1548
 
    >>> argv, opts = _parse_master_args(['bzr', 'command', '--profile'])
1549
 
    >>> print argv
1550
 
    ['command', '--profile']
1551
 
    >>> print opts['profile']
1552
 
    False
1553
 
    """
1554
 
    master_opts = {'builtin':False,
1555
 
        'no-plugins':False,
1556
 
        'version':False,
1557
 
        'profile':False,
1558
 
        'help':False
1559
 
    }
1560
 
 
1561
 
    # This is the point where we could hook into argv[0] to determine
1562
 
    # what front-end is supposed to be run
1563
 
    # For now, we are just ignoring it.
1564
 
    cmd_name = argv.pop(0)
1565
 
    for arg in argv[:]:
1566
 
        if arg[:2] != '--': # at the first non-option, we return the rest
1567
 
            break
1568
 
        arg = arg[2:] # Remove '--'
1569
 
        if arg not in master_opts:
1570
 
            # We could say that this is not an error, that we should
1571
 
            # just let it be handled by the main section instead
1572
 
            raise BzrCommandError('Invalid master option: %r' % arg)
1573
 
        argv.pop(0) # We are consuming this entry
1574
 
        master_opts[arg] = True
1575
 
    return argv, master_opts
1576
 
 
1577
 
 
1578
906
 
1579
907
def run_bzr(argv):
1580
908
    """Execute a command.
1582
910
    This is similar to main(), but without all the trappings for
1583
911
    logging and error handling.  
1584
912
    """
 
913
 
1585
914
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
1586
915
    
1587
916
    try:
1588
 
        # some options like --builtin and --no-plugins have special effects
1589
 
        argv, master_opts = _parse_master_args(argv)
1590
 
        if not master_opts['no-plugins']:
1591
 
            from bzrlib.plugin import load_plugins
1592
 
            load_plugins()
1593
 
 
1594
 
        args, opts = parse_args(argv)
1595
 
 
1596
 
        if master_opts['help']:
1597
 
            from bzrlib.help import help
1598
 
            if argv:
1599
 
                help(argv[0])
1600
 
            else:
1601
 
                help()
1602
 
            return 0            
1603
 
            
 
917
        args, opts = parse_args(argv[1:])
1604
918
        if 'help' in opts:
1605
 
            from bzrlib.help import help
1606
919
            if args:
1607
920
                help(args[0])
1608
921
            else:
1609
922
                help()
1610
923
            return 0
1611
924
        elif 'version' in opts:
1612
 
            show_version()
 
925
            cmd_version([], [])
1613
926
            return 0
1614
 
        elif args and args[0] == 'builtin':
1615
 
            include_plugins=False
1616
 
            args = args[1:]
1617
927
        cmd = str(args.pop(0))
1618
928
    except IndexError:
1619
 
        import help
1620
 
        help.help()
 
929
        log_error('usage: bzr COMMAND')
 
930
        log_error('  try "bzr help"')
1621
931
        return 1
1622
 
          
1623
 
 
1624
 
    plugins_override = not (master_opts['builtin'])
1625
 
    canonical_cmd, cmd_class = get_cmd_class(cmd, plugins_override=plugins_override)
1626
 
 
1627
 
    profile = master_opts['profile']
1628
 
    # For backwards compatibility, I would rather stick with --profile being a
1629
 
    # master/global option
 
932
 
 
933
    canonical_cmd, cmd_class = get_cmd_class(cmd)
 
934
 
 
935
    # global option
1630
936
    if 'profile' in opts:
1631
937
        profile = True
1632
938
        del opts['profile']
 
939
    else:
 
940
        profile = False
1633
941
 
1634
942
    # check options are reasonable
1635
943
    allowed = cmd_class.takes_options
1636
944
    for oname in opts:
1637
945
        if oname not in allowed:
1638
 
            raise BzrCommandError("option '--%s' is not allowed for command %r"
 
946
            raise BzrCommandError("option %r is not allowed for command %r"
1639
947
                                  % (oname, cmd))
1640
948
 
1641
949
    # mix arguments and options into one dictionary
1645
953
        cmdopts[k.replace('-', '_')] = v
1646
954
 
1647
955
    if profile:
1648
 
        import hotshot, tempfile
 
956
        import hotshot
1649
957
        pffileno, pfname = tempfile.mkstemp()
1650
958
        try:
1651
959
            prof = hotshot.Profile(pfname)
1660
968
            ## print_stats seems hardcoded to stdout
1661
969
            stats.print_stats(20)
1662
970
            
1663
 
            return ret.status
 
971
            return ret
1664
972
 
1665
973
        finally:
1666
974
            os.close(pffileno)
1667
975
            os.remove(pfname)
1668
976
    else:
1669
 
        return cmd_class(cmdopts, cmdargs).status 
1670
 
 
1671
 
 
1672
 
def _report_exception(summary, quiet=False):
 
977
        cmdobj = cmd_class(cmdopts, cmdargs) or 0
 
978
 
 
979
 
 
980
 
 
981
def _report_exception(e, summary, quiet=False):
1673
982
    import traceback
1674
983
    log_error('bzr: ' + summary)
1675
 
    bzrlib.trace.log_exception()
 
984
    bzrlib.trace.log_exception(e)
1676
985
 
1677
986
    if not quiet:
1678
987
        tb = sys.exc_info()[2]
1684
993
 
1685
994
 
1686
995
def main(argv):
 
996
    import errno
1687
997
    
1688
 
    bzrlib.trace.open_tracefile(argv)
 
998
    bzrlib.trace.create_tracefile(argv)
1689
999
 
1690
1000
    try:
1691
1001
        try:
1692
 
            try:
1693
 
                return run_bzr(argv)
1694
 
            finally:
1695
 
                # do this here inside the exception wrappers to catch EPIPE
1696
 
                sys.stdout.flush()
 
1002
            ret = run_bzr(argv)
 
1003
            # do this here to catch EPIPE
 
1004
            sys.stdout.flush()
 
1005
            return ret
1697
1006
        except BzrError, e:
1698
1007
            quiet = isinstance(e, (BzrCommandError))
1699
 
            _report_exception('error: ' + e.args[0], quiet=quiet)
 
1008
            _report_exception(e, 'error: ' + e.args[0], quiet=quiet)
1700
1009
            if len(e.args) > 1:
1701
1010
                for h in e.args[1]:
1702
1011
                    # some explanation or hints
1706
1015
            msg = 'assertion failed'
1707
1016
            if str(e):
1708
1017
                msg += ': ' + str(e)
1709
 
            _report_exception(msg)
 
1018
            _report_exception(e, msg)
1710
1019
            return 2
1711
1020
        except KeyboardInterrupt, e:
1712
 
            _report_exception('interrupted', quiet=True)
 
1021
            _report_exception(e, 'interrupted', quiet=True)
1713
1022
            return 2
1714
1023
        except Exception, e:
1715
 
            import errno
1716
1024
            quiet = False
1717
 
            if (isinstance(e, IOError) 
1718
 
                and hasattr(e, 'errno')
1719
 
                and e.errno == errno.EPIPE):
 
1025
            if isinstance(e, IOError) and e.errno == errno.EPIPE:
1720
1026
                quiet = True
1721
1027
                msg = 'broken pipe'
1722
1028
            else:
1723
1029
                msg = str(e).rstrip('\n')
1724
 
            _report_exception(msg, quiet)
 
1030
            _report_exception(e, msg, quiet)
1725
1031
            return 2
1726
1032
    finally:
1727
1033
        bzrlib.trace.close_trace()