~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-08-25 07:46:11 UTC
  • Revision ID: mbp@sourcefrog.net-20050825074611-98130ea6d05d9d2a
- add functions to enable and disable default logging, so that we can
  turn it off while running the tests

- default logging gets turned on from the bzr main function so that
  other applications using the library can make their own decisions

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
 
19
 
import sys, os
 
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
 
 
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
 
 
30
import sys
 
31
import os
20
32
 
21
33
import bzrlib
22
34
from bzrlib.trace import mutter, note, log_error, warning
136
148
        raise BzrCommandError(msg)
137
149
    
138
150
 
 
151
def get_merge_type(typestring):
 
152
    """Attempt to find the merge class/factory associated with a string."""
 
153
    from merge import merge_types
 
154
    try:
 
155
        return merge_types[typestring][0]
 
156
    except KeyError:
 
157
        templ = '%s%%7s: %%s' % (' '*12)
 
158
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
159
        type_list = '\n'.join(lines)
 
160
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
161
            (typestring, type_list)
 
162
        raise BzrCommandError(msg)
 
163
    
 
164
 
139
165
 
140
166
def _get_cmd_dict(plugins_override=True):
141
167
    d = {}
237
263
class ExternalCommand(Command):
238
264
    """Class to wrap external commands.
239
265
 
240
 
    We cheat a little here, when get_cmd_class() calls us we actually give it back
241
 
    an object we construct that has the appropriate path, help, options etc for the
242
 
    specified command.
243
 
 
244
 
    When run_bzr() tries to instantiate that 'class' it gets caught by the __call__
245
 
    method, which we override to call the Command.__init__ method. That then calls
246
 
    our run method which is pretty straight forward.
247
 
 
248
 
    The only wrinkle is that we have to map bzr's dictionary of options and arguments
249
 
    back into command line options and arguments for the script.
 
266
    We cheat a little here, when get_cmd_class() calls us we actually
 
267
    give it back an object we construct that has the appropriate path,
 
268
    help, options etc for the specified command.
 
269
 
 
270
    When run_bzr() tries to instantiate that 'class' it gets caught by
 
271
    the __call__ method, which we override to call the Command.__init__
 
272
    method. That then calls our run method which is pretty straight
 
273
    forward.
 
274
 
 
275
    The only wrinkle is that we have to map bzr's dictionary of options
 
276
    and arguments back into command line options and arguments for the
 
277
    script.
250
278
    """
251
279
 
252
280
    def find_command(cls, cmd):
503
531
    def run(self, source_list, dest):
504
532
        b = find_branch('.')
505
533
 
 
534
        # TODO: glob expansion on windows?
506
535
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
507
536
 
508
537
 
528
557
 
529
558
 
530
559
 
 
560
class cmd_mv(Command):
 
561
    """Move or rename a file.
 
562
 
 
563
    usage:
 
564
        bzr mv OLDNAME NEWNAME
 
565
        bzr mv SOURCE... DESTINATION
 
566
 
 
567
    If the last argument is a versioned directory, all the other names
 
568
    are moved into it.  Otherwise, there must be exactly two arguments
 
569
    and the file is changed to a new name, which must not already exist.
 
570
 
 
571
    Files cannot be moved between branches.
 
572
    """
 
573
    takes_args = ['names*']
 
574
    def run(self, names_list):
 
575
        if len(names_list) < 2:
 
576
            raise BzrCommandError("missing file argument")
 
577
        b = find_branch(names_list[0])
 
578
 
 
579
        rel_names = [b.relpath(x) for x in names_list]
 
580
        
 
581
        if os.path.isdir(names_list[-1]):
 
582
            # move into existing directory
 
583
            b.move(rel_names[:-1], rel_names[-1])
 
584
        else:
 
585
            if len(names_list) != 2:
 
586
                raise BzrCommandError('to mv multiple files the destination '
 
587
                                      'must be a versioned directory')
 
588
            b.move(rel_names[0], rel_names[1])
 
589
            
 
590
    
531
591
 
532
592
 
