/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
329 by Martin Pool
- refactor command functions into command classes
1
# Copyright (C) 2004, 2005 by Canonical Ltd
1 by mbp at sourcefrog
import from baz patch-364
2
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
18
572 by Martin Pool
- trim imports
19
import sys, os
1 by mbp at sourcefrog
import from baz patch-364
20
21
import bzrlib
22
from bzrlib.trace import mutter, note, log_error
329 by Martin Pool
- refactor command functions into command classes
23
from bzrlib.errors import bailout, BzrError, BzrCheckError, BzrCommandError
592 by Martin Pool
- trim imports more
24
from bzrlib.osutils import quotefn
25
from bzrlib import Branch, Inventory, InventoryEntry, BZRDIR, \
1 by mbp at sourcefrog
import from baz patch-364
26
     format_date
27
28
350 by Martin Pool
- refactor command aliases into command classes
29
def _squish_command_name(cmd):
30
    return 'cmd_' + cmd.replace('-', '_')
31
32
33
def _unsquish_command_name(cmd):
34
    assert cmd.startswith("cmd_")
35
    return cmd[4:].replace('_','-')
36
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
37
def _parse_revision_str(revstr):
38
    """This handles a revision string -> revno. 
39
40
    There are several possibilities:
41
42
        '234'       -> 234
43
        '234:345'   -> [234, 345]
44
        ':234'      -> [None, 234]
45
        '234:'      -> [234, None]
46
47
    In the future we will also support:
48
        'uuid:blah-blah-blah'   -> ?
49
        'hash:blahblahblah'     -> ?
50
        potentially:
51
        'tag:mytag'             -> ?
52
    """
53
    if revstr.find(':') != -1:
54
        revs = revstr.split(':')
55
        if len(revs) > 2:
56
            raise ValueError('More than 2 pieces not supported for --revision: %r' % revstr)
57
58
        if not revs[0]:
59
            revs[0] = None
60
        else:
61
            revs[0] = int(revs[0])
62
63
        if not revs[1]:
64
            revs[1] = None
65
        else:
66
            revs[1] = int(revs[1])
67
    else:
68
        revs = int(revstr)
69
    return revs
70
641 by Martin Pool
- improved external-command patch from john
71
def _find_plugins():
72
    """Find all python files which are plugins, and load their commands
73
    to add to the list of "all commands"
74
75
    The environment variable BZRPATH is considered a delimited set of
76
    paths to look through. Each entry is searched for *.py files.
77
    If a directory is found, it is also searched, but they are 
78
    not searched recursively. This allows you to revctl the plugins.
79
    
80
    Inside the plugin should be a series of cmd_* function, which inherit from
81
    the bzrlib.commands.Command class.
82
    """
83
    bzrpath = os.environ.get('BZRPLUGINPATH', '')
84
85
    plugin_cmds = {} 
86
    if not bzrpath:
87
        return plugin_cmds
88
    _platform_extensions = {
89
        'win32':'.pyd',
90
        'cygwin':'.dll',
91
        'darwin':'.dylib',
92
        'linux2':'.so'
93
        }
94
    if _platform_extensions.has_key(sys.platform):
95
        platform_extension = _platform_extensions[sys.platform]
96
    else:
97
        platform_extension = None
98
    for d in bzrpath.split(os.pathsep):
99
        plugin_names = {} # This should really be a set rather than a dict
100
        for f in os.listdir(d):
101
            if f.endswith('.py'):
102
                f = f[:-3]
103
            elif f.endswith('.pyc') or f.endswith('.pyo'):
104
                f = f[:-4]
105
            elif platform_extension and f.endswith(platform_extension):
106
                f = f[:-len(platform_extension)]
107
                if f.endswidth('module'):
108
                    f = f[:-len('module')]
109
            else:
110
                continue
111
            if not plugin_names.has_key(f):
112
                plugin_names[f] = True
113
114
        plugin_names = plugin_names.keys()
115
        plugin_names.sort()
116
        try:
117
            sys.path.insert(0, d)
118
            for name in plugin_names:
119
                try:
120
                    old_module = None
121
                    try:
122
                        if sys.modules.has_key(name):
123
                            old_module = sys.modules[name]
124
                            del sys.modules[name]
125
                        plugin = __import__(name, locals())
126
                        for k in dir(plugin):
127
                            if k.startswith('cmd_'):
128
                                k_unsquished = _unsquish_command_name(k)
129
                                if not plugin_cmds.has_key(k_unsquished):
130
                                    plugin_cmds[k_unsquished] = getattr(plugin, k)
131
                                else:
132
                                    log_error('Two plugins defined the same command: %r' % k)
133
                                    log_error('Not loading the one in %r in dir %r' % (name, d))
134
                    finally:
135
                        if old_module:
136
                            sys.modules[name] = old_module
137
                except ImportError, e:
138
                    log_error('Unable to load plugin: %r from %r\n%s' % (name, d, e))
139
        finally:
140
            sys.path.pop(0)
141
    return plugin_cmds
142
143
def _get_cmd_dict(include_plugins=True):
144
    d = {}
350 by Martin Pool
- refactor command aliases into command classes
145
    for k, v in globals().iteritems():
146
        if k.startswith("cmd_"):
641 by Martin Pool
- improved external-command patch from john
147
            d[_unsquish_command_name(k)] = v
148
    if include_plugins:
149
        d.update(_find_plugins())
150
    return d
151
    
152
def get_all_cmds(include_plugins=True):
153
    """Return canonical name and class for all registered commands."""
154
    for k, v in _get_cmd_dict(include_plugins=include_plugins).iteritems():
155
        yield k,v
156
157
158
def get_cmd_class(cmd,include_plugins=True):
350 by Martin Pool
- refactor command aliases into command classes
159
    """Return the canonical name and command class for a command.
160
    """
161
    cmd = str(cmd)                      # not unicode
162
163
    # first look up this command under the specified name
641 by Martin Pool
- improved external-command patch from john
164
    cmds = _get_cmd_dict(include_plugins=include_plugins)
272 by Martin Pool
- Add command aliases
165
    try:
641 by Martin Pool
- improved external-command patch from john
166
        return cmd, cmds[cmd]
272 by Martin Pool
- Add command aliases
167
    except KeyError:
350 by Martin Pool
- refactor command aliases into command classes
168
        pass
169
170
    # look for any command which claims this as an alias
641 by Martin Pool
- improved external-command patch from john
171
    for cmdname, cmdclass in cmds.iteritems():
350 by Martin Pool
- refactor command aliases into command classes
172
        if cmd in cmdclass.aliases:
173
            return cmdname, cmdclass
422 by Martin Pool
- External-command patch from mpe
174
175
    cmdclass = ExternalCommand.find_command(cmd)
176
    if cmdclass:
177
        return cmd, cmdclass
178
179
    raise BzrCommandError("unknown command %r" % cmd)
272 by Martin Pool
- Add command aliases
180
329 by Martin Pool
- refactor command functions into command classes
181
558 by Martin Pool
- All top-level classes inherit from object
182
class Command(object):
329 by Martin Pool
- refactor command functions into command classes
183
    """Base class for commands.
184
185
    The docstring for an actual command should give a single-line
186
    summary, then a complete description of the command.  A grammar
187
    description will be inserted.
188
189
    takes_args
190
        List of argument forms, marked with whether they are optional,
191
        repeated, etc.
192
193
    takes_options
194
        List of options that may be given for this command.
195
196
    hidden
197
        If true, this command isn't advertised.
198
    """
199
    aliases = []
200
    
201
    takes_args = []
202
    takes_options = []
203
204
    hidden = False
205
    
206
    def __init__(self, options, arguments):
207
        """Construct and run the command.
208
209
        Sets self.status to the return value of run()."""
210
        assert isinstance(options, dict)
211
        assert isinstance(arguments, dict)
212
        cmdargs = options.copy()
213
        cmdargs.update(arguments)
214
        assert self.__doc__ != Command.__doc__, \
215
               ("No help message set for %r" % self)
216
        self.status = self.run(**cmdargs)
217
218
    
219
    def run(self):
220
        """Override this in sub-classes.
221
222
        This is invoked with the options and arguments bound to
223
        keyword parameters.
224
337 by Martin Pool
- Clarify return codes from command objects
225
        Return 0 or None if the command was successful, or a shell
226
        error code if not.
329 by Martin Pool
- refactor command functions into command classes
227
        """
337 by Martin Pool
- Clarify return codes from command objects
228
        return 0
329 by Martin Pool
- refactor command functions into command classes
229
230
422 by Martin Pool
- External-command patch from mpe
231
class ExternalCommand(Command):
232
    """Class to wrap external commands.
233
234
    We cheat a little here, when get_cmd_class() calls us we actually give it back
235
    an object we construct that has the appropriate path, help, options etc for the
236
    specified command.
237
238
    When run_bzr() tries to instantiate that 'class' it gets caught by the __call__
239
    method, which we override to call the Command.__init__ method. That then calls
240
    our run method which is pretty straight forward.
241
242
    The only wrinkle is that we have to map bzr's dictionary of options and arguments
243
    back into command line options and arguments for the script.
244
    """
