~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

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

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
 
 
18
 
 
19
 
import sys, os
 
17
"""Bazaar-NG -- a free distributed version-control tool
 
18
http://bazaar-ng.org/
 
19
 
 
20
**WARNING: THIS IS AN UNSTABLE DEVELOPMENT VERSION**
 
21
 
 
22
* Metadata format is not stable yet -- you may need to
 
23
  discard history in the future.
 
24
 
 
25
* Many commands unimplemented or partially implemented.
 
26
 
 
27
* Space-inefficient storage.
 
28
 
 
29
* No merge operators yet.
 
30
 
 
31
Interesting commands:
 
32
 
 
33
  bzr help [COMMAND]
 
34
      Show help screen
 
35
  bzr version
 
36
      Show software version/licence/non-warranty.
 
37
  bzr init
 
38
      Start versioning the current directory
 
39
  bzr add FILE...
 
40
      Make files versioned.
 
41
  bzr log
 
42
      Show revision history.
 
43
  bzr rename FROM TO
 
44
      Rename one file.
 
45
  bzr move FROM... DESTDIR
 
46
      Move one or more files to a different directory.
 
47
  bzr diff [FILE...]
 
48
      Show changes from last revision to working copy.
 
49
  bzr commit -m 'MESSAGE'
 
50
      Store current state as new revision.
 
51
  bzr export [-r REVNO] DESTINATION
 
52
      Export the branch state at a previous version.
 
53
  bzr status
 
54
      Show summary of pending changes.
 
55
  bzr remove FILE...
 
56
      Make a file not versioned.
 
57
  bzr info
 
58
      Show statistics about this branch.
 
59
  bzr check
 
60
      Verify history is stored safely. 
 
61
  (for more type 'bzr help commands')
 
62
"""
 
63
 
 
64
 
 
65
 
 
66
 
 
67
import sys, os, time, types, shutil, tempfile, fnmatch, difflib, os.path
 
68
from sets import Set
 
69
from pprint import pprint
 
70
from stat import *
 
71
from glob import glob
20
72
 
21
73
import bzrlib
 
74
from bzrlib.store import ImmutableStore
22
75
from bzrlib.trace import mutter, note, log_error
23
76
from bzrlib.errors import bailout, BzrError, BzrCheckError, BzrCommandError
24
 
from bzrlib.osutils import quotefn
25
 
from bzrlib import Branch, Inventory, InventoryEntry, BZRDIR, \
 
77
from bzrlib.osutils import quotefn, pumpfile, isdir, isfile
 
78
from bzrlib.tree import RevisionTree, EmptyTree, WorkingTree, Tree
 
79
from bzrlib.revision import Revision
 
80
from bzrlib import Branch, Inventory, InventoryEntry, ScratchBranch, BZRDIR, \
26
81
     format_date
27
82
 
28
 
 
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
 
 
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
 
 
71
 
def get_all_cmds():
72
 
    """Return canonical name and class for all registered commands."""
73
 
    for k, v in globals().iteritems():
74
 
        if k.startswith("cmd_"):
75
 
            yield _unsquish_command_name(k), v
 
83
BZR_DIFF_FORMAT = "## Bazaar-NG diff, format 0 ##\n"
 
84
BZR_PATCHNAME_FORMAT = 'cset:sha1:%s'
 
85
 
 
86
## standard representation
 
87
NONE_STRING = '(none)'
 
88
EMPTY = 'empty'
 
89
 
 
90
 
 
91
CMD_ALIASES = {
 
92
    '?':         'help',
 
93
    'ci':        'commit',
 
94
    'checkin':   'commit',
 
95
    'di':        'diff',
 
96
    'st':        'status',
 
97
    'stat':      'status',
 
98
    }
 
99
 
76
100
 
77
101
def get_cmd_class(cmd):
78
 
    """Return the canonical name and command class for a command.
79
 
    """
80
 
    cmd = str(cmd)                      # not unicode
81
 
 
82
 
    # first look up this command under the specified name
 
102
    cmd = str(cmd)
 
103
    
 
104
    cmd = CMD_ALIASES.get(cmd, cmd)
 
105
    
83
106
    try:
84
 
        return cmd, globals()[_squish_command_name(cmd)]
 
107
        cmd_class = globals()['cmd_' + cmd.replace('-', '_')]
85
108
    except KeyError:
86
 
        pass
87
 
 
88
 
    # look for any command which claims this as an alias
89
 
    for cmdname, cmdclass in get_all_cmds():
90
 
        if cmd in cmdclass.aliases:
