~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-06-22 09:35:24 UTC
  • Revision ID: mbp@sourcefrog.net-20050622093524-b15e2d374c2ae6ea
- move standard plugins from contrib/plugins to just ./plugins

Show diffs side-by-side

added added

removed removed

Lines of Context:
20
20
 
21
21
import bzrlib
22
22
from bzrlib.trace import mutter, note, log_error
23
 
from bzrlib.errors import bailout, BzrError, BzrCheckError, BzrCommandError
 
23
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
24
24
from bzrlib.osutils import quotefn
25
25
from bzrlib import Branch, Inventory, InventoryEntry, BZRDIR, \
26
26
     format_date
27
27
 
28
28
 
 
29
plugin_cmds = {}
 
30
 
 
31
 
 
32
def register_command(cmd):
 
33
    "Utility function to help register a command"
 
34
    global plugin_cmds
 
35
    k = cmd.__name__
 
36
    if k.startswith("cmd_"):
 
37
        k_unsquished = _unsquish_command_name(k)
 
38
    else:
 
39
        k_unsquished = k
 
40
    if not plugin_cmds.has_key(k_unsquished):
 
41
        plugin_cmds[k_unsquished] = cmd
 
42
    else:
 
43
        log_error('Two plugins defined the same command: %r' % k)
 
44
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
 
45
 
 
46
 
29
47
def _squish_command_name(cmd):
30
48
    return 'cmd_' + cmd.replace('-', '_')
31
49
 
68
86
        revs = int(revstr)
69
87
    return revs
70
88
 
71
 
def get_all_cmds():
72
 
    """Return canonical name and class for all registered commands."""
 
89
 
 
90
 
 
91
def _get_cmd_dict(plugins_override=True):
 
92
    d = {}
73
93
    for k, v in globals().iteritems():
74
94
        if k.startswith("cmd_"):
75
 
            yield _unsquish_command_name(k), v
76
 
 
77
 
def get_cmd_class(cmd):
 
95
            d[_unsquish_command_name(k)] = v
 
96
    # If we didn't load plugins, the plugin_cmds dict will be empty
 
97
    if plugins_override:
 
98
        d.update(plugin_cmds)
 
99
    else:
 
100
        d2 = plugin_cmds.copy()
 
101
        d2.update(d)
 
102
        d = d2
 
103
    return d
 
104
 
 
105
    
 
106
def get_all_cmds(plugins_override=True):
 
107
    """Return canonical name and class for all registered commands."""
 
108
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
 
109
        yield k,v
 
110
 
 
111
 
 
112
def get_cmd_class(cmd, plugins_override=True):
78
113
    """Return the canonical name and command class for a command.
79
114
    """
80
115
    cmd = str(cmd)                      # not unicode
81
116
 
82
117
    # first look up this command under the specified name
 
118
    cmds = _get_cmd_dict(plugins_override=plugins_override)
83
119
    try:
84
 
        return cmd, globals()[_squish_command_name(cmd)]
 
120
        return cmd, cmds[cmd]
85
121
    except KeyError:
86
122
        pass
87
123
 
88
124
    # look for any command which claims this as an alias
89
 
    for cmdname, cmdclass in get_all_cmds():
 
125
    for cmdname, cmdclass in cmds.iteritems():
90
126
        if cmd in cmdclass.aliases:
91
127
            return cmdname, cmdclass
92
128
 
165
201
        import os.path
166
202
        bzrpath = os.environ.get('BZRPATH', '')
167
203
 
168
 
        for dir in bzrpath.split(':'):
 
204
        for dir in bzrpath.split(os.pathsep):
169
205
            path = os.path.join(dir, cmd)
170
206
            if os.path.isfile(path):
171
207
                return ExternalCommand(path)
177
213
    def __init__(self, path):
178
214
        self.path = path
179
215
 
180
 
        # TODO: If either of these fail, we should detect that and
181
 
        # assume that path is not really a bzr plugin after all.
182
 
 
183
216
        pipe = os.popen('%s --bzr-usage' % path, 'r')