245
246
    def find_command(cls, cmd):
572 by Martin Pool
- trim imports
247
        import os.path
422 by Martin Pool
- External-command patch from mpe
248
        bzrpath = os.environ.get('BZRPATH', '')
249
641 by Martin Pool
- improved external-command patch from john
250
        for dir in bzrpath.split(os.pathsep):
422 by Martin Pool
- External-command patch from mpe
251
            path = os.path.join(dir, cmd)
252
            if os.path.isfile(path):
253
                return ExternalCommand(path)
254
255
        return None
256
257
    find_command = classmethod(find_command)
258
259
    def __init__(self, path):
260
        self.path = path
261
424 by Martin Pool
todo
262
        # TODO: If either of these fail, we should detect that and
263
        # assume that path is not really a bzr plugin after all.
264
422 by Martin Pool
- External-command patch from mpe
265
        pipe = os.popen('%s --bzr-usage' % path, 'r')
266
        self.takes_options = pipe.readline().split()
267
        self.takes_args = pipe.readline().split()
268
        pipe.close()
269
270
        pipe = os.popen('%s --bzr-help' % path, 'r')
271
        self.__doc__ = pipe.read()
272
        pipe.close()
273
274
    def __call__(self, options, arguments):
275
        Command.__init__(self, options, arguments)
276
        return self
277
278
    def run(self, **kargs):
279
        opts = []
280
        args = []
281
282
        keys = kargs.keys()
283
        keys.sort()
284
        for name in keys:
285
            value = kargs[name]
286
            if OPTIONS.has_key(name):
287
                # it's an option
288
                opts.append('--%s' % name)
289
                if value is not None and value is not True:
290
                    opts.append(str(value))
291
            else:
292
                # it's an arg, or arg list
293
                if type(value) is not list:
294
                    value = [value]
295
                for v in value:
296
                    if v is not None:
297
                        args.append(str(v))
298
299
        self.status = os.spawnv(os.P_WAIT, self.path, [self.path] + opts + args)
300
        return self.status
301
329 by Martin Pool
- refactor command functions into command classes
302
303
class cmd_status(Command):
1 by mbp at sourcefrog
import from baz patch-364
304
    """Display status summary.
305
466 by Martin Pool
- doc for status command
306
    This reports on versioned and unknown files, reporting them
307
    grouped by state.  Possible states are:
308
309
    added
310
        Versioned in the working copy but not in the previous revision.
311
312
    removed
467 by Martin Pool
- doc for status command
313
        Versioned in the previous revision but removed or deleted
466 by Martin Pool
- doc for status command
314
        in the working copy.
315
316
    renamed
317
        Path of this file changed from the previous revision;
318
        the text may also have changed.  This includes files whose
467 by Martin Pool
- doc for status command
319
        parent directory was renamed.
466 by Martin Pool
- doc for status command
320
321
    modified
322
        Text has changed since the previous revision.
323
324
    unchanged
467 by Martin Pool
- doc for status command
325
        Nothing about this file has changed since the previous revision.
326
        Only shown with --all.
466 by Martin Pool
- doc for status command
327
328
    unknown
329
        Not versioned and not matching an ignore pattern.
330
331
    To see ignored files use 'bzr ignored'.  For details in the
332
    changes to file texts, use 'bzr diff'.
468 by Martin Pool
- Interpret arguments to bzr status
333
334
    If no arguments are specified, the status of the entire working
335
    directory is shown.  Otherwise, only the status of the specified
336
    files or directories is reported.  If a directory is given, status
337
    is reported for everything inside that directory.
1 by mbp at sourcefrog
import from baz patch-364
338
    """
404 by Martin Pool
- bzr status now optionally takes filenames to check
339
    takes_args = ['file*']
465 by Martin Pool
- Move show_status() out of Branch into a new function in
340
    takes_options = ['all', 'show-ids']
350 by Martin Pool
- refactor command aliases into command classes
341
    aliases = ['st', 'stat']
329 by Martin Pool
- refactor command functions into command classes
342
    
465 by Martin Pool
- Move show_status() out of Branch into a new function in
343
    def run(self, all=False, show_ids=False, file_list=None):
468 by Martin Pool
- Interpret arguments to bzr status
344
        if file_list:
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
345
            b = Branch(file_list[0])
468 by Martin Pool
- Interpret arguments to bzr status
346
            file_list = [b.relpath(x) for x in file_list]
347
            # special case: only one path was given and it's the root
348
            # of the branch
349
            if file_list == ['']:
350
                file_list = None
351
        else:
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
352
            b = Branch('.')
465 by Martin Pool
- Move show_status() out of Branch into a new function in
353
        import status
354
        status.show_status(b, show_unchanged=all, show_ids=show_ids,
483 by Martin Pool
- change 'file_list' to more explanatory 'specific_files'
355
                           specific_files=file_list)
329 by Martin Pool
- refactor command functions into command classes
356
357
358
class cmd_cat_revision(Command):
359
    """Write out metadata for a revision."""
360
361
    hidden = True
362
    takes_args = ['revision_id']
363
    
364
    def run(self, revision_id):
365
        Branch('.').get_revision(revision_id).write_xml(sys.stdout)
366
367
368
class cmd_revno(Command):
369
    """Show current revision number.
370
371
    This is equal to the number of revisions on this branch."""
372
    def run(self):
373
        print Branch('.').revno()
374
375
    
376
class cmd_add(Command):
70 by mbp at sourcefrog
Prepare for smart recursive add.
377
    """Add specified files or directories.
378
379
    In non-recursive mode, all the named items are added, regardless
380
    of whether they were previously ignored.  A warning is given if
381
    any of the named files are already versioned.
382
383
    In recursive mode (the default), files are treated the same way
384
    but the behaviour for directories is different.  Directories that
385
    are already versioned do not give a warning.  All directories,
386
    whether already versioned or not, are searched for files or
387
    subdirectories that are neither versioned or ignored, and these
388
    are added.  This search proceeds recursively into versioned
389
    directories.
390
391
    Therefore simply saying 'bzr add .' will version all files that
392
    are currently unknown.
279 by Martin Pool
todo
393
394
    TODO: Perhaps adding a file whose directly is not versioned should
395
    recursively add that parent, rather than giving an error?
70 by mbp at sourcefrog
Prepare for smart recursive add.
396
    """
329 by Martin Pool
- refactor command functions into command classes
397
    takes_args = ['file+']
594 by Martin Pool
- add --no-recurse option for add command
398
    takes_options = ['verbose', 'no-recurse']
329 by Martin Pool
- refactor command functions into command classes
399
    
594 by Martin Pool
- add --no-recurse option for add command
400
    def run(self, file_list, verbose=False, no_recurse=False):
401
        bzrlib.add.smart_add(file_list, verbose, not no_recurse)
329 by Martin Pool
- refactor command functions into command classes
402
403
386 by Martin Pool
- Typo (reported by uws)
404
class cmd_relpath(Command):
329 by Martin Pool
- refactor command functions into command classes
405
    """Show path of a file relative to root"""
392 by Martin Pool
- fix relpath and add tests
406
    takes_args = ['filename']
584 by Martin Pool
- make relpath and revision-history hidden commands
407
    hidden = True
329 by Martin Pool
- refactor command functions into command classes
408
    
392 by Martin Pool
- fix relpath and add tests
409
    def run(self, filename):
410
        print Branch(filename).relpath(filename)
329 by Martin Pool
- refactor command functions into command classes
411
412
413
414
class cmd_inventory(Command):
415
    """Show inventory of the current working copy or a revision."""
588 by Martin Pool
- change inventory command to not show ids by default
416
    takes_options = ['revision', 'show-ids']
329 by Martin Pool
- refactor command functions into command classes
417
    
588 by Martin Pool
- change inventory command to not show ids by default
418
    def run(self, revision=None, show_ids=False):
329 by Martin Pool
- refactor command functions into command classes
419
        b = Branch('.')
420
        if revision == None:
421
            inv = b.read_working_inventory()
422
        else:
423
            inv = b.get_revision_inventory(b.lookup_revision(revision))
424
556 by Martin Pool
- fix up Inventory.entries()
425
        for path, entry in inv.entries():
588 by Martin Pool
- change inventory command to not show ids by default
426
            if show_ids:
427
                print '%-50s %s' % (path, entry.file_id)
428
            else:
429
                print path
329 by Martin Pool
- refactor command functions into command classes
430
431
432
class cmd_move(Command):
433
    """Move files to a different directory.
434
435
    examples:
436
        bzr move *.txt doc
437
438
    The destination must be a versioned directory in the same branch.
439
    """
440
    takes_args = ['source$', 'dest']
441
    def run(self, source_list, dest):
442
        b = Branch('.')
443
444
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
445
446
447
class cmd_rename(Command):
168 by mbp at sourcefrog
new "rename" command
448
    """Change the name of an entry.
449
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
450
    examples:
451
      bzr rename frob.c frobber.c
452
      bzr rename src/frob.c lib/frob.c
453
454
    It is an error if the destination name exists.
455
456
    See also the 'move' command, which moves files into a different
457
    directory without changing their name.
458
459
    TODO: Some way to rename multiple files without invoking bzr for each
460
    one?"""