91
 
            return cmdname, cmdclass
92
 
 
93
 
    cmdclass = ExternalCommand.find_command(cmd)
94
 
    if cmdclass:
95
 
        return cmd, cmdclass
96
 
 
97
 
    raise BzrCommandError("unknown command %r" % cmd)
98
 
 
99
 
 
100
 
class Command(object):
 
109
        raise BzrError("unknown command %r" % cmd)
 
110
 
 
111
    return cmd, cmd_class
 
112
 
 
113
 
 
114
 
 
115
class Command:
101
116
    """Base class for commands.
102
117
 
103
118
    The docstring for an actual command should give a single-line
140
155
        This is invoked with the options and arguments bound to
141
156
        keyword parameters.
142
157
 
143
 
        Return 0 or None if the command was successful, or a shell
144
 
        error code if not.
 
158
        Return True if the command was successful, False if not.
145
159
        """
146
 
        return 0
147
 
 
148
 
 
149
 
class ExternalCommand(Command):
150
 
    """Class to wrap external commands.
151
 
 
152
 
    We cheat a little here, when get_cmd_class() calls us we actually give it back
153
 
    an object we construct that has the appropriate path, help, options etc for the
154
 
    specified command.
155
 
 
156
 
    When run_bzr() tries to instantiate that 'class' it gets caught by the __call__
157
 
    method, which we override to call the Command.__init__ method. That then calls
158
 
    our run method which is pretty straight forward.
159
 
 
160
 
    The only wrinkle is that we have to map bzr's dictionary of options and arguments
161
 
    back into command line options and arguments for the script.
162
 
    """
163
 
 
164
 
    def find_command(cls, cmd):
165
 
        import os.path
166
 
        bzrpath = os.environ.get('BZRPATH', '')
167
 
 
168
 
        for dir in bzrpath.split(':'):
169
 
            path = os.path.join(dir, cmd)
170
 
            if os.path.isfile(path):
171
 
                return ExternalCommand(path)
172
 
 
173
 
        return None
174
 
 
175
 
    find_command = classmethod(find_command)
176
 
 
177
 
    def __init__(self, path):
178
 
        self.path = path
179
 
 
180
 
        # TODO: If either of these fail, we should detect that and
181
 
        # assume that path is not really a bzr plugin after all.
182
 
 
183
 
        pipe = os.popen('%s --bzr-usage' % path, 'r')
184
 
        self.takes_options = pipe.readline().split()
185
 
        self.takes_args = pipe.readline().split()
186
 
        pipe.close()
187
 
 
188
 
        pipe = os.popen('%s --bzr-help' % path, 'r')
189
 
        self.__doc__ = pipe.read()
190
 
        pipe.close()
191
 
 
192
 
    def __call__(self, options, arguments):
193
 
        Command.__init__(self, options, arguments)
194
 
        return self
195
 
 
196
 
    def run(self, **kargs):
197
 
        opts = []
198
 
        args = []
199
 
 
200
 
        keys = kargs.keys()
201
 
        keys.sort()
202
 
        for name in keys:
203
 
            value = kargs[name]
204
 
            if OPTIONS.has_key(name):
205
 
                # it's an option
206
 
                opts.append('--%s' % name)
207
 
                if value is not None and value is not True:
208
 
                    opts.append(str(value))
209
 
            else:
210
 
                # it's an arg, or arg list
211
 
                if type(value) is not list:
212
 
                    value = [value]
213
 
                for v in value:
214
 
                    if v is not None:
215
 
                        args.append(str(v))
216
 
 
217
 
        self.status = os.spawnv(os.P_WAIT, self.path, [self.path] + opts + args)
218
 
        return self.status
 
160
        return True
 
161
 
219
162
 
220
163
 
221
164
class cmd_status(Command):
222
165
    """Display status summary.
223
166
 
224
 
    This reports on versioned and unknown files, reporting them
225
 
    grouped by state.  Possible states are:
226
 
 
227
 
    added
228
 
        Versioned in the working copy but not in the previous revision.
229
 
 
230
 
    removed
231
 
        Versioned in the previous revision but removed or deleted
232
 
        in the working copy.
233
 
 
234
 
    renamed
235
 
        Path of this file changed from the previous revision;
236
 
        the text may also have changed.  This includes files whose
237
 
        parent directory was renamed.
238
 
 
239
 
    modified
240
 
        Text has changed since the previous revision.
241
 
 
242
 
    unchanged
243
 
        Nothing about this file has changed since the previous revision.
244
 
        Only shown with --all.
245
 
 
246
 
    unknown
247
 
        Not versioned and not matching an ignore pattern.
248
 
 
249
 
    To see ignored files use 'bzr ignored'.  For details in the
250
 
    changes to file texts, use 'bzr diff'.
251
 
 
252
 
    If no arguments are specified, the status of the entire working
253
 
    directory is shown.  Otherwise, only the status of the specified
254
 
    files or directories is reported.  If a directory is given, status
255
 
    is reported for everything inside that directory.
 
167
    For each file there is a single line giving its file state and name.
 
168
    The name is that in the current revision unless it is deleted or
 
169
    missing, in which case the old name is shown.
256
170
    """