184
217
        self.takes_options = pipe.readline().split()
 
218
 
 
219
        for opt in self.takes_options:
 
220
            if not opt in OPTIONS:
 
221
                raise BzrError("Unknown option '%s' returned by external command %s"
 
222
                               % (opt, path))
 
223
 
 
224
        # TODO: Is there any way to check takes_args is valid here?
185
225
        self.takes_args = pipe.readline().split()
186
 
        pipe.close()
 
226
 
 
227
        if pipe.close() is not None:
 
228
            raise BzrError("Failed funning '%s --bzr-usage'" % path)
187
229
 
188
230
        pipe = os.popen('%s --bzr-help' % path, 'r')
189
231
        self.__doc__ = pipe.read()
190
 
        pipe.close()
 
232
        if pipe.close() is not None:
 
233
            raise BzrError("Failed funning '%s --bzr-help'" % path)
191
234
 
192
235
    def __call__(self, options, arguments):
193
236
        Command.__init__(self, options, arguments)
200
243
        keys = kargs.keys()
201
244
        keys.sort()
202
245
        for name in keys:
 
246
            optname = name.replace('_','-')
203
247
            value = kargs[name]
204
 
            if OPTIONS.has_key(name):
 
248
            if OPTIONS.has_key(optname):
205
249
                # it's an option
206
 
                opts.append('--%s' % name)
 
250
                opts.append('--%s' % optname)
207
251
                if value is not None and value is not True:
208
252
                    opts.append(str(value))
209
253
            else:
319
363
        bzrlib.add.smart_add(file_list, verbose, not no_recurse)
320
364
 
321
365
 
 
366
 
 
367
class cmd_mkdir(Command):
 
368
    """Create a new versioned directory.
 
369
 
 
370
    This is equivalent to creating the directory and then adding it.
 
371
    """
 
372
    takes_args = ['dir+']
 
373
 
 
374
    def run(self, dir_list):
 
375
        import os
 
376
        import bzrlib.branch
 
377
        
 
378
        b = None
 
379
        
 
380
        for d in dir_list:
 
381
            os.mkdir(d)
 
382
            if not b:
 
383
                b = bzrlib.branch.Branch(d)
 
384
            b.add([d], verbose=True)
 
385
 
 
386
 
322
387
class cmd_relpath(Command):
323
388
    """Show path of a file relative to root"""
324
389
    takes_args = ['filename']
414
479
            if errno == errno.ENOENT:
415
480
                raise
416
481
        if location is None:
417
 
            location = stored_loc
418
 
        if location is None:
419
 
            raise BzrCommandError("No pull location known or specified.")
 
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
420
487
        from branch import find_branch, DivergedBranches
421
488
        br_from = find_branch(location)
422
489
        location = pull_loc(br_from)
426
493
        except DivergedBranches:
427
494
            raise BzrCommandError("These branches have diverged.  Try merge.")
428
495
            
429
 
        merge(('.', -1), ('.', old_revno))
 
496
        merge(('.', -1), ('.', old_revno), check_clean=False)
430
497
        if location != stored_loc:
431
498
            br_to.controlfile("x-pull", "wb").write(location + "\n")
432
499
 
435
502
class cmd_branch(Command):
436
503
    """Create a new copy of a branch.
437
504
 
438
 
    If the TO_LOCATION is omitted, the last component of the
439
 
    FROM_LOCATION will be used.  In other words,
440
 
    "branch ../foo/bar" will attempt to create ./bar.
 
505
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
506
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
507
 
 
508
    To retrieve the branch as of a particular revision, supply the --revision
 
509
    parameter, as in "branch foo/bar -r 5".
441
510
    """
442
511
    takes_args = ['from_location', 'to_location?']
 
512
    takes_options = ['revision']
443
513
 
444
 
    def run(self, from_location, to_location=None):
 
514
    def run(self, from_location, to_location=None, revision=None):
445
515
        import errno
446
516
        from bzrlib.merge import merge
447
 
        
 
517
        from branch import find_branch, DivergedBranches, NoSuchRevision
 