329 by Martin Pool
- refactor command functions into command classes
461
    takes_args = ['from_name', 'to_name']
168 by mbp at sourcefrog
new "rename" command
462
    
329 by Martin Pool
- refactor command functions into command classes
463
    def run(self, from_name, to_name):
464
        b = Branch('.')
465
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
466
467
468
628 by Martin Pool
- merge aaron's updated merge/pull code
469
470
471
class cmd_pull(Command):
472
    """Pull any changes from another branch into the current one.
473
474
    If the location is omitted, the last-used location will be used.
475
    Both the revision history and the working directory will be
476
    updated.
477
478
    This command only works on branches that have not diverged.  Branches are
479
    considered diverged if both branches have had commits without first
480
    pulling from the other.
481
482
    If branches have diverged, you can use 'bzr merge' to pull the text changes
483
    from one into the other.
484
    """
485
    takes_args = ['location?']
486
487
    def run(self, location=None):
488
        from bzrlib.merge import merge
489
        import errno
490
        
491
        br_to = Branch('.')
492
        stored_loc = None
493
        try:
494
            stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
495
        except IOError, e:
496
            if errno == errno.ENOENT:
497
                raise
498
        if location is None:
499
            location = stored_loc
500
        if location is None:
501
            raise BzrCommandError("No pull location known or specified.")
502
        from branch import find_branch, DivergedBranches
503
        br_from = find_branch(location)
504
        location = pull_loc(br_from)
505
        old_revno = br_to.revno()
506
        try:
507
            br_to.update_revisions(br_from)
508
        except DivergedBranches:
509
            raise BzrCommandError("These branches have diverged.  Try merge.")
510
            
640 by Martin Pool
- bzr pull should not check that the tree is clean
511
        merge(('.', -1), ('.', old_revno), check_clean=False)
628 by Martin Pool
- merge aaron's updated merge/pull code
512
        if location != stored_loc:
513
            br_to.controlfile("x-pull", "wb").write(location + "\n")
514
515
516
517
class cmd_branch(Command):
518
    """Create a new copy of a branch.
519
520
    If the TO_LOCATION is omitted, the last component of the
521
    FROM_LOCATION will be used.  In other words,
522
    "branch ../foo/bar" will attempt to create ./bar.
523
    """
524
    takes_args = ['from_location', 'to_location?']
525
526
    def run(self, from_location, to_location=None):
527
        import errno
528
        from bzrlib.merge import merge
671 by Martin Pool
- Don't create an empty destination directory when
529
        from branch import find_branch, DivergedBranches
530
        try:
531
            br_from = find_branch(from_location)
532
        except OSError, e:
533
            if e.errno == errno.ENOENT:
534
                raise BzrCommandError('Source location "%s" does not exist.' %
535
                                      to_location)
536
            else:
537
                raise
538
628 by Martin Pool
- merge aaron's updated merge/pull code
539
        if to_location is None:
684 by Martin Pool
- Strip any number of trailing slashes and backslashes from the path name
540
            to_location = os.path.basename(from_location.rstrip("/\\"))
628 by Martin Pool
- merge aaron's updated merge/pull code
541
542
        try:
543
            os.mkdir(to_location)
544
        except OSError, e:
545
            if e.errno == errno.EEXIST:
546
                raise BzrCommandError('Target directory "%s" already exists.' %
547
                                      to_location)
548
            if e.errno == errno.ENOENT:
549
                raise BzrCommandError('Parent of "%s" does not exist.' %
550
                                      to_location)
551
            else:
552
                raise
553
        br_to = Branch(to_location, init=True)
554
555
        from_location = pull_loc(br_from)
556
        br_to.update_revisions(br_from)
557
        merge((to_location, -1), (to_location, 0), this_dir=to_location,
558
              check_clean=False)
559
        br_to.controlfile("x-pull", "wb").write(from_location + "\n")
560
561
562
def pull_loc(branch):
563
    # TODO: Should perhaps just make attribute be 'base' in
564
    # RemoteBranch and Branch?
565
    if hasattr(branch, "baseurl"):
566
        return branch.baseurl
567
    else:
568
        return branch.base
569
570
571
329 by Martin Pool
- refactor command functions into command classes
572
class cmd_renames(Command):
164 by mbp at sourcefrog
new 'renames' command
573
    """Show list of renamed files.
574
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
575
    TODO: Option to show renames between two historical versions.
576
577
    TODO: Only show renames under dir, rather than in the whole branch.
578
    """
329 by Martin Pool
- refactor command functions into command classes
579
    takes_args = ['dir?']
580
581
    def run(self, dir='.'):
582
        b = Branch(dir)
583
        old_inv = b.basis_tree().inventory
584
        new_inv = b.read_working_inventory()
585
586
        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
587
        renames.sort()
588
        for old_name, new_name in renames:
589
            print "%s => %s" % (old_name, new_name)        
590
591
592
class cmd_info(Command):
472 by Martin Pool
- Optional branch parameter to info command
593
    """Show statistical information about a branch."""
594
    takes_args = ['branch?']
595
    
596
    def run(self, branch=None):
329 by Martin Pool
- refactor command functions into command classes
597
        import info
472 by Martin Pool
- Optional branch parameter to info command
598
599
        from branch import find_branch
600
        b = find_branch(branch)
601
        info.show_info(b)
329 by Martin Pool
- refactor command functions into command classes
602
603
604
class cmd_remove(Command):
605
    """Make a file unversioned.
606
607
    This makes bzr stop tracking changes to a versioned file.  It does
608
    not delete the working copy.
609
    """
610
    takes_args = ['file+']
611
    takes_options = ['verbose']
612
    
613
    def run(self, file_list, verbose=False):
614
        b = Branch(file_list[0])
615
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
616
617
618
class cmd_file_id(Command):
178 by mbp at sourcefrog
- Use a non-null file_id for the branch root directory. At the moment
619
    """Print file_id of a particular file or directory.
620
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
621
    The file_id is assigned when the file is first added and remains the
622
    same through all revisions where the file exists, even when it is
623
    moved or renamed.
624
    """
329 by Martin Pool
- refactor command functions into command classes
625
    hidden = True
626
    takes_args = ['filename']
627
    def run(self, filename):
628
        b = Branch(filename)
629
        i = b.inventory.path2id(b.relpath(filename))
630
        if i == None:
631
            bailout("%r is not a versioned file" % filename)
632
        else:
633
            print i
634
635
636
class cmd_file_path(Command):
178 by mbp at sourcefrog
- Use a non-null file_id for the branch root directory. At the moment
637
    """Print path of file_ids to a file or directory.
638
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
639
    This prints one line for each directory down to the target,
640
    starting at the branch root."""
329 by Martin Pool
- refactor command functions into command classes
641
    hidden = True
642
    takes_args = ['filename']
643
    def run(self, filename):
644
        b = Branch(filename)
645
        inv = b.inventory
646
        fid = inv.path2id(b.relpath(filename))
647
        if fid == None:
648
            bailout("%r is not a versioned file" % filename)
649
        for fip in inv.get_idpath(fid):
650
            print fip
651
652
653
class cmd_revision_history(Command):
654
    """Display list of revision ids on this branch."""
584 by Martin Pool
- make relpath and revision-history hidden commands
655
    hidden = True
329 by Martin Pool
- refactor command functions into command classes
656
    def run(self):
657
        for patchid in Branch('.').revision_history():
658
            print patchid
659
660
661
class cmd_directories(Command):
662
    """Display list of versioned directories in this branch."""
663
    def run(self):
664
        for name, ie in Branch('.').read_working_inventory().directories():
665
            if name == '':
666
                print '.'
667
            else:
668
                print name
669
670
671
class cmd_init(Command):
672
    """Make a directory into a versioned branch.
673
674
    Use this to create an empty branch, or before importing an
675
    existing project.
676
677
    Recipe for importing a tree of files:
678
        cd ~/project
679
        bzr init
680
        bzr add -v .
681
        bzr status
682
        bzr commit -m 'imported project'
683
    """
684
    def run(self):
685
        Branch('.', init=True)
686
687
688
class cmd_diff(Command):
689
    """Show differences in working tree.
690
    
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
691
    If files are listed, only the changes in those files are listed.
692
    Otherwise, all changes for the tree are listed.
693
694
    TODO: Given two revision arguments, show the difference between them.
695
696
    TODO: Allow diff across branches.
697
698
    TODO: Option to use external diff command; could be GNU diff, wdiff,
699
          or a graphical diff.
700
276 by Martin Pool
Doc
701
    TODO: Python difflib is not exactly the same as unidiff; should
702
          either fix it up or prefer to use an external diff.
703
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
704
    TODO: If a directory is given, diff everything under that.
705
276 by Martin Pool
Doc
706
    TODO: Selected-file diff is inefficient and doesn't show you
707
          deleted files.
278 by Martin Pool
- Better workaround for trailing newlines in diffs
708
709
    TODO: This probably handles non-Unix newlines poorly.
329 by Martin Pool
- refactor command functions into command classes
710
    """