257
 
    takes_args = ['file*']
258
 
    takes_options = ['all', 'show-ids']
259
 
    aliases = ['st', 'stat']
 
171
    takes_options = ['all']
260
172
    
261
 
    def run(self, all=False, show_ids=False, file_list=None):
262
 
        if file_list:
263
 
            b = Branch(file_list[0])
264
 
            file_list = [b.relpath(x) for x in file_list]
265
 
            # special case: only one path was given and it's the root
266
 
            # of the branch
267
 
            if file_list == ['']:
268
 
                file_list = None
269
 
        else:
270
 
            b = Branch('.')
271
 
        import status
272
 
        status.show_status(b, show_unchanged=all, show_ids=show_ids,
273
 
                           specific_files=file_list)
 
173
    def run(self, all=False):
 
174
        #import bzrlib.status
 
175
        #bzrlib.status.tree_status(Branch('.'))
 
176
        Branch('.').show_status(show_all=all)
274
177
 
275
178
 
276
179
class cmd_cat_revision(Command):
313
216
    recursively add that parent, rather than giving an error?
314
217
    """
315
218
    takes_args = ['file+']
316
 
    takes_options = ['verbose', 'no-recurse']
 
219
    takes_options = ['verbose']
317
220
    
318
 
    def run(self, file_list, verbose=False, no_recurse=False):
319
 
        bzrlib.add.smart_add(file_list, verbose, not no_recurse)
320
 
 
321
 
 
322
 
class cmd_relpath(Command):
 
221
    def run(self, file_list, verbose=False):
 
222
        bzrlib.add.smart_add(file_list, verbose)
 
223
 
 
224
 
 
225
def Relpath(Command):
323
226
    """Show path of a file relative to root"""
324
 
    takes_args = ['filename']
325
 
    hidden = True
 
227
    takes_args = ('filename')
326
228
    
327
 
    def run(self, filename):
328
 
        print Branch(filename).relpath(filename)
 
229
    def run(self):
 
230
        print Branch(self.args['filename']).relpath(filename)
329
231
 
330
232
 
331
233
 
332
234
class cmd_inventory(Command):
333
235
    """Show inventory of the current working copy or a revision."""
334
 
    takes_options = ['revision', 'show-ids']
 
236
    takes_options = ['revision']
335
237
    
336
 
    def run(self, revision=None, show_ids=False):
 
238
    def run(self, revision=None):
337
239
        b = Branch('.')
338
240
        if revision == None:
339
241
            inv = b.read_working_inventory()
340
242
        else:
341
243
            inv = b.get_revision_inventory(b.lookup_revision(revision))
342
244
 
343
 
        for path, entry in inv.entries():
344
 
            if show_ids:
345
 
                print '%-50s %s' % (path, entry.file_id)
346
 
            else:
347
 
                print path
 
245
        for path, entry in inv.iter_entries():
 
246
            print '%-50s %s' % (entry.file_id, path)
348
247
 
349
248
 
350
249
class cmd_move(Command):
405
304
 
406
305
 
407
306
class cmd_info(Command):
408
 
    """Show statistical information about a branch."""
409
 
    takes_args = ['branch?']
410
 
    
411
 
    def run(self, branch=None):
 
307
    """Show statistical information for this branch"""
 
308
    def run(self):
412
309
        import info
413
 
 
414
 
        from branch import find_branch
415
 
        b = find_branch(branch)
416
 
        info.show_info(b)
 
310
        info.show_info(Branch('.'))        
417
311
 
418
312
 
419
313
class cmd_remove(Command):
467
361
 
468
362
class cmd_revision_history(Command):
469
363
    """Display list of revision ids on this branch."""
470
 
    hidden = True
471
364
    def run(self):
472
365
        for patchid in Branch('.').revision_history():
473
366
            print patchid
525
418
    """
526
419
    
527
420
    takes_args = ['file*']
528
 
    takes_options = ['revision', 'diff-options']