533
593
class cmd_pull(Command):
600
660
    """
601
661
    takes_args = ['from_location', 'to_location?']
602
662
    takes_options = ['revision']
 
663
    aliases = ['get', 'clone']
603
664
 
604
665
    def run(self, from_location, to_location=None, revision=None):
605
666
        import errno
606
667
        from bzrlib.merge import merge
607
 
        from bzrlib.branch import DivergedBranches, NoSuchRevision, \
 
668
        from bzrlib.branch import DivergedBranches, \
608
669
             find_cached_branch, Branch
609
670
        from shutil import rmtree
610
671
        from meta_store import CachedStore
651
712
                    revno, rev_id = br_from.get_revision_info(revision[0])
652
713
                try:
653
714
                    br_to.update_revisions(br_from, stop_revision=revno)
654
 
                except NoSuchRevision:
 
715
                except bzrlib.errors.NoSuchRevision:
655
716
                    rmtree(to_location)
656
717
                    msg = "The branch %s has no revision %d." % (from_location,
657
718
                                                                 revno)
658
719
                    raise BzrCommandError(msg)
659
 
            
 
720
 
660
721
            merge((to_location, -1), (to_location, 0), this_dir=to_location,
661
722
                  check_clean=False, ignore_zero=True)
662
723
            from_location = pull_loc(br_from)
797
858
    If files are listed, only the changes in those files are listed.
798
859
    Otherwise, all changes for the tree are listed.
799
860
 
800
 
    TODO: Given two revision arguments, show the difference between them.
801
 
 
802
861
    TODO: Allow diff across branches.
803
862
 
804
863
    TODO: Option to use external diff command; could be GNU diff, wdiff,
813
872
          deleted files.
814
873
 
815
874
    TODO: This probably handles non-Unix newlines poorly.
 
875
 
 
876
    examples:
 
877
        bzr diff
 
878
        bzr diff -r1
 
879
        bzr diff -r1:2
816
880
    """
817
881
    
818
882
    takes_args = ['file*']
831
895
        else:
832
896
            b = find_branch('.')
833
897
 
834
 
        # TODO: Make show_diff support taking 2 arguments
835
 
        base_rev = None
836
898
        if revision is not None:
837
 
            if len(revision) != 1:
838
 
                raise BzrCommandError('bzr diff --revision takes exactly one revision identifier')
839
 
            base_rev = revision[0]
840
 
    
841
 
        show_diff(b, base_rev, specific_files=file_list,
842
 
                  external_diff_options=diff_options)
843
 
 
 
899
            if len(revision) == 1:
 
900
                show_diff(b, revision[0], specific_files=file_list,
 
901
                          external_diff_options=diff_options)
 
902
            elif len(revision) == 2:
 
903
                show_diff(b, revision[0], specific_files=file_list,
 
904
                          external_diff_options=diff_options,
 
905
                          revision2=revision[1])
 
906
            else:
 
907
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
 
908
        else:
 
909
            show_diff(b, None, specific_files=file_list,
 
910
                      external_diff_options=diff_options)
844
911
 
845
912
        
846
913
 
872
939
    """List files modified in working tree."""
873
940
    hidden = True
874
941
    def run(self):
875
 
        from bzrlib.diff import compare_trees
 
942
        from bzrlib.delta import compare_trees
876
943
 
877
944
        b = find_branch('.')
878
945
        td = compare_trees(b.basis_tree(), b.working_tree())
927
994
    """
928
995
 
929
996
    takes_args = ['filename?']
930
 
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision','long', 'message']
 
997
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision',
 
998
                     'long', 'message', 'short',]
931
999
    
932
1000
    def run(self, filename=None, timezone='original',
933
1001
            verbose=False,
935
1003
            forward=False,
936
1004
            revision=None,
937
1005
            message=None,
938
 
            long=False):
 
1006
            long=False,
 
1007
            short=False):
939
1008
        from bzrlib.branch import find_branch
940
1009
        from bzrlib.log import log_formatter, show_log
941
1010
        import codecs
975
1044
        # in e.g. the default C locale.
976
1045
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
977
1046
 
978
 
        if long:
 
1047
        if not short:
979
1048
            log_format = 'long'
980
1049
        else:
981
1050
            log_format = 'short'
1198
1267
 
1199
1268
class cmd_commit(Command):
1200
1269
    """Commit changes into a new revision.
 
1270
    
 
1271
    If no arguments are given, the entire tree is committed.
1201
1272
 
1202
1273
    If selected files are specified, only changes to those files are
1203
 
    committed.  If a directory is specified then its contents are also
1204
 
    committed.
 
1274
    committed.  If a directory is specified then the directory and everything 
 