518
        from shutil import rmtree
 
519
        try:
 
520
            br_from = find_branch(from_location)
 
521
        except OSError, e:
 
522
            if e.errno == errno.ENOENT:
 
523
                raise BzrCommandError('Source location "%s" does not exist.' %
 
524
                                      to_location)
 
525
            else:
 
526
                raise
 
527
 
448
528
        if to_location is None:
449
 
            to_location = os.path.basename(from_location)
450
 
            # FIXME: If there's a trailing slash, keep removing them
451
 
            # until we find the right bit
 
529
            to_location = os.path.basename(from_location.rstrip("/\\"))
452
530
 
453
531
        try:
454
532
            os.mkdir(to_location)
462
540
            else:
463
541
                raise
464
542
        br_to = Branch(to_location, init=True)
465
 
        from branch import find_branch, DivergedBranches
 
543
 
466
544
        try:
467
 
            br_from = find_branch(from_location)
468
 
        except OSError, e:
469
 
            if e.errno == errno.ENOENT:
470
 
                raise BzrCommandError('Source location "%s" does not exist.' %
471
 
                                      to_location)
472
 
            else:
473
 
                raise
474
 
 
 
545
            br_to.update_revisions(br_from, stop_revision=revision)
 
546
        except NoSuchRevision:
 
547
            rmtree(to_location)
 
548
            msg = "The branch %s has no revision %d." % (from_location,
 
549
                                                         revision)
 
550
            raise BzrCommandError(msg)
 
551
        merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
552
              check_clean=False, ignore_zero=True)
475
553
        from_location = pull_loc(br_from)
476
 
        br_to.update_revisions(br_from)
477
 
        merge((to_location, -1), (to_location, 0), this_dir=to_location,
478
 
              check_clean=False)
479
554
        br_to.controlfile("x-pull", "wb").write(from_location + "\n")
480
555
 
481
556
 
548
623
        b = Branch(filename)
549
624
        i = b.inventory.path2id(b.relpath(filename))
550
625
        if i == None:
551
 
            bailout("%r is not a versioned file" % filename)
 
626
            raise BzrError("%r is not a versioned file" % filename)
552
627
        else:
553
628
            print i
554
629
 
565
640
        inv = b.inventory
566
641
        fid = inv.path2id(b.relpath(filename))
567
642
        if fid == None:
568
 
            bailout("%r is not a versioned file" % filename)
 
643
            raise BzrError("%r is not a versioned file" % filename)
569
644
        for fip in inv.get_idpath(fid):
570
645
            print fip
571
646
 
631
706
    
632
707
    takes_args = ['file*']
633
708
    takes_options = ['revision', 'diff-options']
634
 
    aliases = ['di']
 
709
    aliases = ['di', 'dif']
635
710
 
636
711
    def run(self, revision=None, file_list=None, diff_options=None):
637
712
        from bzrlib.diff import show_diff
939
1014
class cmd_export(Command):
940
1015
    """Export past revision to destination directory.
941
1016
 
942
 
    If no revision is specified this exports the last committed revision."""
 
1017
    If no revision is specified this exports the last committed revision.
 
1018
 
 
1019
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
1020
    given, exports to a directory (equivalent to --format=dir)."""
 
1021
    # TODO: list known exporters
943
1022
    takes_args = ['dest']
944
 
    takes_options = ['revision']
945
 
    def run(self, dest, revision=None):
 
1023
    takes_options = ['revision', 'format']
 
1024
    def run(self, dest, revision=None, format='dir'):
946
1025
        b = Branch('.')
947
1026
        if revision == None:
948
1027
            rh = b.revision_history()[-1]
949
1028
        else:
950
1029
            rh = b.lookup_revision(int(revision))
951
1030
        t = b.revision_tree(rh)
952
 
        t.export(dest)
 
1031
        t.export(dest, format)
953
1032
 
954
1033
 
955
1034
class cmd_cat(Command):
1015
1094
 
1016
1095
    This command checks various invariants about the branch storage to
1017
1096
    detect data corruption or bzr bugs.
 
1097
 
 
1098
    If given the --update flag, it will update some optional fields
 
1099
    to help ensure data consistency.
1018
1100
    """