529
 
    aliases = ['di']
 
421
    takes_options = ['revision']
530
422
 
531
 
    def run(self, revision=None, file_list=None, diff_options=None):
 
423
    def run(self, revision=None, file_list=None):
532
424
        from bzrlib.diff import show_diff
533
 
        from bzrlib import find_branch
534
 
 
535
 
        if file_list:
536
 
            b = find_branch(file_list[0])
537
 
            file_list = [b.relpath(f) for f in file_list]
538
 
            if file_list == ['']:
539
 
                # just pointing to top-of-tree
540
 
                file_list = None
541
 
        else:
542
 
            b = Branch('.')
543
425
    
544
 
        show_diff(b, revision, specific_files=file_list,
545
 
                  external_diff_options=diff_options)
546
 
 
547
 
 
548
 
        
 
426
        show_diff(Branch('.'), revision, file_list)
549
427
 
550
428
 
551
429
class cmd_deleted(Command):
570
448
                else:
571
449
                    print path
572
450
 
573
 
 
574
 
class cmd_modified(Command):
575
 
    """List files modified in working tree."""
576
 
    hidden = True
577
 
    def run(self):
578
 
        import statcache
579
 
        b = Branch('.')
580
 
        inv = b.read_working_inventory()
581
 
        sc = statcache.update_cache(b, inv)
582
 
        basis = b.basis_tree()
583
 
        basis_inv = basis.inventory
584
 
        
585
 
        # We used to do this through iter_entries(), but that's slow
586
 
        # when most of the files are unmodified, as is usually the
587
 
        # case.  So instead we iterate by inventory entry, and only
588
 
        # calculate paths as necessary.
589
 
 
590
 
        for file_id in basis_inv:
591
 
            cacheentry = sc.get(file_id)
592
 
            if not cacheentry:                 # deleted
593
 
                continue
594
 
            ie = basis_inv[file_id]
595
 
            if cacheentry[statcache.SC_SHA1] != ie.text_sha1:
596
 
                path = inv.id2path(file_id)
597
 
                print path
598
 
 
599
 
 
600
 
 
601
 
class cmd_added(Command):
602
 
    """List files added in working tree."""
603
 
    hidden = True
604
 
    def run(self):
605
 
        b = Branch('.')
606
 
        wt = b.working_tree()
607
 
        basis_inv = b.basis_tree().inventory
608
 
        inv = wt.inventory
609
 
        for file_id in inv:
610
 
            if file_id in basis_inv:
611
 
                continue
612
 
            path = inv.id2path(file_id)
613
 
            if not os.access(b.abspath(path), os.F_OK):
614
 
                continue
615
 
            print path
616
 
                
617
 
        
618
 
 
619
451
class cmd_root(Command):
620
452
    """Show the tree root directory.
621
453
 
624
456
    takes_args = ['filename?']
625
457
    def run(self, filename=None):
626
458
        """Print the branch root."""
627
 
        from branch import find_branch
628
 
        b = find_branch(filename)
629
 
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
 
459
        print bzrlib.branch.find_branch_root(filename)
 
460
 
630
461
 
631
462
 
632
463
class cmd_log(Command):
633
464
    """Show log of this branch.
634
465
 
635
 
    To request a range of logs, you can use the command -r begin:end
636
 
    -r revision requests a specific revision, -r :end or -r begin: are
637
 
    also valid.
638
 
 
639
 
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
640
 
  
 
466
    TODO: Options to show ids; to limit range; etc.
641
467
    """
642
 
 
643
 
    takes_args = ['filename?']
644
 
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision']
645
 
    
646
 
    def run(self, filename=None, timezone='original',
647
 
            verbose=False,
648
 
            show_ids=False,
649
 
            forward=False,
650
 
            revision=None):
651
 
        from bzrlib import show_log, find_branch
652
 
        import codecs
653
 
 
654
 
        direction = (forward and 'forward') or 'reverse'
655
 
        
656
 
        if filename:
657
 
            b = find_branch(filename)
658
 
            fp = b.relpath(filename)
659
 
            if fp:
660
 
                file_id = b.read_working_inventory().path2id(fp)
661
 
            else:
662
 
                file_id = None  # points to branch root
663
 
        else:
664
 
            b = find_branch('.')
665
 
            file_id = None
666
 
 
667
 
        if revision == None:
668
 
            revision = [None, None]
669
 
        elif isinstance(revision, int):
670
 
            revision = [revision, revision]
671
 
        else:
672
 
            # pair of revisions?
673
 
            pass
674
 
            
675
 
        assert len(revision) == 2
676
 
 
677
 
        mutter('encoding log as %r' % bzrlib.user_encoding)
678
 
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout)
679
 
 
680
 
        show_log(b, file_id,
681
 
                 show_timezone=timezone,
682
 
                 verbose=verbose,
683
 
                 show_ids=show_ids,
684
 
                 to_file=outf,
685
 
                 direction=direction,
686
 
                 start_revision=revision[0],
687
 
                 end_revision=revision[1])
688
 
 
689
 
 
690
 
 
691
 
class cmd_touching_revisions(Command):
692
 
    """Return revision-ids which affected a particular file.