711
    
712
    takes_args = ['file*']
571 by Martin Pool
- new --diff-options to pass options through to external
713
    takes_options = ['revision', 'diff-options']
638 by Martin Pool
- add 'dif' as alias for 'diff' command
714
    aliases = ['di', 'dif']
329 by Martin Pool
- refactor command functions into command classes
715
571 by Martin Pool
- new --diff-options to pass options through to external
716
    def run(self, revision=None, file_list=None, diff_options=None):
329 by Martin Pool
- refactor command functions into command classes
717
        from bzrlib.diff import show_diff
547 by Martin Pool
- bzr diff finds a branch from the first parameter,
718
        from bzrlib import find_branch
719
720
        if file_list:
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
721
            b = find_branch(file_list[0])
547 by Martin Pool
- bzr diff finds a branch from the first parameter,
722
            file_list = [b.relpath(f) for f in file_list]
723
            if file_list == ['']:
724
                # just pointing to top-of-tree
725
                file_list = None
726
        else:
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
727
            b = Branch('.')
329 by Martin Pool
- refactor command functions into command classes
728
    
571 by Martin Pool
- new --diff-options to pass options through to external
729
        show_diff(b, revision, specific_files=file_list,
730
                  external_diff_options=diff_options)
329 by Martin Pool
- refactor command functions into command classes
731
732
437 by Martin Pool
- new command 'bzr modified' to exercise the statcache
733
        
734
735
329 by Martin Pool
- refactor command functions into command classes
736
class cmd_deleted(Command):
135 by mbp at sourcefrog
Simple new 'deleted' command
737
    """List files deleted in the working tree.
738
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
739
    TODO: Show files deleted since a previous revision, or between two revisions.
135 by mbp at sourcefrog
Simple new 'deleted' command
740
    """
329 by Martin Pool
- refactor command functions into command classes
741
    def run(self, show_ids=False):
742
        b = Branch('.')
743
        old = b.basis_tree()
744
        new = b.working_tree()
745
746
        ## TODO: Much more efficient way to do this: read in new
747
        ## directories with readdir, rather than stating each one.  Same
748
        ## level of effort but possibly much less IO.  (Or possibly not,
749
        ## if the directories are very large...)
750
751
        for path, ie in old.inventory.iter_entries():
752
            if not new.has_id(ie.file_id):
753
                if show_ids:
754
                    print '%-50s %s' % (path, ie.file_id)
755
                else:
756
                    print path
757
437 by Martin Pool
- new command 'bzr modified' to exercise the statcache
758
759
class cmd_modified(Command):
760
    """List files modified in working tree."""
761
    hidden = True
762
    def run(self):
763
        import statcache
764
        b = Branch('.')
438 by Martin Pool
- Avoid calling Inventory.iter_entries() when finding modified
765
        inv = b.read_working_inventory()
766
        sc = statcache.update_cache(b, inv)
437 by Martin Pool
- new command 'bzr modified' to exercise the statcache
767
        basis = b.basis_tree()
768
        basis_inv = basis.inventory
438 by Martin Pool
- Avoid calling Inventory.iter_entries() when finding modified
769
        
770
        # We used to do this through iter_entries(), but that's slow
771
        # when most of the files are unmodified, as is usually the
772
        # case.  So instead we iterate by inventory entry, and only
773
        # calculate paths as necessary.
774
775
        for file_id in basis_inv:
776
            cacheentry = sc.get(file_id)
777
            if not cacheentry:                 # deleted
778
                continue
779
            ie = basis_inv[file_id]
437 by Martin Pool
- new command 'bzr modified' to exercise the statcache
780
            if cacheentry[statcache.SC_SHA1] != ie.text_sha1:
438 by Martin Pool
- Avoid calling Inventory.iter_entries() when finding modified
781
                path = inv.id2path(file_id)
437 by Martin Pool
- new command 'bzr modified' to exercise the statcache
782
                print path
439 by Martin Pool
- new command 'bzr added'
783
784
785
786
class cmd_added(Command):
787
    """List files added in working tree."""
788
    hidden = True
789
    def run(self):
790
        b = Branch('.')
791
        wt = b.working_tree()
792
        basis_inv = b.basis_tree().inventory
793
        inv = wt.inventory
794
        for file_id in inv:
795
            if file_id in basis_inv:
796
                continue
797
            path = inv.id2path(file_id)
798
            if not os.access(b.abspath(path), os.F_OK):
799
                continue
800
            print path
437 by Martin Pool
- new command 'bzr modified' to exercise the statcache
801
                
802
        
803
329 by Martin Pool
- refactor command functions into command classes
804
class cmd_root(Command):
805
    """Show the tree root directory.
806
807
    The root is the nearest enclosing directory with a .bzr control
808
    directory."""
809
    takes_args = ['filename?']
810
    def run(self, filename=None):
811
        """Print the branch root."""
416 by Martin Pool
- bzr log and bzr root now accept an http URL
812
        from branch import find_branch
813
        b = find_branch(filename)
814
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
329 by Martin Pool
- refactor command functions into command classes
815
816
817
class cmd_log(Command):
1 by mbp at sourcefrog
import from baz patch-364
818
    """Show log of this branch.
819
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
820
    To request a range of logs, you can use the command -r begin:end
821
    -r revision requests a specific revision, -r :end or -r begin: are
822
    also valid.
823
824
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
825
  
545 by Martin Pool
- --forward option for log
826
    """
367 by Martin Pool
- New --show-ids option for bzr log
827
378 by Martin Pool
- New usage bzr log FILENAME
828
    takes_args = ['filename?']
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
829
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision']
545 by Martin Pool
- --forward option for log
830
    
831
    def run(self, filename=None, timezone='original',
832
            verbose=False,
833
            show_ids=False,
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
834
            forward=False,
835
            revision=None):
527 by Martin Pool
- refactor log command
836
        from bzrlib import show_log, find_branch
562 by Martin Pool
- bug fix for printing logs containing unicode
837
        import codecs
545 by Martin Pool
- --forward option for log
838
839
        direction = (forward and 'forward') or 'reverse'
527 by Martin Pool
- refactor log command
840
        
378 by Martin Pool
- New usage bzr log FILENAME
841
        if filename:
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
842
            b = find_branch(filename)
527 by Martin Pool
- refactor log command
843
            fp = b.relpath(filename)
533 by Martin Pool
- fix up asking for the log for the root of a remote branch
844
            if fp:
845
                file_id = b.read_working_inventory().path2id(fp)
846
            else:
847
                file_id = None  # points to branch root
527 by Martin Pool
- refactor log command
848
        else:
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
849
            b = find_branch('.')
527 by Martin Pool
- refactor log command
850
            file_id = None
851
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
852
        if revision == None:
853
            revision = [None, None]
854
        elif isinstance(revision, int):
855
            revision = [revision, revision]
856
        else:
857
            # pair of revisions?
858
            pass
859
            
860
        assert len(revision) == 2
861
562 by Martin Pool
- bug fix for printing logs containing unicode
862
        mutter('encoding log as %r' % bzrlib.user_encoding)
610 by Martin Pool
- replace Branch.lock(mode) with separate lock_read and lock_write
863
864
        # use 'replace' so that we don't abort if trying to write out
865
        # in e.g. the default C locale.
866
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
562 by Martin Pool
- bug fix for printing logs containing unicode
867
527 by Martin Pool
- refactor log command
868
        show_log(b, file_id,
869
                 show_timezone=timezone,
870
                 verbose=verbose,
871
                 show_ids=show_ids,
562 by Martin Pool
- bug fix for printing logs containing unicode
872
                 to_file=outf,
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
873
                 direction=direction,
874
                 start_revision=revision[0],
875
                 end_revision=revision[1])
329 by Martin Pool
- refactor command functions into command classes
876
877
375 by Martin Pool
- New command touching-revisions and function to trace
878
879
class cmd_touching_revisions(Command):
523 by Martin Pool
doc
880
    """Return revision-ids which affected a particular file.
881
882
    A more user-friendly interface is "bzr log FILE"."""
375 by Martin Pool
- New command touching-revisions and function to trace
883
    hidden = True
884
    takes_args = ["filename"]
885
    def run(self, filename):
580 by Martin Pool
- Use explicit lock methods on a branch, rather than doing it
886
        b = Branch(filename)
375 by Martin Pool
- New command touching-revisions and function to trace
887
        inv = b.read_working_inventory()
888
        file_id = inv.path2id(b.relpath(filename))
889
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
890
            print "%6d %s" % (revno, what)
891
892
329 by Martin Pool
- refactor command functions into command classes
893
class cmd_ls(Command):
1 by mbp at sourcefrog
import from baz patch-364
894
    """List files in a tree.
895
254 by Martin Pool
- Doc cleanups from Magnus Therning
896
    TODO: Take a revision or remote path and list that tree instead.
1 by mbp at sourcefrog
import from baz patch-364
897
    """