1019
1101
    takes_args = ['dir?']
 
1102
 
1020
1103
    def run(self, dir='.'):
1021
1104
        import bzrlib.check
1022
1105
        bzrlib.check.check(Branch(dir))
1023
1106
 
1024
1107
 
1025
1108
 
 
1109
class cmd_upgrade(Command):
 
1110
    """Upgrade branch storage to current format.
 
1111
 
 
1112
    This should normally be used only after the check command tells
 
1113
    you to run it.
 
1114
    """
 
1115
    takes_args = ['dir?']
 
1116
 
 
1117
    def run(self, dir='.'):
 
1118
        from bzrlib.upgrade import upgrade
 
1119
        upgrade(Branch(dir))
 
1120
 
 
1121
 
 
1122
 
1026
1123
class cmd_whoami(Command):
1027
1124
    """Show bzr user id."""
1028
1125
    takes_options = ['email']
1039
1136
    hidden = True
1040
1137
    def run(self):
1041
1138
        from bzrlib.selftest import selftest
1042
 
        if selftest():
1043
 
            return 0
1044
 
        else:
1045
 
            return 1
1046
 
 
 
1139
        return int(not selftest())
1047
1140
 
1048
1141
 
1049
1142
class cmd_version(Command):
1140
1233
    takes_options = ['revision']
1141
1234
 
1142
1235
    def run(self, revision=-1):
 
1236
        from bzrlib.merge import merge
1143
1237
        merge(('.', revision), parse_spec('.'),
1144
1238
              check_clean=False,
1145
1239
              ignore_zero=True)
1176
1270
 
1177
1271
 
1178
1272
 
 
1273
class cmd_plugins(Command):
 
1274
    """List plugins"""
 
1275
    hidden = True
 
1276
    def run(self):
 
1277
        import bzrlib.plugin
 
1278
        from pprint import pprint
 
1279
        pprint(bzrlib.plugin.all_plugins)
 
1280
 
 
1281
 
 
1282
 
1179
1283
# list of all available options; the rhs can be either None for an
1180
1284
# option that takes no argument, or a constructor function that checks
1181
1285
# the type.
1185
1289
    'help':                   None,
1186
1290
    'file':                   unicode,
1187
1291
    'force':                  None,
 
1292
    'format':                 unicode,
1188
1293
    'forward':                None,
1189
1294
    'message':                unicode,
1190
1295
    'no-recurse':             None,
1195
1300
    'verbose':                None,
1196
1301
    'version':                None,
1197
1302
    'email':                  None,
 
1303
    'update':                 None,
1198
1304
    }
1199
1305
 