693
 
 
694
 
    A more user-friendly interface is "bzr log FILE"."""
695
 
    hidden = True
696
 
    takes_args = ["filename"]
697
 
    def run(self, filename):
698
 
        b = Branch(filename)
699
 
        inv = b.read_working_inventory()
700
 
        file_id = inv.path2id(b.relpath(filename))
701
 
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
702
 
            print "%6d %s" % (revno, what)
 
468
    takes_options = ['timezone', 'verbose']
 
469
    def run(self, timezone='original', verbose=False):
 
470
        Branch('.').write_log(show_timezone=timezone, verbose=verbose)
703
471
 
704
472
 
705
473
class cmd_ls(Command):
739
507
 
740
508
 
741
509
class cmd_ignore(Command):
742
 
    """Ignore a command or pattern
743
 
 
744
 
    To remove patterns from the ignore list, edit the .bzrignore file.
745
 
 
746
 
    If the pattern contains a slash, it is compared to the whole path
747
 
    from the branch root.  Otherwise, it is comapred to only the last
748
 
    component of the path.
749
 
 
750
 
    Ignore patterns are case-insensitive on case-insensitive systems.
751
 
 
752
 
    Note: wildcards must be quoted from the shell on Unix.
753
 
 
754
 
    examples:
755
 
        bzr ignore ./Makefile
756
 
        bzr ignore '*.class'
757
 
    """
 
510
    """Ignore a command or pattern"""
758
511
    takes_args = ['name_pattern']
759
512
    
760
513
    def run(self, name_pattern):
761
 
        from bzrlib.atomicfile import AtomicFile
762
 
        import os.path
763
 
 
764
514
        b = Branch('.')
765
 
        ifn = b.abspath('.bzrignore')
766
 
 
767
 
        if os.path.exists(ifn):
768
 
            f = open(ifn, 'rt')
769
 
            try:
770
 
                igns = f.read().decode('utf-8')
771
 
            finally:
772
 
                f.close()
773
 
        else:
774
 
            igns = ''
775
 
 
776
 
        # TODO: If the file already uses crlf-style termination, maybe
777
 
        # we should use that for the newly added lines?
778
 
 
779
 
        if igns and igns[-1] != '\n':
780
 
            igns += '\n'
781
 
        igns += name_pattern + '\n'
782
 
 
783
 
        try:
784
 
            f = AtomicFile(ifn, 'wt')
785
 
            f.write(igns.encode('utf-8'))
786
 
            f.commit()
787
 
        finally:
788
 
            f.close()
 
515
 
 
516
        # XXX: This will fail if it's a hardlink; should use an AtomicFile class.
 
517
        f = open(b.abspath('.bzrignore'), 'at')
 
518
        f.write(name_pattern + '\n')
 
519
        f.close()
789
520
 
790
521
        inv = b.working_tree().inventory
791
522
        if inv.path2id('.bzrignore'):
797
528
 
798
529
 
799
530
class cmd_ignored(Command):
800
 
    """List ignored files and the patterns that matched them.
801
 
 
802
 
    See also: bzr ignore"""
 
531
    """List ignored files and the patterns that matched them."""
803
532
    def run(self):
804
533
        tree = Branch('.').working_tree()
805
534
        for path, file_class, kind, file_id in tree.list_files():
815
544
 
816
545
    example:
817
546
        bzr lookup-revision 33
818
 
    """
 
547
        """
819
548
    hidden = True
820
 
    takes_args = ['revno']
821
 
    
822
549
    def run(self, revno):
823
550
        try:
824
551
            revno = int(revno)
825
552
        except ValueError:
826
 
            raise BzrCommandError("not a valid revision-number: %r" % revno)
827
 
 
828
 
        print Branch('.').lookup_revision(revno)
 
553
            raise BzrError("not a valid revision-number: %r" % revno)
 
554
 
 
555
        print Branch('.').lookup_revision(revno) or NONE_STRING
 
556
 
829
557
 
830
558
 
831
559
class cmd_export(Command):
834
562
    If no revision is specified this exports the last committed revision."""