329 by Martin Pool
- refactor command functions into command classes
898
    hidden = True
899
    def run(self, revision=None, verbose=False):
900
        b = Branch('.')
901
        if revision == None:
902
            tree = b.working_tree()
903
        else:
904
            tree = b.revision_tree(b.lookup_revision(revision))
905
906
        for fp, fc, kind, fid in tree.list_files():
907
            if verbose:
908
                if kind == 'directory':
909
                    kindch = '/'
910
                elif kind == 'file':
911
                    kindch = ''
912
                else:
913
                    kindch = '???'
914
915
                print '%-8s %s%s' % (fc, fp, kindch)
1 by mbp at sourcefrog
import from baz patch-364
916
            else:
329 by Martin Pool
- refactor command functions into command classes
917
                print fp
918
919
920
921
class cmd_unknowns(Command):
634 by Martin Pool
- Tidy help messages
922
    """List unknown files."""
329 by Martin Pool
- refactor command functions into command classes
923
    def run(self):
924
        for f in Branch('.').unknowns():
925
            print quotefn(f)
926
927
928
929
class cmd_ignore(Command):
634 by Martin Pool
- Tidy help messages
930
    """Ignore a command or pattern.
420 by Martin Pool
Doc
931
932
    To remove patterns from the ignore list, edit the .bzrignore file.
933
934
    If the pattern contains a slash, it is compared to the whole path
935
    from the branch root.  Otherwise, it is comapred to only the last
936
    component of the path.
937
938
    Ignore patterns are case-insensitive on case-insensitive systems.
939
940
    Note: wildcards must be quoted from the shell on Unix.
941
942
    examples:
943
        bzr ignore ./Makefile
944
        bzr ignore '*.class'
945
    """
329 by Martin Pool
- refactor command functions into command classes
946
    takes_args = ['name_pattern']
310 by Martin Pool
- new 'bzr ignored' command!
947
    
329 by Martin Pool
- refactor command functions into command classes
948
    def run(self, name_pattern):
409 by Martin Pool
- New AtomicFile class
949
        from bzrlib.atomicfile import AtomicFile
575 by Martin Pool
- cleanup imports
950
        import os.path
409 by Martin Pool
- New AtomicFile class
951
329 by Martin Pool
- refactor command functions into command classes
952
        b = Branch('.')
410 by Martin Pool
- Fix ignore command and add tests
953
        ifn = b.abspath('.bzrignore')
329 by Martin Pool
- refactor command functions into command classes
954
410 by Martin Pool
- Fix ignore command and add tests
955
        if os.path.exists(ifn):
498 by Martin Pool
bugfix for bzr ignore reported by ddaa:
956
            f = open(ifn, 'rt')
957
            try:
958
                igns = f.read().decode('utf-8')
959
            finally:
960
                f.close()
409 by Martin Pool
- New AtomicFile class
961
        else:
962
            igns = ''
963
575 by Martin Pool
- cleanup imports
964
        # TODO: If the file already uses crlf-style termination, maybe
965
        # we should use that for the newly added lines?
966
409 by Martin Pool
- New AtomicFile class
967
        if igns and igns[-1] != '\n':
968
            igns += '\n'
969
        igns += name_pattern + '\n'
970
498 by Martin Pool
bugfix for bzr ignore reported by ddaa:
971
        try:
972
            f = AtomicFile(ifn, 'wt')
973
            f.write(igns.encode('utf-8'))
974
            f.commit()
975
        finally:
976
            f.close()
329 by Martin Pool
- refactor command functions into command classes
977
978
        inv = b.working_tree().inventory
979
        if inv.path2id('.bzrignore'):
980
            mutter('.bzrignore is already versioned')
981
        else:
982
            mutter('need to make new .bzrignore file versioned')
983
            b.add(['.bzrignore'])
984
985
986
987
class cmd_ignored(Command):
421 by Martin Pool
doc
988
    """List ignored files and the patterns that matched them.
989
990
    See also: bzr ignore"""
329 by Martin Pool
- refactor command functions into command classes
991
    def run(self):
992
        tree = Branch('.').working_tree()
993
        for path, file_class, kind, file_id in tree.list_files():
994
            if file_class != 'I':
995
                continue
996
            ## XXX: Slightly inefficient since this was already calculated
997
            pat = tree.is_ignored(path)
998
            print '%-50s %s' % (path, pat)
999
1000
1001
class cmd_lookup_revision(Command):
1002
    """Lookup the revision-id from a revision-number
1003
1004
    example:
1005
        bzr lookup-revision 33
421 by Martin Pool
doc
1006
    """
329 by Martin Pool
- refactor command functions into command classes
1007
    hidden = True
338 by Martin Pool
- cleanup of some imports
1008
    takes_args = ['revno']
1009
    
329 by Martin Pool
- refactor command functions into command classes
1010
    def run(self, revno):
1011
        try:
1012
            revno = int(revno)
1013
        except ValueError:
338 by Martin Pool
- cleanup of some imports
1014
            raise BzrCommandError("not a valid revision-number: %r" % revno)
1015
1016
        print Branch('.').lookup_revision(revno)
329 by Martin Pool
- refactor command functions into command classes
1017
1018
1019
class cmd_export(Command):
1020
    """Export past revision to destination directory.
1021
678 by Martin Pool
- export to tarballs
1022
    If no revision is specified this exports the last committed revision.
1023
1024
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
1025
    given, exports to a directory (equivalent to --format=dir)."""
1026
    # TODO: list known exporters
329 by Martin Pool
- refactor command functions into command classes
1027
    takes_args = ['dest']
678 by Martin Pool
- export to tarballs
1028
    takes_options = ['revision', 'format']
1029
    def run(self, dest, revision=None, format='dir'):
329 by Martin Pool
- refactor command functions into command classes
1030
        b = Branch('.')
394 by Martin Pool
- Fix argument handling in export command
1031
        if revision == None:
1032
            rh = b.revision_history()[-1]
329 by Martin Pool
- refactor command functions into command classes
1033
        else:
394 by Martin Pool
- Fix argument handling in export command
1034
            rh = b.lookup_revision(int(revision))
329 by Martin Pool
- refactor command functions into command classes
1035
        t = b.revision_tree(rh)
678 by Martin Pool
- export to tarballs
1036
        t.export(dest, format)
329 by Martin Pool
- refactor command functions into command classes
1037
1038
1039
class cmd_cat(Command):
1040
    """Write a file's text from a previous revision."""
1041
1042
    takes_options = ['revision']
1043
    takes_args = ['filename']
1044
1045
    def run(self, filename, revision=None):
1046
        if revision == None:
1047
            raise BzrCommandError("bzr cat requires a revision number")
1048
        b = Branch('.')
1049
        b.print_file(b.relpath(filename), int(revision))
1050
1051
1052
class cmd_local_time_offset(Command):
1053
    """Show the offset in seconds from GMT to local time."""
1054
    hidden = True    
1055
    def run(self):
1056
        print bzrlib.osutils.local_time_offset()
1057
1058
1059
1060
class cmd_commit(Command):
1061
    """Commit changes into a new revision.
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
1062
491 by Martin Pool
- Selective commit!
1063
    If selected files are specified, only changes to those files are
1064
    committed.  If a directory is specified then its contents are also
1065
    committed.
1066
1067
    A selected-file commit may fail in some cases where the committed
1068
    tree would be invalid, such as trying to commit a file in a
1069
    newly-added directory that is not itself committed.
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
1070
1071
    TODO: Run hooks on tree to-be-committed, and after commit.
1072
1073
    TODO: Strict commit that fails if there are unknown or deleted files.
1074
    """
491 by Martin Pool
- Selective commit!
1075
    takes_args = ['selected*']
389 by Martin Pool
- new commit --file option!
1076
    takes_options = ['message', 'file', 'verbose']
350 by Martin Pool
- refactor command aliases into command classes
1077
    aliases = ['ci', 'checkin']
1078
505 by Martin Pool
- commit is verbose by default
1079
    def run(self, message=None, file=None, verbose=True, selected_list=None):
485 by Martin Pool
- move commit code into its own module
1080
        from bzrlib.commit import commit
1081
389 by Martin Pool
- new commit --file option!
1082
        ## Warning: shadows builtin file()
1083
        if not message and not file:
1084
            raise BzrCommandError("please specify a commit message",
1085
                                  ["use either --message or --file"])
1086
        elif message and file:
1087
            raise BzrCommandError("please specify either --message or --file")
1088
        
1089
        if file:
1090
            import codecs
1091
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
1092
485 by Martin Pool
- move commit code into its own module
1093
        b = Branch('.')
491 by Martin Pool
- Selective commit!
1094
        commit(b, message, verbose=verbose, specific_files=selected_list)
329 by Martin Pool
- refactor command functions into command classes
1095
1096
1097
class cmd_check(Command):
1098
    """Validate consistency of branch history.
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
1099
1100
    This command checks various invariants about the branch storage to
1101
    detect data corruption or bzr bugs.
674 by Martin Pool
- check command now also checks new inventory_sha1 and
1102
1103
    If given the --update flag, it will update some optional fields
1104
    to help ensure data consistency.
232 by mbp at sourcefrog
Allow docstrings for help to be in PEP0257 format.
1105
    """