1275
    within it is committed.
1205
1276
 
1206
1277
    A selected-file commit may fail in some cases where the committed
1207
1278
    tree would be invalid, such as trying to commit a file in a
1215
1286
    takes_options = ['message', 'file', 'verbose', 'unchanged']
1216
1287
    aliases = ['ci', 'checkin']
1217
1288
 
 
1289
    # TODO: Give better message for -s, --summary, used by tla people
 
1290
    
1218
1291
    def run(self, message=None, file=None, verbose=True, selected_list=None,
1219
1292
            unchanged=False):
1220
1293
        from bzrlib.errors import PointlessCommit
1222
1295
 
1223
1296
        ## Warning: shadows builtin file()
1224
1297
        if not message and not file:
 
1298
            # FIXME: Ugly; change status code to send to a provided function?
 
1299
            
1225
1300
            import cStringIO
1226
1301
            stdout = sys.stdout
1227
1302
            catcher = cStringIO.StringIO()
1242
1317
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1243
1318
 
1244
1319
        b = find_branch('.')
1245
 
 
 
1320
        if selected_list:
 
1321
            selected_list = [b.relpath(s) for s in selected_list]
 
1322
            
1246
1323
        try:
1247
1324
            b.commit(message, verbose=verbose,
1248
1325
                     specific_files=selected_list,
1267
1344
 
1268
1345
    def run(self, dir='.'):
1269
1346
        from bzrlib.check import check
 
1347
 
1270
1348
        check(find_branch(dir))
1271
1349
 
1272
1350
 
1273
 
 
1274
1351
class cmd_scan_cache(Command):
1275
1352
    hidden = True
1276
1353
    def run(self):
1311
1388
    takes_options = ['email']
1312
1389
    
1313
1390
    def run(self, email=False):
 
1391
        try:
 
1392
            b = bzrlib.branch.find_branch('.')
 
1393
        except:
 
1394
            b = None
 
1395
        
1314
1396
        if email:
1315
 
            print bzrlib.osutils.user_email()
 
1397
            print bzrlib.osutils.user_email(b)
1316
1398
        else:
1317
 
            print bzrlib.osutils.username()
 
1399
            print bzrlib.osutils.username(b)
1318
1400
 
1319
1401
 
1320
1402
class cmd_selftest(Command):
1322
1404
    hidden = True
1323
1405
    takes_options = ['verbose']
1324
1406
    def run(self, verbose=False):
 
1407
        import bzrlib.ui
1325
1408
        from bzrlib.selftest import selftest
1326
 
        return int(not selftest(verbose=verbose))
 
1409
 
 
1410
        # we don't want progress meters from the tests to go to the
 
1411
        # real output.
 
1412
 
 
1413
        save_ui = bzrlib.ui.ui_factory
 
1414
        try:
 
1415
            bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
 
1416
            return int(not selftest(verbose=verbose))
 
1417
        finally:
 
1418
            bzrlib.ui.ui_factory = save_ui
1327
1419
 
1328
1420
 
1329
1421
class cmd_version(Command):
1384
1476
 
1385
1477
 
1386
1478
 
 
1479
class cmd_find_merge_base(Command):
 
1480
    """Find and print a base revision for merging two branches.
 
1481
 
 
1482
    TODO: Options to specify revisions on either side, as if
 
1483
          merging only part of the history.
 
1484
    """
 
1485
    takes_args = ['branch', 'other']
 
1486
    hidden = True
 
1487
    
 
1488
    def run(self, branch, other):
 
1489
        branch1 = find_branch(branch)
 
1490
        branch2 = find_branch(other)
 
1491
 
 
1492
        base_revno, base_revid = branch1.common_ancestor(branch2)
 
1493
 
 
1494
        if base_revno is None:
 
1495
            raise bzrlib.errors.UnrelatedBranches()
 
1496
 
 
1497
        print 'merge base is revision %s' % base_revid
 
1498
        print ' r%-6d in %s' % (base_revno, branch)
 
1499
 
 
1500
        other_revno = branch2.revision_id_to_revno(base_revid)
 
1501
        
 
1502
        print ' r%-6d in %s' % (other_revno, other)
 
1503
 
 
1504
 
 
1505
 
1387
1506
class cmd_merge(Command):
1388
 
    """Perform a three-way merge of trees.
1389
 
    
1390
 
    The SPEC parameters are working tree or revision specifiers.  Working trees
1391
 
    are specified using standard paths or urls.  No component of a directory
1392
 
    path may begin with '@'.
1393
 
    
1394
 
    Working tree examples: '.', '..', 'foo@', but NOT 'foo/@bar'
1395
 
 
1396
 
    Revisions are specified using a dirname/@revno pair, where dirname is the
1397
 
    branch directory and revno is the revision within that branch.  If no revno
1398
 
    is specified, the latest revision is used.
1399
 
 
1400
 
    Revision examples: './@127', 'foo/@', '../@1'
1401
 
 
1402
 
    The OTHER_SPEC parameter is required.  If the BASE_SPEC parameter is
1403
 
    not supplied, the common ancestor of OTHER_SPEC the current branch is used
1404
 
    as the BASE.
1405
 
 
 
1507
    """Perform a three-way merge.
 
1508
    
 
1509
    The branch is the branch you will merge from.  By default, it will merge
 
1510
    the latest revision.  If you specify a revision, that revision will be
 
1511
    merged.  If you specify two revisions, the first will be used as a BASE, 
 
1512
    and the second one as OTHER.  Revision numbers are always relative to the
 
1513
    specified branch.
 
1514
    
 
1515
    Examples:
 
1516
 
 
1517
    To merge the latest revision from bzr.dev
 
1518
    bzr merge ../bzr.dev
 
1519
 
 
1520
    To merge changes up to and including revision 82 from bzr.dev
 
1521
    bzr merge -r 82 ../bzr.dev
 
1522
 
 
1523
    To merge the changes introduced by 82, without previous changes:
 
1524
    bzr merge -r 81..82 ../bzr.dev
 
1525
    
1406
1526
    merge refuses to run if there are any uncommitted changes, unless
1407
1527
    --force is given.
1408
1528
    """
1409
 
    takes_args = ['other_spec', 'base_spec?']
1410
 
    takes_options = ['force', 'merge-type']
 
1529
    takes_args = ['branch?']
 
1530
    takes_options = ['revision', 'force', 'merge-type']
1411
1531
 
1412
 
    def run(self, other_spec, base_spec=None, force=False, merge_type=None):
 
1532
    def run(self, branch='.', revision=None, force=False, 
 
1533
            merge_type=None):
1413
1534
        from bzrlib.merge import merge
1414
1535
        from bzrlib.merge_core import ApplyMerge3
1415
1536
        if merge_type is None:
1416
1537
            merge_type = ApplyMerge3
1417
 
        merge(parse_spec(other_spec), parse_spec(base_spec),
1418
 
              check_clean=(not force), merge_type=merge_type)
 
1538
 
 
1539
        if revision is None or len(revision) < 1:
 
1540
            base = (None, None)
 
1541
            other = (branch, -1)
 
1542
        else:
 
1543
            if len(revision) == 1:
 
1544
                other = (branch, revision[0])
 
1545
                base = (None, None)
 
1546
            else:
 
1547
                assert len(revision) == 2
 
1548
                if None in revision:
 
1549
                    raise BzrCommandError(
 
1550
                        "Merge doesn't permit that revision specifier.")
 
1551
                base = (branch, revision[0])
 
1552
                other = (branch, revision[1])
 
1553
            
 
1554
        merge(other, base, check_clean=(not force), merge_type=merge_type)
1419
1555
 
1420
1556
 
1421
1557
class cmd_revert(Command):
1456
1592
    """Show help on a command or other topic.
1457
1593
 
1458
1594
    For a list of all available commands, say 'bzr help commands'."""
 
1595
    takes_options = ['long']
1459
1596
    takes_args = ['topic?']
1460
1597
    aliases = ['?']
1461
1598
    
1462
 
    def run(self, topic=None):
 
1599
    def run(self, topic=None, long=False):
1463
1600
        import help
 
1601
        if topic is None and long:
 
1602
            topic = "commands"
1464
1603
        help.help(topic)
1465
1604
 
1466
1605
 
 
1606
class cmd_shell_complete(Command):
 
1607
    """Show appropriate completions for context.
 
1608
 
 
1609
    For a list of all available commands, say 'bzr shell-complete'."""
 
1610
    takes_args = ['context?']
 
1611
    aliases = ['s-c']
 
1612
    hidden = True
 
1613
    
 
1614
    def run(self, context=None):
 
1615
        import shellcomplete
 
1616
        shellcomplete.shellcomplete(context)
 
1617
 
 
1618
 
 
1619
class cmd_missing(Command):
 
1620
    """What is missing in this branch relative to other branch.
 
1621
    """
 
1622
    takes_args = ['remote?']
 
1623
    aliases = ['mis', 'miss']
 
1624
    # We don't have to add quiet to the list, because 
 
1625
    # unknown options are parsed as booleans
 
1626
    takes_options = ['verbose', 'quiet']
 
1627
 
 
1628
    def run(self, remote=None, verbose=False, quiet=False):
 
1629
        from bzrlib.branch import find_branch, DivergedBranches
 
1630
        from bzrlib.errors import BzrCommandError
 
1631
        from bzrlib.missing import get_parent, show_missing
 
1632
 
 
1633
        if verbose and quiet:
 
1634
            raise BzrCommandError('Cannot pass both quiet and verbose')
 
1635
 
 
1636
        b = find_branch('.')
 
1637
        parent = get_parent(b)
 
1638
        if remote is None:
 
1639
            if parent is None:
 
1640
                raise BzrCommandError("No missing location known or specified.")
 
1641
            else:
 
1642
                if not quiet:
 
1643
                    print "Using last location: %s" % parent
 
1644
                remote = parent
 
1645
        elif parent is None:
 
1646
            # We only update x-pull if it did not exist, missing should not change the parent
 
1647
            b.controlfile('x-pull', 'wb').write(remote + '\n')
 
1648
        br_remote = find_branch(remote)
 
1649
 
 
1650
        return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
 
1651
 
1467
1652
 
1468
1653
 
1469
1654
class cmd_plugins(Command):
1498
1683
    'no-recurse':             None,
1499
1684
    'profile':                None,
1500
1685
    'revision':               _parse_revision_str,
 
1686
    'short':                  None,
1501
1687
    'show-ids':               None,
1502
1688
    'timezone':               str,
1503
1689
    'verbose':                None,
1664
1850
    return argdict
1665
1851
 
1666
1852
 
1667
 
def _parse_master_args(argv):
1668
 
    """Parse the arguments that always go with the original command.
1669
 
    These are things like bzr --no-plugins, etc.
1670
 
 
1671
 
    There are now 2 types of option flags. Ones that come *before* the command,
1672
 
    and ones that come *after* the command.
1673
 
    Ones coming *before* the command are applied against all possible commands.
1674
 
    And are generally applied before plugins are loaded.
1675
 
 
1676
 
    The current list are:
1677
 
        --builtin   Allow plugins to load, but don't let them override builtin commands,
1678
 
                    they will still be allowed if they do not override a builtin.
1679
 
        --no-plugins    Don't load any plugins. This lets you get back to official source
1680
 
                        behavior.
1681
 
        --profile   Enable the hotspot profile before running the command.
1682
 
                    For backwards compatibility, this is also a non-master option.
1683
 
        --version   Spit out the version of bzr that is running and exit.
1684
 
                    This is also a non-master option.
1685
 
        --help      Run help and exit, also a non-master option (I think that should stay, though)
1686
 
 
1687
 
    >>> argv, opts = _parse_master_args(['--test'])
1688
 
    Traceback (most recent call last):
1689
 
    ...
1690
 
    BzrCommandError: Invalid master option: 'test'
1691
 
    >>> argv, opts = _parse_master_args(['--version', 'command'])
1692
 
    >>> print argv
1693
 
    ['command']
1694
 
    >>> print opts['version']
1695
 
    True
1696
 
    >>> argv, opts = _parse_master_args(['--profile', 'command', '--more-options'])
1697
 
    >>> print argv
1698
 
    ['command', '--more-options']
1699
 
    >>> print opts['profile']
1700
 
    True
1701
 
    >>> argv, opts = _parse_master_args(['--no-plugins', 'command'])
1702
 
    >>> print argv
1703
 
    ['command']
1704
 
    >>> print opts['no-plugins']
1705
 
    True
1706
 
    >>> print opts['profile']
1707
 
    False
1708
 
    >>> argv, opts = _parse_master_args(['command', '--profile'])
1709
 
    >>> print argv
1710
 
    ['command', '--profile']
1711
 
    >>> print opts['profile']
1712
 
    False
1713
 
    """
1714
 
    master_opts = {'builtin':False,
1715
 
        'no-plugins':False,
1716
 
        'version':False,
1717
 
        'profile':False,
1718
 
        'help':False
1719
 
    }
1720
 
 
1721
 
    for arg in argv[:]:
1722
 
        if arg[:2] != '--': # at the first non-option, we return the rest
1723
 
            break
1724
 
        arg = arg[2:] # Remove '--'
1725
 
        if arg not in master_opts:
1726
 
            # We could say that this is not an error, that we should
1727
 
            # just let it be handled by the main section instead
1728
 
            raise BzrCommandError('Invalid master option: %r' % arg)
1729
 
        argv.pop(0) # We are consuming this entry
1730
 
        master_opts[arg] = True
1731
 
    return argv, master_opts
1732
 
 
1733
 
 
1734
1853
 
1735
1854
def run_bzr(argv):
1736
1855
    """Execute a command.
1739
1858
    logging and error handling.  
1740
1859
    
1741
1860
    argv
1742
 
       The command-line arguments, without the program name.
 
1861
       The command-line arguments, without the program name from argv[0]
1743
1862
    
1744
1863
    Returns a command status or raises an exception.
 
1864
 
 
1865
    Special master options: these must come before the command because
 
1866
    they control how the command is interpreted.
 
1867
 
 
1868
    --no-plugins
 
1869
        Do not load plugin modules at all
 
1870
 
 
1871
    --builtin
 
1872
        Only use builtin commands.  (Plugins are still allowed to change
 
1873
        other behaviour.)
 
1874
 
 
1875
    --profile
 
1876
        Run under the Python profiler.
1745
1877
    """
 
1878
    
1746
1879
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
1747
1880
 
1748
 
    # some options like --builtin and --no-plugins have special effects
1749
 
    argv, master_opts = _parse_master_args(argv)
1750
 
    if not master_opts['no-plugins']:
 
1881
    opt_profile = opt_no_plugins = opt_builtin = False
 
1882
 
 
1883
    # --no-plugins is handled specially at a very early stage. We need
 
1884
    # to load plugins before doing other command parsing so that they
 
1885
    # can override commands, but this needs to happen first.
 
1886
 
 
1887
    for a in argv[:]:
 
1888
        if a == '--profile':
 
1889
            opt_profile = True
 
1890
        elif a == '--no-plugins':
 
1891
            opt_no_plugins = True
 
1892
        elif a == '--builtin':
 
1893
            opt_builtin = True
 
1894
        else:
 
1895
            break
 
1896
        argv.remove(a)
 
1897
 
 
1898
    if not opt_no_plugins:
1751
1899
        from bzrlib.plugin import load_plugins
1752
1900
        load_plugins()
1753
1901
 
1754
1902
    args, opts = parse_args(argv)
1755
1903
 
1756
 
    if master_opts.get('help') or 'help' in opts:
 
1904
    if 'help' in opts:
1757
1905
        from bzrlib.help import help
1758
 
        if argv:
1759
 
            help(argv[0])
 
1906
        if args:
 
1907
            help(args[0])
1760
1908
        else:
1761
1909
            help()
1762
1910
        return 0            
1765
1913
        show_version()
1766
1914
        return 0
1767
1915
    
1768
 
    if args and args[0] == 'builtin':
1769
 
        include_plugins=False
1770
 
        args = args[1:]
 
1916
    if not args:
 
1917
        from bzrlib.help import help
 
1918
        help(None)
 
1919
        return 0
1771
1920
    
1772
 
    try:
1773
 
        cmd = str(args.pop(0))
1774
 
    except IndexError:
1775
 
        print >>sys.stderr, "please try 'bzr help' for help"
1776
 
        return 1
1777
 
 
1778
 
    plugins_override = not (master_opts['builtin'])
1779
 
    canonical_cmd, cmd_class = get_cmd_class(cmd, plugins_override=plugins_override)
1780
 
 
1781
 
    profile = master_opts['profile']
1782
 
    # For backwards compatibility, I would rather stick with --profile being a
1783
 
    # master/global option
1784
 
    if 'profile' in opts:
1785
 
        profile = True
1786
 
        del opts['profile']
 
1921
    cmd = str(args.pop(0))
 
1922
 
 
1923
    canonical_cmd, cmd_class = \
 
1924
                   get_cmd_class(cmd, plugins_override=not opt_builtin)
1787
1925
 
1788
1926
    # check options are reasonable
1789
1927
    allowed = cmd_class.takes_options
1798
1936
    for k, v in opts.items():
1799
1937
        cmdopts[k.replace('-', '_')] = v
1800
1938
 
1801
 
    if profile:
 
1939
    if opt_profile:
1802
1940
        import hotshot, tempfile
1803
1941
        pffileno, pfname = tempfile.mkstemp()
1804
1942
        try:
1823
1961
        return cmd_class(cmdopts, cmdargs).status 
1824
1962
 
1825
1963
 
1826
 
def _report_exception(summary, quiet=False):
1827
 
    import traceback
1828
 
    log_error('bzr: ' + summary)
1829
 
    bzrlib.trace.log_exception()
1830
 
 
1831
 
    if not quiet:
1832
 
        tb = sys.exc_info()[2]
1833
 
        exinfo = traceback.extract_tb(tb)
1834
 
        if exinfo:
1835
 
            sys.stderr.write('  at %s:%d in %s()\n' % exinfo[-1][:3])
1836
 
        sys.stderr.write('  see ~/.bzr.log for debug information\n')
1837
 
 
1838
 
 
1839
 
 
1840
1964
def main(argv):
 
1965
    import bzrlib.ui
1841
1966
    
1842
 
    bzrlib.trace.open_tracefile(argv)
 
1967
    bzrlib.trace.log_startup(argv)
 
1968
 
 
1969
    bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory()
1843
1970
 
1844
1971
    try:
1845
1972
        try:
1846
 
            try:
1847
 
                return run_bzr(argv[1:])
1848
 
            finally:
1849
 
                # do this here inside the exception wrappers to catch EPIPE
1850
 
                sys.stdout.flush()
1851
 
        except BzrError, e:
1852
 
            quiet = isinstance(e, (BzrCommandError))
1853
 
            _report_exception('error: ' + e.args[0], quiet=quiet)
1854
 
            if len(e.args) > 1:
1855
 
                for h in e.args[1]:
1856
 
                    # some explanation or hints
1857
 
                    log_error('  ' + h)
1858
 
            return 1
1859
 
        except AssertionError, e:
1860
 
            msg = 'assertion failed'
1861
 
            if str(e):
1862
 
                msg += ': ' + str(e)
1863
 
            _report_exception(msg)
1864
 
            return 2
1865
 
        except KeyboardInterrupt, e:
1866
 
            _report_exception('interrupted', quiet=True)
1867
 
            return 2
1868
 
        except Exception, e:
1869
 
            import errno
1870
 
            quiet = False
1871
 
            if (isinstance(e, IOError) 
1872
 
                and hasattr(e, 'errno')
1873
 
                and e.errno == errno.EPIPE):
1874
 
                quiet = True
1875
 
                msg = 'broken pipe'
1876
 
            else:
1877
 
                msg = str(e).rstrip('\n')
1878
 
            _report_exception(msg, quiet)
1879
 
            return 2
1880
 
    finally:
1881
 
        bzrlib.trace.close_trace()
 
1973
            return run_bzr(argv[1:])
 
1974
        finally:
 
1975
            # do this here inside the exception wrappers to catch EPIPE
 
1976
            sys.stdout.flush()
 
1977
    except BzrCommandError, e:
 
1978
        # command line syntax error, etc
 
1979
        log_error(str(e))
 
1980
        return 1
 
1981
    except BzrError, e:
 
1982
        bzrlib.trace.log_exception()
 
1983
        return 1
 
1984
    except AssertionError, e:
 
1985
        bzrlib.trace.log_exception('assertion failed: ' + str(e))
 
1986
        return 3
 
1987
    except KeyboardInterrupt, e:
 
1988
        bzrlib.trace.note('interrupted')
 
1989
        return 2
 
1990
    except Exception, e:
 
1991
        import errno
 
1992
        if (isinstance(e, IOError) 
 
1993
            and hasattr(e, 'errno')
 
1994
            and e.errno == errno.EPIPE):
 
1995
            bzrlib.trace.note('broken pipe')
 
1996
            return 2
 
1997
        else:
 
1998
            bzrlib.trace.log_exception()
 
1999
            return 2
1882
2000
 
1883
2001
 
1884
2002
if __name__ == '__main__':