835
563
    takes_args = ['dest']
836
564
    takes_options = ['revision']
837
 
    def run(self, dest, revision=None):
 
565
    def run(self, dest, revno=None):
838
566
        b = Branch('.')
839
 
        if revision == None:
840
 
            rh = b.revision_history()[-1]
 
567
        if revno == None:
 
568
            rh = b.revision_history[-1]
841
569
        else:
842
 
            rh = b.lookup_revision(int(revision))
 
570
            rh = b.lookup_revision(int(revno))
843
571
        t = b.revision_tree(rh)
844
572
        t.export(dest)
845
573
 
868
596
class cmd_commit(Command):
869
597
    """Commit changes into a new revision.
870
598
 
871
 
    If selected files are specified, only changes to those files are
872
 
    committed.  If a directory is specified then its contents are also
873
 
    committed.
874
 
 
875
 
    A selected-file commit may fail in some cases where the committed
876
 
    tree would be invalid, such as trying to commit a file in a
877
 
    newly-added directory that is not itself committed.
 
599
    TODO: Commit only selected files.
878
600
 
879
601
    TODO: Run hooks on tree to-be-committed, and after commit.
880
602
 
881
603
    TODO: Strict commit that fails if there are unknown or deleted files.
882
604
    """
883
 
    takes_args = ['selected*']
884
 
    takes_options = ['message', 'file', 'verbose']
885
 
    aliases = ['ci', 'checkin']
886
 
 
887
 
    def run(self, message=None, file=None, verbose=True, selected_list=None):
888
 
        from bzrlib.commit import commit
889
 
 
890
 
        ## Warning: shadows builtin file()
891
 
        if not message and not file:
892
 
            raise BzrCommandError("please specify a commit message",
893
 
                                  ["use either --message or --file"])
894
 
        elif message and file:
895
 
            raise BzrCommandError("please specify either --message or --file")
896
 
        
897
 
        if file:
898
 
            import codecs
899
 
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
900
 
 
901
 
        b = Branch('.')
902
 
        commit(b, message, verbose=verbose, specific_files=selected_list)
 
605
    takes_options = ['message', 'verbose']
 
606
    
 
607
    def run(self, message=None, verbose=False):
 
608
        if not message:
 
609
            raise BzrCommandError("please specify a commit message")
 
610
        Branch('.').commit(message, verbose=verbose)
903
611
 
904
612
 
905
613
class cmd_check(Command):
911
619
    takes_args = ['dir?']
912
620
    def run(self, dir='.'):
913
621
        import bzrlib.check
914
 
        bzrlib.check.check(Branch(dir))
 
622
        bzrlib.check.check(Branch(dir, find_root=False))
915
623
 
916
624
 
917
625
 
932
640
    def run(self):
933
641
        failures, tests = 0, 0
934
642
 
935
 
        import doctest, bzrlib.store
 
643
        import doctest, bzrlib.store, bzrlib.tests
936
644
        bzrlib.trace.verbose = False
937
645
 
938
646
        for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
939
 
            bzrlib.tree, bzrlib.commands, bzrlib.add:
 
647
            bzrlib.tree, bzrlib.tests, bzrlib.commands, bzrlib.add:
940
648
            mf, mt = doctest.testmod(m)
941
649
            failures += mf
942
650
            tests += mt
949
657
        print '%-40s %3d tests' % ('total', tests),
950
658
        if failures:
951
659
            print '%3d FAILED!' % failures
952
 
            return 1
953
660
        else:
954
661
            print
955
 
            return 0
956
662
 
957
663
 
958
664
 
977
683
    def run(self):
978
684
        print "it sure does!"
979
685
 
980
 
def parse_spec(spec):
981
 
    if '/@' in spec:
982
 
        parsed = spec.split('/@')
983
 
        assert len(parsed) == 2
984
 
        if parsed[1] == "":
985
 
            parsed[1] = -1
986
 
        else:
987
 
            parsed[1] = int(parsed[1])
988
 
            assert parsed[1] >=0
989
 
    else:
990
 
        parsed = [spec, None]
991
 
    return parsed
992
 
 
993
 
class cmd_merge(Command):
994
 
    """Perform a three-way merge of trees."""
995
 
    takes_args = ['other_spec', 'base_spec']
996
 
 
997
 
    def run(self, other_spec, base_spec):
998
 
        from bzrlib.merge import merge
999
 
        merge(parse_spec(other_spec), parse_spec(base_spec))