329 by Martin Pool
- refactor command functions into command classes
1106
    takes_args = ['dir?']
674 by Martin Pool
- check command now also checks new inventory_sha1 and
1107
    takes_options = ['update']
1108
1109
    def run(self, dir='.', update=False):
329 by Martin Pool
- refactor command functions into command classes
1110
        import bzrlib.check
674 by Martin Pool
- check command now also checks new inventory_sha1 and
1111
        bzrlib.check.check(Branch(dir), update=update)
329 by Martin Pool
- refactor command functions into command classes
1112
1113
1114
1115
class cmd_whoami(Command):
1116
    """Show bzr user id."""
1117
    takes_options = ['email']
286 by Martin Pool
- New bzr whoami --email option
1118
    
329 by Martin Pool
- refactor command functions into command classes
1119
    def run(self, email=False):
1120
        if email:
1121
            print bzrlib.osutils.user_email()
1122
        else:
1123
            print bzrlib.osutils.username()
1124
1125
1126
class cmd_selftest(Command):
55 by mbp at sourcefrog
bzr selftest shows some counts of tests
1127
    """Run internal test suite"""
329 by Martin Pool
- refactor command functions into command classes
1128
    hidden = True
1129
    def run(self):
608 by Martin Pool
- Split selftests out into a new module and start changing them
1130
        from bzrlib.selftest import selftest
1131
        if selftest():
1132
            return 0
1133
        else:
515 by Martin Pool
- bzr selftest: return shell false (1) if any tests fail
1134
            return 1
55 by mbp at sourcefrog
bzr selftest shows some counts of tests
1135
329 by Martin Pool
- refactor command functions into command classes
1136
1137
1138
class cmd_version(Command):
634 by Martin Pool
- Tidy help messages
1139
    """Show version of bzr."""
329 by Martin Pool
- refactor command functions into command classes
1140
    def run(self):
1141
        show_version()
1142
1143
def show_version():
1144
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
605 by Martin Pool
- patch from Lalo Martins to show version of bzr itself
1145
    # is bzrlib itself in a branch?
606 by Martin Pool
- new bzrlib.get_bzr_revision() tells about the history of
1146
    bzrrev = bzrlib.get_bzr_revision()
1147
    if bzrrev:
1148
        print "  (bzr checkout, revision %d {%s})" % bzrrev
329 by Martin Pool
- refactor command functions into command classes
1149
    print bzrlib.__copyright__
1150
    print "http://bazaar-ng.org/"
1151
    print
1152
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
1153
    print "you may use, modify and redistribute it under the terms of the GNU"
1154
    print "General Public License version 2 or later."
1155
1156
1157
class cmd_rocks(Command):
1158
    """Statement of optimism."""
1159
    hidden = True
1160
    def run(self):
1161
        print "it sure does!"
1162
493 by Martin Pool
- Merge aaron's merge command
1163
def parse_spec(spec):
622 by Martin Pool
Updated merge patch from Aaron
1164
    """
1165
    >>> parse_spec(None)
1166
    [None, None]
1167
    >>> parse_spec("./")
1168
    ['./', None]
1169
    >>> parse_spec("../@")
1170
    ['..', -1]
1171
    >>> parse_spec("../f/@35")
1172
    ['../f', 35]
1173
    """
1174
    if spec is None:
1175
        return [None, None]
493 by Martin Pool
- Merge aaron's merge command
1176
    if '/@' in spec:
1177
        parsed = spec.split('/@')
1178
        assert len(parsed) == 2
1179
        if parsed[1] == "":
1180
            parsed[1] = -1
1181
        else:
1182
            parsed[1] = int(parsed[1])
1183
            assert parsed[1] >=0
1184
    else:
1185
        parsed = [spec, None]
1186
    return parsed
1187
628 by Martin Pool
- merge aaron's updated merge/pull code
1188
1189
493 by Martin Pool
- Merge aaron's merge command
1190
class cmd_merge(Command):
622 by Martin Pool
Updated merge patch from Aaron
1191
    """Perform a three-way merge of trees.
1192
    
1193
    The SPEC parameters are working tree or revision specifiers.  Working trees
1194
    are specified using standard paths or urls.  No component of a directory
1195
    path may begin with '@'.
1196
    
1197
    Working tree examples: '.', '..', 'foo@', but NOT 'foo/@bar'
1198
1199
    Revisions are specified using a dirname/@revno pair, where dirname is the
1200
    branch directory and revno is the revision within that branch.  If no revno
1201
    is specified, the latest revision is used.
1202
1203
    Revision examples: './@127', 'foo/@', '../@1'
1204
1205
    The OTHER_SPEC parameter is required.  If the BASE_SPEC parameter is
1206
    not supplied, the common ancestor of OTHER_SPEC the current branch is used
1207
    as the BASE.
628 by Martin Pool
- merge aaron's updated merge/pull code
1208
1209
    merge refuses to run if there are any uncommitted changes, unless
1210
    --force is given.
622 by Martin Pool
Updated merge patch from Aaron
1211
    """
1212
    takes_args = ['other_spec', 'base_spec?']
628 by Martin Pool
- merge aaron's updated merge/pull code
1213
    takes_options = ['force']
622 by Martin Pool
Updated merge patch from Aaron
1214
628 by Martin Pool
- merge aaron's updated merge/pull code
1215
    def run(self, other_spec, base_spec=None, force=False):
591 by Martin Pool
- trim imports
1216
        from bzrlib.merge import merge
628 by Martin Pool
- merge aaron's updated merge/pull code
1217
        merge(parse_spec(other_spec), parse_spec(base_spec),
1218
              check_clean=(not force))
329 by Martin Pool
- refactor command functions into command classes
1219
622 by Martin Pool
Updated merge patch from Aaron
1220
1221
class cmd_revert(Command):
628 by Martin Pool
- merge aaron's updated merge/pull code
1222
    """Reverse all changes since the last commit.
1223
1224
    Only versioned files are affected.
1225
1226
    TODO: Store backups of any files that will be reverted, so
1227
          that the revert can be undone.          
622 by Martin Pool
Updated merge patch from Aaron
1228
    """
1229
    takes_options = ['revision']
1230
1231
    def run(self, revision=-1):
636 by Martin Pool
- fix missing import in revert
1232
        from bzrlib.merge import merge
628 by Martin Pool
- merge aaron's updated merge/pull code
1233
        merge(('.', revision), parse_spec('.'),
1234
              check_clean=False,
1235
              ignore_zero=True)
622 by Martin Pool
Updated merge patch from Aaron
1236
1237
329 by Martin Pool
- refactor command functions into command classes
1238
class cmd_assert_fail(Command):
1239
    """Test reporting of assertion failures"""
1240
    hidden = True
1241
    def run(self):
1242
        assert False, "always fails"
1243
1244
1245
class cmd_help(Command):
1246
    """Show help on a command or other topic.
1247
1248
    For a list of all available commands, say 'bzr help commands'."""
1249
    takes_args = ['topic?']
350 by Martin Pool
- refactor command aliases into command classes
1250
    aliases = ['?']
329 by Martin Pool
- refactor command functions into command classes
1251
    
1252
    def run(self, topic=None):
351 by Martin Pool
- Split out help functions into bzrlib.help
1253
        import help
1254
        help.help(topic)
1255
1 by mbp at sourcefrog
import from baz patch-364
1256
429 by Martin Pool
- New command update-stat-cache for testing
1257
class cmd_update_stat_cache(Command):
1258
    """Update stat-cache mapping inodes to SHA-1 hashes.
1259
1260
    For testing only."""
1261
    hidden = True
1262
    def run(self):
1263
        import statcache
1264
        b = Branch('.')
454 by Martin Pool
- fix update-stat-cache command
1265
        statcache.update_cache(b.base, b.read_working_inventory())
429 by Martin Pool
- New command update-stat-cache for testing
1266
1267
1 by mbp at sourcefrog
import from baz patch-364
1268
1269
# list of all available options; the rhs can be either None for an
1270
# option that takes no argument, or a constructor function that checks
1271
# the type.
1272
OPTIONS = {
1273
    'all':                    None,
571 by Martin Pool
- new --diff-options to pass options through to external
1274
    'diff-options':           str,
1 by mbp at sourcefrog
import from baz patch-364
1275
    'help':                   None,
389 by Martin Pool
- new commit --file option!
1276
    'file':                   unicode,
628 by Martin Pool
- merge aaron's updated merge/pull code
1277
    'force':                  None,
678 by Martin Pool
- export to tarballs
1278
    'format':                 unicode,
545 by Martin Pool
- --forward option for log
1279
    'forward':                None,
1 by mbp at sourcefrog
import from baz patch-364
1280
    'message':                unicode,
594 by Martin Pool
- add --no-recurse option for add command
1281
    'no-recurse':             None,
137 by mbp at sourcefrog
new --profile option
1282
    'profile':                None,
567 by Martin Pool
- New form 'bzr log -r FROM:TO'
1283
    'revision':               _parse_revision_str,
1 by mbp at sourcefrog
import from baz patch-364
1284
    'show-ids':               None,
12 by mbp at sourcefrog
new --timezone option for bzr log
1285
    'timezone':               str,
1 by mbp at sourcefrog
import from baz patch-364
1286
    'verbose':                None,
1287
    'version':                None,
286 by Martin Pool
- New bzr whoami --email option
1288
    'email':                  None,
674 by Martin Pool
- check command now also checks new inventory_sha1 and
1289
    'update':                 None,
1 by mbp at sourcefrog
import from baz patch-364
1290
    }