1200
1306
SHORT_OPTIONS = {
1222
1328
    (['status'], {'all': True})
1223
1329
    >>> parse_args('commit --message=biter'.split())
1224
1330
    (['commit'], {'message': u'biter'})
 
1331
    >>> parse_args('log -r 500'.split())
 
1332
    (['log'], {'revision': 500})
 
1333
    >>> parse_args('log -r500:600'.split())
 
1334
    (['log'], {'revision': [500, 600]})
 
1335
    >>> parse_args('log -vr500:600'.split())
 
1336
    (['log'], {'verbose': True, 'revision': [500, 600]})
 
1337
    >>> parse_args('log -rv500:600'.split()) #the r takes an argument
 
1338
    Traceback (most recent call last):
 
1339
    ...
 
1340
    ValueError: invalid literal for int(): v500
1225
1341
    """
1226
1342
    args = []
1227
1343
    opts = {}
1241
1357
                else:
1242
1358
                    optname = a[2:]
1243
1359
                if optname not in OPTIONS:
1244
 
                    bailout('unknown long option %r' % a)
 
1360
                    raise BzrError('unknown long option %r' % a)
1245
1361
            else:
1246
1362
                shortopt = a[1:]
1247
 
                if shortopt not in SHORT_OPTIONS:
1248
 
                    bailout('unknown short option %r' % a)
1249
 
                optname = SHORT_OPTIONS[shortopt]
 
1363
                if shortopt in SHORT_OPTIONS:
 
1364
                    # Multi-character options must have a space to delimit
 
1365
                    # their value
 
1366
                    optname = SHORT_OPTIONS[shortopt]
 
1367
                else:
 
1368
                    # Single character short options, can be chained,
 
1369
                    # and have their value appended to their name
 
1370
                    shortopt = a[1:2]
 
1371
                    if shortopt not in SHORT_OPTIONS:
 
1372
                        # We didn't find the multi-character name, and we
 
1373
                        # didn't find the single char name
 
1374
                        raise BzrError('unknown short option %r' % a)
 
1375
                    optname = SHORT_OPTIONS[shortopt]
 
1376
 
 
1377
                    if a[2:]:
 
1378
                        # There are extra things on this option
 
1379
                        # see if it is the value, or if it is another
 
1380
                        # short option
 
1381
                        optargfn = OPTIONS[optname]
 
1382
                        if optargfn is None:
 
1383
                            # This option does not take an argument, so the
 
1384
                            # next entry is another short option, pack it back
 
1385
                            # into the list
 
1386
                            argv.insert(0, '-' + a[2:])
 
1387
                        else:
 
1388
                            # This option takes an argument, so pack it
 
1389
                            # into the array
 
1390
                            optarg = a[2:]
1250
1391
            
1251
1392
            if optname in opts:
1252
1393
                # XXX: Do we ever want to support this, e.g. for -r?
1253
 
                bailout('repeated option %r' % a)
 
1394
                raise BzrError('repeated option %r' % a)
1254
1395
                
1255
1396
            optargfn = OPTIONS[optname]
1256
1397
            if optargfn:
1257
1398
                if optarg == None:
1258
1399
                    if not argv:
1259
 
                        bailout('option %r needs an argument' % a)
 
1400
                        raise BzrError('option %r needs an argument' % a)
1260
1401
                    else:
1261
1402
                        optarg = argv.pop(0)
1262
1403
                opts[optname] = optargfn(optarg)
1263
1404
            else:
1264
1405
                if optarg != None:
1265
 
                    bailout('option %r takes no argument' % optname)
 
1406
                    raise BzrError('option %r takes no argument' % optname)
1266
1407
                opts[optname] = True
1267
1408
        else:
1268
1409
            args.append(a)
1316
1457
    return argdict
1317
1458
 
1318
1459
 
 
1460
def _parse_master_args(argv):
 
1461
    """Parse the arguments that always go with the original command.
 
1462
    These are things like bzr --no-plugins, etc.
 
1463
 
 
1464
    There are now 2 types of option flags. Ones that come *before* the command,
 
1465
    and ones that come *after* the command.
 
1466
    Ones coming *before* the command are applied against all possible commands.
 
1467
    And are generally applied before plugins are loaded.
 
1468
 
 
1469
    The current list are:
 
1470
        --builtin   Allow plugins to load, but don't let them override builtin commands,
 
1471
                    they will still be allowed if they do not override a builtin.
 
1472
        --no-plugins    Don't load any plugins. This lets you get back to official source
 
1473
                        behavior.
 
1474
        --profile   Enable the hotspot profile before running the command.
 
1475
                    For backwards compatibility, this is also a non-master option.
 
1476
        --version   Spit out the version of bzr that is running and exit.
 
1477
                    This is also a non-master option.
 
1478
        --help      Run help and exit, also a non-master option (I think that should stay, though)
 
1479
 
 
1480
    >>> argv, opts = _parse_master_args(['bzr', '--test'])
 
1481
    Traceback (most recent call last):
 
1482
    ...
 
1483
    BzrCommandError: Invalid master option: 'test'
 
1484
    >>> argv, opts = _parse_master_args(['bzr', '--version', 'command'])
 
1485
    >>> print argv
 
1486
    ['command']
 
1487
    >>> print opts['version']
 
1488
    True
 
1489
    >>> argv, opts = _parse_master_args(['bzr', '--profile', 'command', '--more-options'])
 
1490
    >>> print argv
 
1491
    ['command', '--more-options']
 
1492
    >>> print opts['profile']
 
1493
    True
 
1494
    >>> argv, opts = _parse_master_args(['bzr', '--no-plugins', 'command'])
 
1495
    >>> print argv
 
1496
    ['command']
 
1497
    >>> print opts['no-plugins']
 
1498
    True
 
1499
    >>> print opts['profile']
 
1500
    False
 
1501
    >>> argv, opts = _parse_master_args(['bzr', 'command', '--profile'])
 
1502
    >>> print argv
 
1503
    ['command', '--profile']
 
1504
    >>> print opts['profile']
 
1505
    False
 
1506
    """
 
1507
    master_opts = {'builtin':False,
 
1508
        'no-plugins':False,
 
1509
        'version':False,
 
1510
        'profile':False,
 
1511
        'help':False
 
1512
    }
 
1513
 
 
1514
    # This is the point where we could hook into argv[0] to determine
 
1515
    # what front-end is supposed to be run
 
1516
    # For now, we are just ignoring it.
 
1517
    cmd_name = argv.pop(0)
 
1518
    for arg in argv[:]:
 
1519
        if arg[:2] != '--': # at the first non-option, we return the rest
 
1520
            break
 
1521
        arg = arg[2:] # Remove '--'
 
1522
        if arg not in master_opts:
 
1523
            # We could say that this is not an error, that we should
 
1524
            # just let it be handled by the main section instead
 
1525
            raise BzrCommandError('Invalid master option: %r' % arg)
 
1526
        argv.pop(0) # We are consuming this entry
 
1527
        master_opts[arg] = True
 
1528
    return argv, master_opts
 
1529
 
 
1530
 
1319
1531
 
1320
1532
def run_bzr(argv):
1321
1533
    """Execute a command.
1326
1538
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
1327
1539
    
1328
1540
    try:
1329
 
        args, opts = parse_args(argv[1:])
 
1541
        # some options like --builtin and --no-plugins have special effects
 
1542
        argv, master_opts = _parse_master_args(argv)
 
1543
        if not master_opts['no-plugins']:
 
1544
            bzrlib.load_plugins()
 
1545
 
 
1546
        args, opts = parse_args(argv)
 
1547
 
 
1548
        if master_opts['help']:
 
1549
            from bzrlib.help import help
 
1550
            if argv:
 
1551
                help(argv[0])
 
1552
            else:
 
1553
                help()
 
1554
            return 0            
 
1555
            
1330
1556
        if 'help' in opts:
1331
 
            import help
 
1557
            from bzrlib.help import help
1332
1558
            if args:
1333
 
                help.help(args[0])
 
1559
                help(args[0])
1334
1560
            else:
1335
 
                help.help()
 
1561
                help()
1336
1562
            return 0
1337
1563
        elif 'version' in opts:
1338
1564
            show_version()
1339
1565
            return 0
 
1566
        elif args and args[0] == 'builtin':
 
1567
            include_plugins=False
 
1568
            args = args[1:]
1340
1569
        cmd = str(args.pop(0))
1341
1570
    except IndexError:
1342
1571
        import help
1344
1573
        return 1
1345
1574
          
1346
1575
 
1347
 
    canonical_cmd, cmd_class = get_cmd_class(cmd)
 
1576
    plugins_override = not (master_opts['builtin'])
 
1577
    canonical_cmd, cmd_class = get_cmd_class(cmd, plugins_override=plugins_override)
1348
1578
 
1349
 
    # global option
 
1579
    profile = master_opts['profile']
 
1580
    # For backwards compatibility, I would rather stick with --profile being a
 
1581
    # master/global option
1350
1582
    if 'profile' in opts:
1351
1583
        profile = True
1352
1584
        del opts['profile']
1353
 
    else:
1354
 
        profile = False
1355
1585
 
1356
1586
    # check options are reasonable
1357
1587
    allowed = cmd_class.takes_options