1000
686
 
1001
687
class cmd_assert_fail(Command):
1002
688
    """Test reporting of assertion failures"""
1010
696
 
1011
697
    For a list of all available commands, say 'bzr help commands'."""
1012
698
    takes_args = ['topic?']
1013
 
    aliases = ['?']
1014
699
    
1015
700
    def run(self, topic=None):
1016
 
        import help
1017
 
        help.help(topic)
1018
 
 
1019
 
 
1020
 
class cmd_update_stat_cache(Command):
1021
 
    """Update stat-cache mapping inodes to SHA-1 hashes.
1022
 
 
1023
 
    For testing only."""
1024
 
    hidden = True
1025
 
    def run(self):
1026
 
        import statcache
1027
 
        b = Branch('.')
1028
 
        statcache.update_cache(b.base, b.read_working_inventory())
1029
 
 
 
701
        help(topic)
 
702
 
 
703
 
 
704
def help(topic=None):
 
705
    if topic == None:
 
706
        print __doc__
 
707
    elif topic == 'commands':
 
708
        help_commands()
 
709
    else:
 
710
        help_on_command(topic)
 
711
 
 
712
 
 
713
def help_on_command(cmdname):
 
714
    cmdname = str(cmdname)
 
715
 
 
716
    from inspect import getdoc
 
717
    topic, cmdclass = get_cmd_class(cmdname)
 
718
 
 
719
    doc = getdoc(cmdclass)
 
720
    if doc == None:
 
721
        raise NotImplementedError("sorry, no detailed help yet for %r" % cmdname)
 
722
 
 
723
    if '\n' in doc:
 
724
        short, rest = doc.split('\n', 1)
 
725
    else:
 
726
        short = doc
 
727
        rest = ''
 
728
 
 
729
    print 'usage: bzr ' + topic,
 
730
    for aname in cmdclass.takes_args:
 
731
        aname = aname.upper()
 
732
        if aname[-1] in ['$', '+']:
 
733
            aname = aname[:-1] + '...'
 
734
        elif aname[-1] == '?':
 
735
            aname = '[' + aname[:-1] + ']'
 
736
        elif aname[-1] == '*':
 
737
            aname = '[' + aname[:-1] + '...]'
 
738
        print aname,
 
739
    print 
 
740
    print short
 
741
    if rest:
 
742
        print rest
 
743
 
 
744
    if cmdclass.takes_options:
 
745
        print
 
746
        print 'options:'
 
747
        for on in cmdclass.takes_options:
 
748
            print '    --%s' % on
 
749
 
 
750
 
 
751
def help_commands():
 
752
    """List all commands"""
 
753
    import inspect
 
754
    
 
755
    accu = []
 
756
    for k, v in globals().items():
 
757
        if k.startswith('cmd_'):
 
758
            accu.append((k[4:].replace('_','-'), v))
 
759
    accu.sort()
 
760
    for cmdname, cmdclass in accu:
 
761
        if cmdclass.hidden:
 
762
            continue
 
763
        print cmdname
 
764
        help = inspect.getdoc(cmdclass)
 
765
        if help:
 
766
            print "    " + help.split('\n', 1)[0]
 
767
 
 
768
 
 
769
######################################################################
 
770
# main routine
1030
771
 
1031
772
 
1032
773
# list of all available options; the rhs can be either None for an
1034
775
# the type.
1035
776
OPTIONS = {
1036
777
    'all':                    None,
1037
 
    'diff-options':           str,
1038
778
    'help':                   None,
1039
 
    'file':                   unicode,
1040
 
    'forward':                None,
1041
779
    'message':                unicode,
1042
 
    'no-recurse':             None,
1043
780
    'profile':                None,
1044
 
    'revision':               _parse_revision_str,
 
781
    'revision':               int,
1045
782
    'show-ids':               None,
1046
783
    'timezone':               str,
1047
784
    'verbose':                None,
1050
787
    }
1051
788
 
1052
789
SHORT_OPTIONS = {
1053
 
    'F':                      'file', 
1054
 
    'h':                      'help',
1055
790
    'm':                      'message',
1056
791
    'r':                      'revision',
1057
792
    'v':                      'verbose',
1175
910
    This is similar to main(), but without all the trappings for
1176
911
    logging and error handling.  
1177
912
    """
 
913
 
1178
914
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
1179
915
    
1180
916
    try:
1181
917
        args, opts = parse_args(argv[1:])
1182
918
        if 'help' in opts:
1183
 
            import help
1184
919
            if args:
1185
 
                help.help(args[0])
 