1291
1292
SHORT_OPTIONS = {
583 by Martin Pool
- add -h as short name for --help
1293
    'F':                      'file', 
1294
    'h':                      'help',
1 by mbp at sourcefrog
import from baz patch-364
1295
    'm':                      'message',
1296
    'r':                      'revision',
1297
    'v':                      'verbose',
1298
}
1299
1300
1301
def parse_args(argv):
1302
    """Parse command line.
1303
    
1304
    Arguments and options are parsed at this level before being passed
1305
    down to specific command handlers.  This routine knows, from a
1306
    lookup table, something about the available options, what optargs
1307
    they take, and which commands will accept them.
1308
31 by Martin Pool
fix up parse_args doctest
1309
    >>> parse_args('--help'.split())
1 by mbp at sourcefrog
import from baz patch-364
1310
    ([], {'help': True})
31 by Martin Pool
fix up parse_args doctest
1311
    >>> parse_args('--version'.split())
1 by mbp at sourcefrog
import from baz patch-364
1312
    ([], {'version': True})
31 by Martin Pool
fix up parse_args doctest
1313
    >>> parse_args('status --all'.split())
1 by mbp at sourcefrog
import from baz patch-364
1314
    (['status'], {'all': True})
31 by Martin Pool
fix up parse_args doctest
1315
    >>> parse_args('commit --message=biter'.split())
17 by mbp at sourcefrog
allow --option=ARG syntax
1316
    (['commit'], {'message': u'biter'})
683 by Martin Pool
- short option stacking patch from John A Meinel
1317
    >>> parse_args('log -r 500'.split())
1318
    (['log'], {'revision': 500})
1319
    >>> parse_args('log -r500:600'.split())
1320
    (['log'], {'revision': [500, 600]})
1321
    >>> parse_args('log -vr500:600'.split())
1322
    (['log'], {'verbose': True, 'revision': [500, 600]})
1323
    >>> parse_args('log -rv500:600'.split()) #the r takes an argument
1324
    Traceback (most recent call last):
1325
    ...
1326
    ValueError: invalid literal for int(): v500
1 by mbp at sourcefrog
import from baz patch-364
1327
    """
1328
    args = []
1329
    opts = {}
1330
1331
    # TODO: Maybe handle '--' to end options?
1332
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
1333
    while argv:
1334
        a = argv.pop(0)
1 by mbp at sourcefrog
import from baz patch-364
1335
        if a[0] == '-':
264 by Martin Pool
parse_args: option names must be ascii
1336
            # option names must not be unicode
1337
            a = str(a)
17 by mbp at sourcefrog
allow --option=ARG syntax
1338
            optarg = None
1 by mbp at sourcefrog
import from baz patch-364
1339
            if a[1] == '-':
1340
                mutter("  got option %r" % a)
17 by mbp at sourcefrog
allow --option=ARG syntax
1341
                if '=' in a:
1342
                    optname, optarg = a[2:].split('=', 1)
1343
                else:
1344
                    optname = a[2:]
1 by mbp at sourcefrog
import from baz patch-364
1345
                if optname not in OPTIONS:
1346
                    bailout('unknown long option %r' % a)
1347
            else:
1348
                shortopt = a[1:]
683 by Martin Pool
- short option stacking patch from John A Meinel
1349
                if shortopt in SHORT_OPTIONS:
1350
                    # Multi-character options must have a space to delimit
1351
                    # their value
1352
                    optname = SHORT_OPTIONS[shortopt]
1353
                else:
1354
                    # Single character short options, can be chained,
1355
                    # and have their value appended to their name
1356
                    shortopt = a[1:2]
1357
                    if shortopt not in SHORT_OPTIONS:
1358
                        # We didn't find the multi-character name, and we
1359
                        # didn't find the single char name
1360
                        bailout('unknown short option %r' % a)
1361
                    optname = SHORT_OPTIONS[shortopt]
1362
1363
                    if a[2:]:
1364
                        # There are extra things on this option
1365
                        # see if it is the value, or if it is another
1366
                        # short option
1367
                        optargfn = OPTIONS[optname]
1368
                        if optargfn is None:
1369
                            # This option does not take an argument, so the
1370
                            # next entry is another short option, pack it back
1371
                            # into the list
1372
                            argv.insert(0, '-' + a[2:])
1373
                        else:
1374
                            # This option takes an argument, so pack it
1375
                            # into the array
1376
                            optarg = a[2:]
1 by mbp at sourcefrog
import from baz patch-364
1377
            
1378
            if optname in opts:
1379
                # XXX: Do we ever want to support this, e.g. for -r?
1380
                bailout('repeated option %r' % a)
17 by mbp at sourcefrog
allow --option=ARG syntax
1381
                
1 by mbp at sourcefrog
import from baz patch-364
1382
            optargfn = OPTIONS[optname]
1383
            if optargfn:
17 by mbp at sourcefrog
allow --option=ARG syntax
1384
                if optarg == None:
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
1385
                    if not argv:
17 by mbp at sourcefrog
allow --option=ARG syntax
1386
                        bailout('option %r needs an argument' % a)
1387
                    else:
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
1388
                        optarg = argv.pop(0)
17 by mbp at sourcefrog
allow --option=ARG syntax
1389
                opts[optname] = optargfn(optarg)
1 by mbp at sourcefrog
import from baz patch-364
1390
            else:
17 by mbp at sourcefrog
allow --option=ARG syntax
1391
                if optarg != None:
1392
                    bailout('option %r takes no argument' % optname)
1 by mbp at sourcefrog
import from baz patch-364
1393
                opts[optname] = True
1394
        else:
1395
            args.append(a)
1396
1397
    return args, opts
1398
1399
1400
1401
329 by Martin Pool
- refactor command functions into command classes
1402
def _match_argform(cmd, takes_args, args):
1 by mbp at sourcefrog
import from baz patch-364
1403
    argdict = {}
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
1404
329 by Martin Pool
- refactor command functions into command classes
1405
    # step through args and takes_args, allowing appropriate 0-many matches
1406
    for ap in takes_args:
1 by mbp at sourcefrog
import from baz patch-364
1407
        argname = ap[:-1]
1408
        if ap[-1] == '?':
62 by mbp at sourcefrog
- new find_branch_root function; based on suggestion from aaron
1409
            if args:
1410
                argdict[argname] = args.pop(0)
196 by mbp at sourcefrog
selected-file diff
1411
        elif ap[-1] == '*': # all remaining arguments
1412
            if args:
1413
                argdict[argname + '_list'] = args[:]
1414
                args = []
1415
            else:
1416
                argdict[argname + '_list'] = None
1 by mbp at sourcefrog
import from baz patch-364
1417
        elif ap[-1] == '+':
1418
            if not args:
329 by Martin Pool
- refactor command functions into command classes
1419
                raise BzrCommandError("command %r needs one or more %s"
1 by mbp at sourcefrog
import from baz patch-364
1420
                        % (cmd, argname.upper()))
1421
            else:
1422
                argdict[argname + '_list'] = args[:]
1423
                args = []
160 by mbp at sourcefrog
- basic support for moving files to different directories - have not done support for renaming them yet, but should be straightforward - some tests, but many cases are not handled yet i think
1424
        elif ap[-1] == '$': # all but one
1425
            if len(args) < 2:
329 by Martin Pool
- refactor command functions into command classes
1426
                raise BzrCommandError("command %r needs one or more %s"
160 by mbp at sourcefrog
- basic support for moving files to different directories - have not done support for renaming them yet, but should be straightforward - some tests, but many cases are not handled yet i think
1427
                        % (cmd, argname.upper()))
1428
            argdict[argname + '_list'] = args[:-1]
1429
            args[:-1] = []                
1 by mbp at sourcefrog
import from baz patch-364
1430
        else:
1431
            # just a plain arg
1432
            argname = ap
1433
            if not args:
329 by Martin Pool
- refactor command functions into command classes
1434
                raise BzrCommandError("command %r requires argument %s"
1 by mbp at sourcefrog
import from baz patch-364
1435
                        % (cmd, argname.upper()))
1436
            else:
1437
                argdict[argname] = args.pop(0)
1438
            
1439
    if args:
329 by Martin Pool
- refactor command functions into command classes
1440
        raise BzrCommandError("extra argument to command %s: %s"
1441
                              % (cmd, args[0]))
1 by mbp at sourcefrog
import from baz patch-364
1442
1443
    return argdict