920
                help(args[0])
1186
921
            else:
1187
 
                help.help()
 
922
                help()
1188
923
            return 0
1189
924
        elif 'version' in opts:
1190
 
            show_version()
 
925
            cmd_version([], [])
1191
926
            return 0
1192
927
        cmd = str(args.pop(0))
1193
928
    except IndexError:
1194
 
        import help
1195
 
        help.help()
 
929
        log_error('usage: bzr COMMAND')
 
930
        log_error('  try "bzr help"')
1196
931
        return 1
1197
 
          
1198
932
 
1199
933
    canonical_cmd, cmd_class = get_cmd_class(cmd)
1200
934
 
1209
943
    allowed = cmd_class.takes_options
1210
944
    for oname in opts:
1211
945
        if oname not in allowed:
1212
 
            raise BzrCommandError("option '--%s' is not allowed for command %r"
 
946
            raise BzrCommandError("option %r is not allowed for command %r"
1213
947
                                  % (oname, cmd))
1214
948
 
1215
949
    # mix arguments and options into one dictionary
1219
953
        cmdopts[k.replace('-', '_')] = v
1220
954
 
1221
955
    if profile:
1222
 
        import hotshot, tempfile
 
956
        import hotshot
1223
957
        pffileno, pfname = tempfile.mkstemp()
1224
958
        try:
1225
959
            prof = hotshot.Profile(pfname)
1234
968
            ## print_stats seems hardcoded to stdout
1235
969
            stats.print_stats(20)
1236
970
            
1237
 
            return ret.status
 
971
            return ret
1238
972
 
1239
973
        finally:
1240
974
            os.close(pffileno)
1241
975
            os.remove(pfname)
1242
976
    else:
1243
 
        return cmd_class(cmdopts, cmdargs).status 
1244
 
 
1245
 
 
1246
 
def _report_exception(summary, quiet=False):
 
977
        cmdobj = cmd_class(cmdopts, cmdargs) or 0
 
978
 
 
979
 
 
980
 
 
981
def _report_exception(e, summary, quiet=False):
1247
982
    import traceback
1248
983
    log_error('bzr: ' + summary)
1249
 
    bzrlib.trace.log_exception()
 
984
    bzrlib.trace.log_exception(e)
1250
985
 
1251
986
    if not quiet:
1252
987
        tb = sys.exc_info()[2]
1260
995
def main(argv):
1261
996
    import errno
1262
997
    
1263
 
    bzrlib.open_tracefile(argv)
 
998
    bzrlib.trace.create_tracefile(argv)
1264
999
 
1265
1000
    try:
1266
1001
        try:
1267
 
            try:
1268
 
                return run_bzr(argv)
1269
 
            finally:
1270
 
                # do this here inside the exception wrappers to catch EPIPE
1271
 
                sys.stdout.flush()
 
1002
            ret = run_bzr(argv)
 
1003
            # do this here to catch EPIPE
 
1004
            sys.stdout.flush()
 
1005
            return ret
1272
1006
        except BzrError, e:
1273
1007
            quiet = isinstance(e, (BzrCommandError))
1274
 
            _report_exception('error: ' + e.args[0], quiet=quiet)
 
1008
            _report_exception(e, 'error: ' + e.args[0], quiet=quiet)
1275
1009
            if len(e.args) > 1:
1276
1010
                for h in e.args[1]:
1277
1011
                    # some explanation or hints
1281
1015
            msg = 'assertion failed'
1282
1016
            if str(e):
1283
1017
                msg += ': ' + str(e)
1284
 
            _report_exception(msg)
 
1018
            _report_exception(e, msg)
1285
1019
            return 2
1286
1020
        except KeyboardInterrupt, e:
1287
 
            _report_exception('interrupted', quiet=True)
 
1021
            _report_exception(e, 'interrupted', quiet=True)
1288
1022
            return 2
1289
1023
        except Exception, e:
1290
1024
            quiet = False
1291
 
            if (isinstance(e, IOError) 
1292
 
                and hasattr(e, 'errno')
1293
 
                and e.errno == errno.EPIPE):
 
1025
            if isinstance(e, IOError) and e.errno == errno.EPIPE:
1294
1026
                quiet = True
1295
1027
                msg = 'broken pipe'
1296
1028
            else:
1297
1029
                msg = str(e).rstrip('\n')
1298
 
            _report_exception(msg, quiet)
 
1030
            _report_exception(e, msg, quiet)
1299
1031
            return 2
1300
1032
    finally:
1301
1033
        bzrlib.trace.close_trace()