1444
1445
1446
1447
def run_bzr(argv):
1448
    """Execute a command.
1449
1450
    This is similar to main(), but without all the trappings for
245 by mbp at sourcefrog
- control files always in utf-8-unix format
1451
    logging and error handling.  
1 by mbp at sourcefrog
import from baz patch-364
1452
    """
251 by mbp at sourcefrog
- factor out locale.getpreferredencoding()
1453
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
245 by mbp at sourcefrog
- control files always in utf-8-unix format
1454
    
641 by Martin Pool
- improved external-command patch from john
1455
    include_plugins=True
1 by mbp at sourcefrog
import from baz patch-364
1456
    try:
26 by mbp at sourcefrog
fix StopIteration error on python2.3(?)
1457
        args, opts = parse_args(argv[1:])
1 by mbp at sourcefrog
import from baz patch-364
1458
        if 'help' in opts:
351 by Martin Pool
- Split out help functions into bzrlib.help
1459
            import help
159 by mbp at sourcefrog
bzr commit --help now works
1460
            if args:
351 by Martin Pool
- Split out help functions into bzrlib.help
1461
                help.help(args[0])
159 by mbp at sourcefrog
bzr commit --help now works
1462
            else:
351 by Martin Pool
- Split out help functions into bzrlib.help
1463
                help.help()
1 by mbp at sourcefrog
import from baz patch-364
1464
            return 0
1465
        elif 'version' in opts:
336 by Martin Pool
- fix up 'bzr --version'
1466
            show_version()
1 by mbp at sourcefrog
import from baz patch-364
1467
            return 0
641 by Martin Pool
- improved external-command patch from john
1468
        elif args and args[0] == 'builtin':
1469
            include_plugins=False
1470
            args = args[1:]
265 by Martin Pool
parse_args: command names must also be ascii
1471
        cmd = str(args.pop(0))
1 by mbp at sourcefrog
import from baz patch-364
1472
    except IndexError:
448 by Martin Pool
- bzr with no command now shows help, not just an error
1473
        import help
1474
        help.help()
1 by mbp at sourcefrog
import from baz patch-364
1475
        return 1
448 by Martin Pool
- bzr with no command now shows help, not just an error
1476
          
115 by mbp at sourcefrog
todo
1477
641 by Martin Pool
- improved external-command patch from john
1478
    canonical_cmd, cmd_class = get_cmd_class(cmd,include_plugins=include_plugins)
1 by mbp at sourcefrog
import from baz patch-364
1479
137 by mbp at sourcefrog
new --profile option
1480
    # global option
1481
    if 'profile' in opts:
1482
        profile = True
1483
        del opts['profile']
1484
    else:
1485
        profile = False
1 by mbp at sourcefrog
import from baz patch-364
1486
1487
    # check options are reasonable
329 by Martin Pool
- refactor command functions into command classes
1488
    allowed = cmd_class.takes_options
1 by mbp at sourcefrog
import from baz patch-364
1489
    for oname in opts:
1490
        if oname not in allowed:
381 by Martin Pool
- Better message when a wrong argument is given
1491
            raise BzrCommandError("option '--%s' is not allowed for command %r"
329 by Martin Pool
- refactor command functions into command classes
1492
                                  % (oname, cmd))
176 by mbp at sourcefrog
New cat command contributed by janmar.
1493
137 by mbp at sourcefrog
new --profile option
1494
    # mix arguments and options into one dictionary
329 by Martin Pool
- refactor command functions into command classes
1495
    cmdargs = _match_argform(cmd, cmd_class.takes_args, args)
1496
    cmdopts = {}
136 by mbp at sourcefrog
new --show-ids option for 'deleted' command
1497
    for k, v in opts.items():
329 by Martin Pool
- refactor command functions into command classes
1498
        cmdopts[k.replace('-', '_')] = v
1 by mbp at sourcefrog
import from baz patch-364
1499
137 by mbp at sourcefrog
new --profile option
1500
    if profile:
338 by Martin Pool
- cleanup of some imports
1501
        import hotshot, tempfile
239 by mbp at sourcefrog
- remove profiler temporary file when done
1502
        pffileno, pfname = tempfile.mkstemp()
1503
        try:
1504
            prof = hotshot.Profile(pfname)
329 by Martin Pool
- refactor command functions into command classes
1505
            ret = prof.runcall(cmd_class, cmdopts, cmdargs) or 0
239 by mbp at sourcefrog
- remove profiler temporary file when done
1506
            prof.close()
1507
1508
            import hotshot.stats
1509
            stats = hotshot.stats.load(pfname)
1510
            #stats.strip_dirs()
1511
            stats.sort_stats('time')
1512
            ## XXX: Might like to write to stderr or the trace file instead but
1513
            ## print_stats seems hardcoded to stdout
1514
            stats.print_stats(20)
1515
            
337 by Martin Pool
- Clarify return codes from command objects
1516
            return ret.status
239 by mbp at sourcefrog
- remove profiler temporary file when done
1517
1518
        finally:
1519
            os.close(pffileno)
1520
            os.remove(pfname)
137 by mbp at sourcefrog
new --profile option
1521
    else:
500 by Martin Pool
- fix return value from run_bzr
1522
        return cmd_class(cmdopts, cmdargs).status 
1 by mbp at sourcefrog
import from baz patch-364
1523
1524
359 by Martin Pool
- pychecker fixups
1525
def _report_exception(summary, quiet=False):
267 by Martin Pool
- better reporting of errors
1526
    import traceback
1527
    log_error('bzr: ' + summary)
359 by Martin Pool
- pychecker fixups
1528
    bzrlib.trace.log_exception()
317 by Martin Pool
- better error message for broken pipe
1529
1530
    if not quiet:
1531
        tb = sys.exc_info()[2]
1532
        exinfo = traceback.extract_tb(tb)
1533
        if exinfo:
1534
            sys.stderr.write('  at %s:%d in %s()\n' % exinfo[-1][:3])
1535
        sys.stderr.write('  see ~/.bzr.log for debug information\n')
267 by Martin Pool
- better reporting of errors
1536
1537
1538
1 by mbp at sourcefrog
import from baz patch-364
1539
def main(argv):
317 by Martin Pool
- better error message for broken pipe
1540
    import errno
1541
    
344 by Martin Pool
- It's not an error to use the library without
1542
    bzrlib.open_tracefile(argv)
260 by Martin Pool
- remove atexit() dependency for writing out execution times
1543
1 by mbp at sourcefrog
import from baz patch-364
1544
    try:
260 by Martin Pool
- remove atexit() dependency for writing out execution times
1545
        try:
337 by Martin Pool
- Clarify return codes from command objects
1546
            try:
1547
                return run_bzr(argv)
1548
            finally:
1549
                # do this here inside the exception wrappers to catch EPIPE
1550
                sys.stdout.flush()
260 by Martin Pool
- remove atexit() dependency for writing out execution times
1551
        except BzrError, e:
329 by Martin Pool
- refactor command functions into command classes
1552
            quiet = isinstance(e, (BzrCommandError))
359 by Martin Pool
- pychecker fixups
1553
            _report_exception('error: ' + e.args[0], quiet=quiet)
260 by Martin Pool
- remove atexit() dependency for writing out execution times
1554
            if len(e.args) > 1:
1555
                for h in e.args[1]:
267 by Martin Pool
- better reporting of errors
1556
                    # some explanation or hints
260 by Martin Pool
- remove atexit() dependency for writing out execution times
1557
                    log_error('  ' + h)
1558
            return 1
267 by Martin Pool
- better reporting of errors
1559
        except AssertionError, e:
1560
            msg = 'assertion failed'
1561
            if str(e):
1562
                msg += ': ' + str(e)
359 by Martin Pool
- pychecker fixups
1563
            _report_exception(msg)
318 by Martin Pool
- better error message for Ctrl-c
1564
            return 2
1565
        except KeyboardInterrupt, e:
359 by Martin Pool
- pychecker fixups
1566
            _report_exception('interrupted', quiet=True)
318 by Martin Pool
- better error message for Ctrl-c
1567
            return 2
260 by Martin Pool
- remove atexit() dependency for writing out execution times
1568
        except Exception, e:
317 by Martin Pool
- better error message for broken pipe
1569
            quiet = False
419 by Martin Pool
- RemoteBranch.__str__ and repr
1570
            if (isinstance(e, IOError) 
1571
                and hasattr(e, 'errno')
1572
                and e.errno == errno.EPIPE):
317 by Martin Pool
- better error message for broken pipe
1573
                quiet = True
1574
                msg = 'broken pipe'
1575
            else:
1576
                msg = str(e).rstrip('\n')
359 by Martin Pool
- pychecker fixups
1577
            _report_exception(msg, quiet)
318 by Martin Pool
- better error message for Ctrl-c
1578
            return 2
260 by Martin Pool
- remove atexit() dependency for writing out execution times
1579
    finally:
1580
        bzrlib.trace.close_trace()
1 by mbp at sourcefrog
import from baz patch-364
1581
1582
1583
if __name__ == '__main__':
1584
    sys.exit(main(sys.argv))