~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-03-15 05:19:54 UTC
  • Revision ID: mbp@sourcefrog.net-20050315051954-e4bdd6dfd26f8ecf
witty comment

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005 by Canonical Ltd
 
1
#! /usr/bin/python
 
2
 
 
3
 
 
4
# Copyright (C) 2004, 2005 by Martin Pool
 
5
# Copyright (C) 2005 by Canonical Ltd
 
6
 
2
7
 
3
8
# This program is free software; you can redistribute it and/or modify
4
9
# it under the terms of the GNU General Public License as published by
14
19
# along with this program; if not, write to the Free Software
15
20
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
21
 
17
 
 
18
 
 
19
 
import sys, os, time, os.path
 
22
"""Bazaar-NG -- a free distributed version-control tool
 
23
 
 
24
**WARNING: THIS IS AN UNSTABLE DEVELOPMENT VERSION**
 
25
 
 
26
Current limitation include:
 
27
 
 
28
* Metadata format is not stable yet -- you may need to
 
29
  discard history in the future.
 
30
 
 
31
* No handling of subdirectories, symlinks or any non-text files.
 
32
 
 
33
* Insufficient error handling.
 
34
 
 
35
* Many commands unimplemented or partially implemented.
 
36
 
 
37
* Space-inefficient storage.
 
38
 
 
39
* No merge operators yet.
 
40
 
 
41
Interesting commands::
 
42
 
 
43
  bzr help
 
44
       Show summary help screen
 
45
  bzr version
 
46
       Show software version/licence/non-warranty.
 
47
  bzr init
 
48
       Start versioning the current directory
 
49
  bzr add FILE...
 
50
       Make files versioned.
 
51
  bzr log
 
52
       Show revision history.
 
53
  bzr diff
 
54
       Show changes from last revision to working copy.
 
55
  bzr commit -m 'MESSAGE'
 
56
       Store current state as new revision.
 
57
  bzr export REVNO DESTINATION
 
58
       Export the branch state at a previous version.
 
59
  bzr status
 
60
       Show summary of pending changes.
 
61
  bzr remove FILE...
 
62
       Make a file not versioned.
 
63
"""
 
64
 
 
65
# not currently working:
 
66
#  bzr info
 
67
#       Show some information about this branch.
 
68
 
 
69
 
 
70
 
 
71
__copyright__ = "Copyright 2005 Canonical Development Ltd."
 
72
__author__ = "Martin Pool <mbp@canonical.com>"
 
73
__docformat__ = "restructuredtext en"
 
74
__version__ = '0.0.0'
 
75
 
 
76
 
 
77
import sys, os, random, time, sha, sets, types, re, shutil, tempfile
 
78
import traceback, socket, fnmatch, difflib
 
79
from os import path
20
80
from sets import Set
 
81
from pprint import pprint
 
82
from stat import *
 
83
from glob import glob
21
84
 
22
85
import bzrlib
 
86
from bzrlib.store import ImmutableStore
23
87
from bzrlib.trace import mutter, note, log_error
24
 
from bzrlib.errors import bailout, BzrError, BzrCheckError, BzrCommandError
 
88
from bzrlib.errors import bailout, BzrError
25
89
from bzrlib.osutils import quotefn, pumpfile, isdir, isfile
26
 
from bzrlib.tree import RevisionTree, EmptyTree, Tree
 
90
from bzrlib.tree import RevisionTree, EmptyTree, WorkingTree, Tree
27
91
from bzrlib.revision import Revision
28
92
from bzrlib import Branch, Inventory, InventoryEntry, ScratchBranch, BZRDIR, \
29
93
     format_date
30
 
from bzrlib import merge
31
 
 
32
 
 
33
 
def _squish_command_name(cmd):
34
 
    return 'cmd_' + cmd.replace('-', '_')
35
 
 
36
 
 
37
 
def _unsquish_command_name(cmd):
38
 
    assert cmd.startswith("cmd_")
39
 
    return cmd[4:].replace('_','-')
40
 
 
41
 
def get_all_cmds():
42
 
    """Return canonical name and class for all registered commands."""
43
 
    for k, v in globals().iteritems():
44
 
        if k.startswith("cmd_"):
45
 
            yield _unsquish_command_name(k), v
46
 
 
47
 
def get_cmd_class(cmd):
48
 
    """Return the canonical name and command class for a command.
49
 
    """
50
 
    cmd = str(cmd)                      # not unicode
51
 
 
52
 
    # first look up this command under the specified name
53
 
    try:
54
 
        return cmd, globals()[_squish_command_name(cmd)]
55
 
    except KeyError:
56
 
        pass
57
 
 
58
 
    # look for any command which claims this as an alias
59
 
    for cmdname, cmdclass in get_all_cmds():
60
 
        if cmd in cmdclass.aliases:
61
 
            return cmdname, cmdclass
62
 
 
63
 
    cmdclass = ExternalCommand.find_command(cmd)
64
 
    if cmdclass:
65
 
        return cmd, cmdclass
66
 
 
67
 
    raise BzrCommandError("unknown command %r" % cmd)
68
 
 
69
 
 
70
 
class Command:
71
 
    """Base class for commands.
72
 
 
73
 
    The docstring for an actual command should give a single-line
74
 
    summary, then a complete description of the command.  A grammar
75
 
    description will be inserted.
76
 
 
77
 
    takes_args
78
 
        List of argument forms, marked with whether they are optional,
79
 
        repeated, etc.
80
 
 
81
 
    takes_options
82
 
        List of options that may be given for this command.
83
 
 
84
 
    hidden
85
 
        If true, this command isn't advertised.
86
 
    """
87
 
    aliases = []
88
 
    
89
 
    takes_args = []
90
 
    takes_options = []
91
 
 
92
 
    hidden = False
93
 
    
94
 
    def __init__(self, options, arguments):
95
 
        """Construct and run the command.
96
 
 
97
 
        Sets self.status to the return value of run()."""
98
 
        assert isinstance(options, dict)
99
 
        assert isinstance(arguments, dict)
100
 
        cmdargs = options.copy()
101
 
        cmdargs.update(arguments)
102
 
        assert self.__doc__ != Command.__doc__, \
103
 
               ("No help message set for %r" % self)
104
 
        self.status = self.run(**cmdargs)
105
 
 
106
 
    
107
 
    def run(self):
108
 
        """Override this in sub-classes.
109
 
 
110
 
        This is invoked with the options and arguments bound to
111
 
        keyword parameters.
112
 
 
113
 
        Return 0 or None if the command was successful, or a shell
114
 
        error code if not.
115
 
        """
116
 
        return 0
117
 
 
118
 
 
119
 
class ExternalCommand(Command):
120
 
    """Class to wrap external commands.
121
 
 
122
 
    We cheat a little here, when get_cmd_class() calls us we actually give it back
123
 
    an object we construct that has the appropriate path, help, options etc for the
124
 
    specified command.
125
 
 
126
 
    When run_bzr() tries to instantiate that 'class' it gets caught by the __call__
127
 
    method, which we override to call the Command.__init__ method. That then calls
128
 
    our run method which is pretty straight forward.
129
 
 
130
 
    The only wrinkle is that we have to map bzr's dictionary of options and arguments
131
 
    back into command line options and arguments for the script.
132
 
    """
133
 
 
134
 
    def find_command(cls, cmd):
135
 
        bzrpath = os.environ.get('BZRPATH', '')
136
 
 
137
 
        for dir in bzrpath.split(':'):
138
 
            path = os.path.join(dir, cmd)
139
 
            if os.path.isfile(path):
140
 
                return ExternalCommand(path)
141
 
 
142
 
        return None
143
 
 
144
 
    find_command = classmethod(find_command)
145
 
 
146
 
    def __init__(self, path):
147
 
        self.path = path
148
 
 
149
 
        # TODO: If either of these fail, we should detect that and
150
 
        # assume that path is not really a bzr plugin after all.
151
 
 
152
 
        pipe = os.popen('%s --bzr-usage' % path, 'r')
153
 
        self.takes_options = pipe.readline().split()
154
 
        self.takes_args = pipe.readline().split()
155
 
        pipe.close()
156
 
 
157
 
        pipe = os.popen('%s --bzr-help' % path, 'r')
158
 
        self.__doc__ = pipe.read()
159
 
        pipe.close()
160
 
 
161
 
    def __call__(self, options, arguments):
162
 
        Command.__init__(self, options, arguments)
163
 
        return self
164
 
 
165
 
    def run(self, **kargs):
166
 
        opts = []
167
 
        args = []
168
 
 
169
 
        keys = kargs.keys()
170
 
        keys.sort()
171
 
        for name in keys:
172
 
            value = kargs[name]
173
 
            if OPTIONS.has_key(name):
174
 
                # it's an option
175
 
                opts.append('--%s' % name)
176
 
                if value is not None and value is not True:
177
 
                    opts.append(str(value))
178
 
            else:
179
 
                # it's an arg, or arg list
180
 
                if type(value) is not list:
181
 
                    value = [value]
182
 
                for v in value:
183
 
                    if v is not None:
184
 
                        args.append(str(v))
185
 
 
186
 
        self.status = os.spawnv(os.P_WAIT, self.path, [self.path] + opts + args)
187
 
        return self.status
188
 
 
189
 
 
190
 
class cmd_status(Command):
 
94
 
 
95
BZR_DIFF_FORMAT = "## Bazaar-NG diff, format 0 ##\n"
 
96
BZR_PATCHNAME_FORMAT = 'cset:sha1:%s'
 
97
 
 
98
## standard representation
 
99
NONE_STRING = '(none)'
 
100
EMPTY = 'empty'
 
101
 
 
102
 
 
103
## TODO: Perhaps a different version of inventory commands that
 
104
## returns iterators...
 
105
 
 
106
## TODO: Perhaps an AtomicFile class that writes to a temporary file and then renames.
 
107
 
 
108
## TODO: Some kind of locking on branches.  Perhaps there should be a
 
109
## parameter to the branch object saying whether we want a read or
 
110
## write lock; release it from destructor.  Perhaps don't even need a
 
111
## read lock to look at immutable objects?
 
112
 
 
113
## TODO: Perhaps make UUIDs predictable in test mode to make it easier
 
114
## to compare output?
 
115
 
 
116
## TODO: Some kind of global code to generate the right Branch object
 
117
## to work on.  Almost, but not quite all, commands need one, and it
 
118
## can be taken either from their parameters or their working
 
119
## directory.
 
120
 
 
121
## TODO: rename command, needed soon: check destination doesn't exist
 
122
## either in working copy or tree; move working copy; update
 
123
## inventory; write out
 
124
 
 
125
## TODO: move command; check destination is a directory and will not
 
126
## clash; move it.
 
127
 
 
128
## TODO: command to show renames, one per line, as to->from
 
129
 
 
130
 
 
131
 
 
132
 
 
133
def cmd_status(all=False):
191
134
    """Display status summary.
192
135
 
193
 
    This reports on versioned and unknown files, reporting them
194
 
    grouped by state.  Possible states are:
195
 
 
196
 
    added
197
 
        Versioned in the working copy but not in the previous revision.
198
 
 
199
 
    removed
200
 
        Versioned in the previous revision but removed or deleted
201
 
        in the working copy.
202
 
 
203
 
    renamed
204
 
        Path of this file changed from the previous revision;
205
 
        the text may also have changed.  This includes files whose
206
 
        parent directory was renamed.
207
 
 
208
 
    modified
209
 
        Text has changed since the previous revision.
210
 
 
211
 
    unchanged
212
 
        Nothing about this file has changed since the previous revision.
213
 
        Only shown with --all.
214
 
 
215
 
    unknown
216
 
        Not versioned and not matching an ignore pattern.
217
 
 
218
 
    To see ignored files use 'bzr ignored'.  For details in the
219
 
    changes to file texts, use 'bzr diff'.
220
 
 
221
 
    If no arguments are specified, the status of the entire working
222
 
    directory is shown.  Otherwise, only the status of the specified
223
 
    files or directories is reported.  If a directory is given, status
224
 
    is reported for everything inside that directory.
225
 
    """
226
 
    takes_args = ['file*']
227
 
    takes_options = ['all', 'show-ids']
228
 
    aliases = ['st', 'stat']
229
 
    
230
 
    def run(self, all=False, show_ids=False, file_list=None):
231
 
        if file_list:
232
 
            b = Branch(file_list[0], lock_mode='r')
233
 
            file_list = [b.relpath(x) for x in file_list]
234
 
            # special case: only one path was given and it's the root
235
 
            # of the branch
236
 
            if file_list == ['']:
237
 
                file_list = None
238
 
        else:
239
 
            b = Branch('.', lock_mode='r')
240
 
        import status
241
 
        status.show_status(b, show_unchanged=all, show_ids=show_ids,
242
 
                           specific_files=file_list)
243
 
 
244
 
 
245
 
class cmd_cat_revision(Command):
246
 
    """Write out metadata for a revision."""
247
 
 
248
 
    hidden = True
249
 
    takes_args = ['revision_id']
250
 
    
251
 
    def run(self, revision_id):
252
 
        Branch('.').get_revision(revision_id).write_xml(sys.stdout)
253
 
 
254
 
 
255
 
class cmd_revno(Command):
256
 
    """Show current revision number.
257
 
 
258
 
    This is equal to the number of revisions on this branch."""
259
 
    def run(self):
260
 
        print Branch('.').revno()
261
 
 
262
 
    
263
 
class cmd_add(Command):
264
 
    """Add specified files or directories.
265
 
 
266
 
    In non-recursive mode, all the named items are added, regardless
267
 
    of whether they were previously ignored.  A warning is given if
268
 
    any of the named files are already versioned.
269
 
 
270
 
    In recursive mode (the default), files are treated the same way
271
 
    but the behaviour for directories is different.  Directories that
272
 
    are already versioned do not give a warning.  All directories,
273
 
    whether already versioned or not, are searched for files or
274
 
    subdirectories that are neither versioned or ignored, and these
275
 
    are added.  This search proceeds recursively into versioned
276
 
    directories.
277
 
 
278
 
    Therefore simply saying 'bzr add .' will version all files that
279
 
    are currently unknown.
280
 
 
281
 
    TODO: Perhaps adding a file whose directly is not versioned should
282
 
    recursively add that parent, rather than giving an error?
283
 
    """
284
 
    takes_args = ['file+']
285
 
    takes_options = ['verbose']
286
 
    
287
 
    def run(self, file_list, verbose=False):
288
 
        bzrlib.add.smart_add(file_list, verbose)
289
 
 
290
 
 
291
 
class cmd_relpath(Command):
292
 
    """Show path of a file relative to root"""
293
 
    takes_args = ['filename']
294
 
    
295
 
    def run(self, filename):
296
 
        print Branch(filename).relpath(filename)
297
 
 
298
 
 
299
 
 
300
 
class cmd_inventory(Command):
301
 
    """Show inventory of the current working copy or a revision."""
302
 
    takes_options = ['revision']
303
 
    
304
 
    def run(self, revision=None):
305
 
        b = Branch('.')
306
 
        if revision == None:
307
 
            inv = b.read_working_inventory()
308
 
        else:
309
 
            inv = b.get_revision_inventory(b.lookup_revision(revision))
310
 
 
311
 
        for path, entry in inv.iter_entries():
312
 
            print '%-50s %s' % (entry.file_id, path)
313
 
 
314
 
 
315
 
class cmd_move(Command):
316
 
    """Move files to a different directory.
317
 
 
318
 
    examples:
319
 
        bzr move *.txt doc
320
 
 
321
 
    The destination must be a versioned directory in the same branch.
322
 
    """
323
 
    takes_args = ['source$', 'dest']
324
 
    def run(self, source_list, dest):
325
 
        b = Branch('.')
326
 
 
327
 
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
328
 
 
329
 
 
330
 
class cmd_rename(Command):
331
 
    """Change the name of an entry.
332
 
 
333
 
    examples:
334
 
      bzr rename frob.c frobber.c
335
 
      bzr rename src/frob.c lib/frob.c
336
 
 
337
 
    It is an error if the destination name exists.
338
 
 
339
 
    See also the 'move' command, which moves files into a different
340
 
    directory without changing their name.
341
 
 
342
 
    TODO: Some way to rename multiple files without invoking bzr for each
343
 
    one?"""
344
 
    takes_args = ['from_name', 'to_name']
345
 
    
346
 
    def run(self, from_name, to_name):
347
 
        b = Branch('.')
348
 
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
349
 
 
350
 
 
351
 
 
352
 
class cmd_renames(Command):
353
 
    """Show list of renamed files.
354
 
 
355
 
    TODO: Option to show renames between two historical versions.
356
 
 
357
 
    TODO: Only show renames under dir, rather than in the whole branch.
358
 
    """
359
 
    takes_args = ['dir?']
360
 
 
361
 
    def run(self, dir='.'):
362
 
        b = Branch(dir)
363
 
        old_inv = b.basis_tree().inventory
364
 
        new_inv = b.read_working_inventory()
365
 
 
366
 
        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
367
 
        renames.sort()
368
 
        for old_name, new_name in renames:
369
 
            print "%s => %s" % (old_name, new_name)        
370
 
 
371
 
 
372
 
class cmd_info(Command):
373
 
    """Show statistical information about a branch."""
374
 
    takes_args = ['branch?']
375
 
    
376
 
    def run(self, branch=None):
377
 
        import info
378
 
 
379
 
        from branch import find_branch
380
 
        b = find_branch(branch)
381
 
        info.show_info(b)
382
 
 
383
 
 
384
 
class cmd_remove(Command):
385
 
    """Make a file unversioned.
386
 
 
387
 
    This makes bzr stop tracking changes to a versioned file.  It does
388
 
    not delete the working copy.
389
 
    """
390
 
    takes_args = ['file+']
391
 
    takes_options = ['verbose']
392
 
    
393
 
    def run(self, file_list, verbose=False):
394
 
        b = Branch(file_list[0])
395
 
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
396
 
 
397
 
 
398
 
class cmd_file_id(Command):
399
 
    """Print file_id of a particular file or directory.
400
 
 
401
 
    The file_id is assigned when the file is first added and remains the
402
 
    same through all revisions where the file exists, even when it is
403
 
    moved or renamed.
404
 
    """
405
 
    hidden = True
406
 
    takes_args = ['filename']
407
 
    def run(self, filename):
408
 
        b = Branch(filename)
409
 
        i = b.inventory.path2id(b.relpath(filename))
410
 
        if i == None:
411
 
            bailout("%r is not a versioned file" % filename)
412
 
        else:
413
 
            print i
414
 
 
415
 
 
416
 
class cmd_file_path(Command):
417
 
    """Print path of file_ids to a file or directory.
418
 
 
419
 
    This prints one line for each directory down to the target,
420
 
    starting at the branch root."""
421
 
    hidden = True
422
 
    takes_args = ['filename']
423
 
    def run(self, filename):
424
 
        b = Branch(filename)
425
 
        inv = b.inventory
426
 
        fid = inv.path2id(b.relpath(filename))
427
 
        if fid == None:
428
 
            bailout("%r is not a versioned file" % filename)
429
 
        for fip in inv.get_idpath(fid):
430
 
            print fip
431
 
 
432
 
 
433
 
class cmd_revision_history(Command):
434
 
    """Display list of revision ids on this branch."""
435
 
    def run(self):
436
 
        for patchid in Branch('.').revision_history():
437
 
            print patchid
438
 
 
439
 
 
440
 
class cmd_directories(Command):
441
 
    """Display list of versioned directories in this branch."""
442
 
    def run(self):
443
 
        for name, ie in Branch('.').read_working_inventory().directories():
444
 
            if name == '':
445
 
                print '.'
446
 
            else:
447
 
                print name
448
 
 
449
 
 
450
 
class cmd_init(Command):
451
 
    """Make a directory into a versioned branch.
452
 
 
453
 
    Use this to create an empty branch, or before importing an
454
 
    existing project.
455
 
 
456
 
    Recipe for importing a tree of files:
457
 
        cd ~/project
458
 
        bzr init
459
 
        bzr add -v .
460
 
        bzr status
461
 
        bzr commit -m 'imported project'
462
 
    """
463
 
    def run(self):
464
 
        Branch('.', init=True)
465
 
 
466
 
 
467
 
class cmd_diff(Command):
468
 
    """Show differences in working tree.
469
 
    
470
 
    If files are listed, only the changes in those files are listed.
471
 
    Otherwise, all changes for the tree are listed.
472
 
 
473
 
    TODO: Given two revision arguments, show the difference between them.
474
 
 
475
 
    TODO: Allow diff across branches.
476
 
 
477
 
    TODO: Option to use external diff command; could be GNU diff, wdiff,
478
 
          or a graphical diff.
479
 
 
480
 
    TODO: Python difflib is not exactly the same as unidiff; should
481
 
          either fix it up or prefer to use an external diff.
482
 
 
483
 
    TODO: If a directory is given, diff everything under that.
484
 
 
485
 
    TODO: Selected-file diff is inefficient and doesn't show you
486
 
          deleted files.
487
 
 
488
 
    TODO: This probably handles non-Unix newlines poorly.
489
 
    """
490
 
    
491
 
    takes_args = ['file*']
492
 
    takes_options = ['revision']
493
 
    aliases = ['di']
494
 
 
495
 
    def run(self, revision=None, file_list=None):
496
 
        from bzrlib.diff import show_diff
497
 
    
498
 
        show_diff(Branch('.'), revision, specific_files=file_list)
499
 
 
500
 
 
501
 
        
502
 
 
503
 
 
504
 
class cmd_deleted(Command):
505
 
    """List files deleted in the working tree.
506
 
 
507
 
    TODO: Show files deleted since a previous revision, or between two revisions.
508
 
    """
509
 
    def run(self, show_ids=False):
510
 
        b = Branch('.')
511
 
        old = b.basis_tree()
512
 
        new = b.working_tree()
513
 
 
514
 
        ## TODO: Much more efficient way to do this: read in new
515
 
        ## directories with readdir, rather than stating each one.  Same
516
 
        ## level of effort but possibly much less IO.  (Or possibly not,
517
 
        ## if the directories are very large...)
518
 
 
519
 
        for path, ie in old.inventory.iter_entries():
520
 
            if not new.has_id(ie.file_id):
521
 
                if show_ids:
522
 
                    print '%-50s %s' % (path, ie.file_id)
523
 
                else:
524
 
                    print path
525
 
 
526
 
 
527
 
class cmd_modified(Command):
528
 
    """List files modified in working tree."""
529
 
    hidden = True
530
 
    def run(self):
531
 
        import statcache
532
 
        b = Branch('.')
 
136
    For each file there is a single line giving its file state and name.
 
137
    The name is that in the current revision unless it is deleted or
 
138
    missing, in which case the old name is shown.
 
139
 
 
140
    :todo: Don't show unchanged files unless ``--all`` is given?
 
141
    """
 
142
    Branch('.').show_status(show_all=all)
 
143
 
 
144
 
 
145
 
 
146
######################################################################
 
147
# examining history
 
148
def cmd_get_revision(revision_id):
 
149
    Branch('.').get_revision(revision_id).write_xml(sys.stdout)
 
150
 
 
151
 
 
152
def cmd_get_file_text(text_id):
 
153
    """Get contents of a file by hash."""
 
154
    sf = Branch('.').text_store[text_id]
 
155
    pumpfile(sf, sys.stdout)
 
156
 
 
157
 
 
158
 
 
159
######################################################################
 
160
# commands
 
161
    
 
162
 
 
163
def cmd_revno():
 
164
    """Show number of revisions on this branch"""
 
165
    print Branch('.').revno()
 
166
    
 
167
 
 
168
def cmd_add(file_list, verbose=False):
 
169
    """Add specified files.
 
170
    
 
171
    Fails if the files are already added.
 
172
    """
 
173
    Branch('.').add(file_list, verbose=verbose)
 
174
 
 
175
 
 
176
def cmd_inventory(revision=None):
 
177
    """Show inventory of the current working copy."""
 
178
    ## TODO: Also optionally show a previous inventory
 
179
    ## TODO: Format options
 
180
    b = Branch('.')
 
181
    if revision == None:
533
182
        inv = b.read_working_inventory()
534
 
        sc = statcache.update_cache(b, inv)
535
 
        basis = b.basis_tree()
536
 
        basis_inv = basis.inventory
537
 
        
538
 
        # We used to do this through iter_entries(), but that's slow
539
 
        # when most of the files are unmodified, as is usually the
540
 
        # case.  So instead we iterate by inventory entry, and only
541
 
        # calculate paths as necessary.
542
 
 
543
 
        for file_id in basis_inv:
544
 
            cacheentry = sc.get(file_id)
545
 
            if not cacheentry:                 # deleted
546
 
                continue
547
 
            ie = basis_inv[file_id]
548
 
            if cacheentry[statcache.SC_SHA1] != ie.text_sha1:
549
 
                path = inv.id2path(file_id)
550
 
                print path
551
 
 
552
 
 
553
 
 
554
 
class cmd_added(Command):
555
 
    """List files added in working tree."""
556
 
    hidden = True
557
 
    def run(self):
558
 
        b = Branch('.')
559
 
        wt = b.working_tree()
560
 
        basis_inv = b.basis_tree().inventory
561
 
        inv = wt.inventory
562
 
        for file_id in inv:
563
 
            if file_id in basis_inv:
564
 
                continue
565
 
            path = inv.id2path(file_id)
566
 
            if not os.access(b.abspath(path), os.F_OK):
567
 
                continue
568
 
            print path
569
 
                
570
 
        
571
 
 
572
 
class cmd_root(Command):
573
 
    """Show the tree root directory.
574
 
 
575
 
    The root is the nearest enclosing directory with a .bzr control
576
 
    directory."""
577
 
    takes_args = ['filename?']
578
 
    def run(self, filename=None):
579
 
        """Print the branch root."""
580
 
        from branch import find_branch
581
 
        b = find_branch(filename)
582
 
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
583
 
 
584
 
 
585
 
class cmd_log(Command):
 
183
    else:
 
184
        inv = b.get_revision_inventory(b.lookup_revision(revision))
 
185
        
 
186
    for path, entry in inv.iter_entries():
 
187
        print '%-50s %s' % (entry.file_id, path)
 
188
 
 
189
 
 
190
 
 
191
def cmd_info():
 
192
    b = Branch('.')
 
193
    print 'branch format:', b.controlfile('branch-format', 'r').readline().rstrip('\n')
 
194
 
 
195
    def plural(n, base='', pl=None):
 
196
        if n == 1:
 
197
            return base
 
198
        elif pl is not None:
 
199
            return pl
 
200
        else:
 
201
            return 's'
 
202
 
 
203
    count_version_dirs = 0
 
204
 
 
205
    count_status = {'A': 0, 'D': 0, 'M': 0, 'R': 0, '?': 0, 'I': 0, '.': 0}
 
206
    for st_tup in bzrlib.diff_trees(b.basis_tree(), b.working_tree()):
 
207
        fs = st_tup[0]
 
208
        count_status[fs] += 1
 
209
        if fs not in ['I', '?'] and st_tup[4] == 'directory':
 
210
            count_version_dirs += 1
 
211
 
 
212
    print
 
213
    print 'in the working tree:'
 
214
    for name, fs in (('unchanged', '.'),
 
215
                     ('modified', 'M'), ('added', 'A'), ('removed', 'D'),
 
216
                     ('renamed', 'R'), ('unknown', '?'), ('ignored', 'I'),
 
217
                     ):
 
218
        print '  %5d %s' % (count_status[fs], name)
 
219
    print '  %5d versioned subdirector%s' % (count_version_dirs,
 
220
                                             plural(count_version_dirs, 'y', 'ies'))
 
221
 
 
222
    print
 
223
    print 'branch history:'
 
224
    history = b.revision_history()
 
225
    revno = len(history)
 
226
    print '  %5d revision%s' % (revno, plural(revno))
 
227
    committers = Set()
 
228
    for rev in history:
 
229
        committers.add(b.get_revision(rev).committer)
 
230
    print '  %5d committer%s' % (len(committers), plural(len(committers)))
 
231
    if revno > 0:
 
232
        firstrev = b.get_revision(history[0])
 
233
        age = int((time.time() - firstrev.timestamp) / 3600 / 24)
 
234
        print '  %5d day%s old' % (age, plural(age))
 
235
        print '  first revision: %s' % format_date(firstrev.timestamp,
 
236
                                                 firstrev.timezone)
 
237
 
 
238
        lastrev = b.get_revision(history[-1])
 
239
        print '  latest revision: %s' % format_date(lastrev.timestamp,
 
240
                                                    lastrev.timezone)
 
241
        
 
242
    
 
243
 
 
244
 
 
245
def cmd_remove(file_list, verbose=False):
 
246
    Branch('.').remove(file_list, verbose=verbose)
 
247
 
 
248
 
 
249
 
 
250
def cmd_file_id(filename):
 
251
    i = Branch('.').read_working_inventory().path2id(filename)
 
252
    if i is None:
 
253
        bailout("%s is not a versioned file" % filename)
 
254
    else:
 
255
        print i
 
256
 
 
257
 
 
258
def cmd_find_filename(fileid):
 
259
    n = find_filename(fileid)
 
260
    if n is None:
 
261
        bailout("%s is not a live file id" % fileid)
 
262
    else:
 
263
        print n
 
264
 
 
265
 
 
266
def cmd_revision_history():
 
267
    for patchid in Branch('.').revision_history():
 
268
        print patchid
 
269
 
 
270
 
 
271
 
 
272
def cmd_init():
 
273
    # TODO: Check we're not already in a working directory?  At the
 
274
    # moment you'll get an ugly error.
 
275
    
 
276
    # TODO: What if we're in a subdirectory of a branch?  Would like
 
277
    # to allow that, but then the parent may need to understand that
 
278
    # the children have disappeared, or should they be versioned in
 
279
    # both?
 
280
 
 
281
    # TODO: Take an argument/option for branch name.
 
282
    Branch('.', init=True)
 
283
 
 
284
 
 
285
def cmd_diff(revision=None):
 
286
    """Show diff from basis to working copy.
 
287
 
 
288
    :todo: Take one or two revision arguments, look up those trees,
 
289
           and diff them.
 
290
 
 
291
    :todo: Allow diff across branches.
 
292
 
 
293
    :todo: Mangle filenames in diff to be more relevant.
 
294
 
 
295
    :todo: Shouldn't be in the cmd function.
 
296
    """
 
297
 
 
298
    b = Branch('.')
 
299
 
 
300
    if revision == None:
 
301
        old_tree = b.basis_tree()
 
302
    else:
 
303
        old_tree = b.revision_tree(b.lookup_revision(revision))
 
304
        
 
305
    new_tree = b.working_tree()
 
306
    old_inv = old_tree.inventory
 
307
    new_inv = new_tree.inventory
 
308
 
 
309
    # TODO: Options to control putting on a prefix or suffix, perhaps as a format string
 
310
    old_label = ''
 
311
    new_label = ''
 
312
 
 
313
    DEVNULL = '/dev/null'
 
314
    # Windows users, don't panic about this filename -- it is a
 
315
    # special signal to GNU patch that the file should be created or
 
316
    # deleted respectively.
 
317
 
 
318
    # TODO: Generation of pseudo-diffs for added/deleted files could
 
319
    # be usefully made into a much faster special case.
 
320
 
 
321
    # TODO: Better to return them in sorted order I think.
 
322
    
 
323
    for file_state, fid, old_name, new_name, kind in bzrlib.diff_trees(old_tree, new_tree):
 
324
        d = None
 
325
 
 
326
        # Don't show this by default; maybe do it if an option is passed
 
327
        # idlabel = '      {%s}' % fid
 
328
        idlabel = ''
 
329
 
 
330
        # FIXME: Something about the diff format makes patch unhappy
 
331
        # with newly-added files.
 
332
 
 
333
        def diffit(*a, **kw):
 
334
            sys.stdout.writelines(difflib.unified_diff(*a, **kw))
 
335
            print
 
336
        
 
337
        if file_state in ['.', '?', 'I']:
 
338
            continue
 
339
        elif file_state == 'A':
 
340
            print '*** added %s %r' % (kind, new_name)
 
341
            if kind == 'file':
 
342
                diffit([],
 
343
                       new_tree.get_file(fid).readlines(),
 
344
                       fromfile=DEVNULL,
 
345
                       tofile=new_label + new_name + idlabel)
 
346
        elif file_state == 'D':
 
347
            assert isinstance(old_name, types.StringTypes)
 
348
            print '*** deleted %s %r' % (kind, old_name)
 
349
            if kind == 'file':
 
350
                diffit(old_tree.get_file(fid).readlines(), [],
 
351
                       fromfile=old_label + old_name + idlabel,
 
352
                       tofile=DEVNULL)
 
353
        elif file_state in ['M', 'R']:
 
354
            if file_state == 'M':
 
355
                assert kind == 'file'
 
356
                assert old_name == new_name
 
357
                print '*** modified %s %r' % (kind, new_name)
 
358
            elif file_state == 'R':
 
359
                print '*** renamed %s %r => %r' % (kind, old_name, new_name)
 
360
 
 
361
            if kind == 'file':
 
362
                diffit(old_tree.get_file(fid).readlines(),
 
363
                       new_tree.get_file(fid).readlines(),
 
364
                       fromfile=old_label + old_name + idlabel,
 
365
                       tofile=new_label + new_name)
 
366
        else:
 
367
            bailout("can't represent state %s {%s}" % (file_state, fid))
 
368
 
 
369
 
 
370
 
 
371
def cmd_log(timezone='original'):
586
372
    """Show log of this branch.
587
373
 
588
 
    TODO: Option to limit range.
589
 
 
590
 
    TODO: Perhaps show most-recent first with an option for last.
 
374
    :todo: Options for utc; to show ids; to limit range; etc.
591
375
    """
592
 
    takes_args = ['filename?']
593
 
    takes_options = ['timezone', 'verbose', 'show-ids']
594
 
    def run(self, filename=None, timezone='original', verbose=False, show_ids=False):
595
 
        from branch import find_branch
596
 
        b = find_branch((filename or '.'), lock_mode='r')
597
 
        if filename:
598
 
            filename = b.relpath(filename)
599
 
        bzrlib.show_log(b, filename,
600
 
                        show_timezone=timezone,
601
 
                        verbose=verbose,
602
 
                        show_ids=show_ids)
603
 
 
604
 
 
605
 
 
606
 
class cmd_touching_revisions(Command):
607
 
    """Return revision-ids which affected a particular file."""
608
 
    hidden = True
609
 
    takes_args = ["filename"]
610
 
    def run(self, filename):
611
 
        b = Branch(filename, lock_mode='r')
612
 
        inv = b.read_working_inventory()
613
 
        file_id = inv.path2id(b.relpath(filename))
614
 
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
615
 
            print "%6d %s" % (revno, what)
616
 
 
617
 
 
618
 
class cmd_ls(Command):
 
376
    Branch('.').write_log(show_timezone=timezone)
 
377
 
 
378
 
 
379
def cmd_ls(revision=None, verbose=False):
619
380
    """List files in a tree.
620
381
 
621
 
    TODO: Take a revision or remote path and list that tree instead.
 
382
    :todo: Take a revision or remote path and list that tree instead.
622
383
    """
623
 
    hidden = True
624
 
    def run(self, revision=None, verbose=False):
625
 
        b = Branch('.')
626
 
        if revision == None:
627
 
            tree = b.working_tree()
 
384
    b = Branch('.')
 
385
    if revision == None:
 
386
        tree = b.working_tree()
 
387
    else:
 
388
        tree = b.revision_tree(b.lookup_revision(revision))
 
389
        
 
390
    for fp, fc, kind, fid in tree.list_files():
 
391
        if verbose:
 
392
            if kind == 'directory':
 
393
                kindch = '/'
 
394
            elif kind == 'file':
 
395
                kindch = ''
 
396
            else:
 
397
                kindch = '???'
 
398
                
 
399
            print '%-8s %s%s' % (fc, fp, kindch)
628
400
        else:
629
 
            tree = b.revision_tree(b.lookup_revision(revision))
630
 
 
631
 
        for fp, fc, kind, fid in tree.list_files():
632
 
            if verbose:
633
 
                if kind == 'directory':
634
 
                    kindch = '/'
635
 
                elif kind == 'file':
636
 
                    kindch = ''
637
 
                else:
638
 
                    kindch = '???'
639
 
 
640
 
                print '%-8s %s%s' % (fc, fp, kindch)
641
 
            else:
642
 
                print fp
643
 
 
644
 
 
645
 
 
646
 
class cmd_unknowns(Command):
 
401
            print fp
 
402
    
 
403
    
 
404
 
 
405
def cmd_unknowns():
647
406
    """List unknown files"""
648
 
    def run(self):
649
 
        for f in Branch('.').unknowns():
650
 
            print quotefn(f)
651
 
 
652
 
 
653
 
 
654
 
class cmd_ignore(Command):
655
 
    """Ignore a command or pattern
656
 
 
657
 
    To remove patterns from the ignore list, edit the .bzrignore file.
658
 
 
659
 
    If the pattern contains a slash, it is compared to the whole path
660
 
    from the branch root.  Otherwise, it is comapred to only the last
661
 
    component of the path.
662
 
 
663
 
    Ignore patterns are case-insensitive on case-insensitive systems.
664
 
 
665
 
    Note: wildcards must be quoted from the shell on Unix.
666
 
 
667
 
    examples:
668
 
        bzr ignore ./Makefile
669
 
        bzr ignore '*.class'
670
 
    """
671
 
    takes_args = ['name_pattern']
672
 
    
673
 
    def run(self, name_pattern):
674
 
        from bzrlib.atomicfile import AtomicFile
675
 
        import codecs
676
 
 
677
 
        b = Branch('.')
678
 
        ifn = b.abspath('.bzrignore')
679
 
 
680
 
        if os.path.exists(ifn):
681
 
            f = open(ifn, 'rt')
682
 
            try:
683
 
                igns = f.read().decode('utf-8')
684
 
            finally:
685
 
                f.close()
686
 
        else:
687
 
            igns = ''
688
 
 
689
 
        if igns and igns[-1] != '\n':
690
 
            igns += '\n'
691
 
        igns += name_pattern + '\n'
692
 
 
693
 
        try:
694
 
            f = AtomicFile(ifn, 'wt')
695
 
            f.write(igns.encode('utf-8'))
696
 
            f.commit()
697
 
        finally:
698
 
            f.close()
699
 
 
700
 
        inv = b.working_tree().inventory
701
 
        if inv.path2id('.bzrignore'):
702
 
            mutter('.bzrignore is already versioned')
703
 
        else:
704
 
            mutter('need to make new .bzrignore file versioned')
705
 
            b.add(['.bzrignore'])
706
 
 
707
 
 
708
 
 
709
 
class cmd_ignored(Command):
710
 
    """List ignored files and the patterns that matched them.
711
 
 
712
 
    See also: bzr ignore"""
713
 
    def run(self):
714
 
        tree = Branch('.').working_tree()
715
 
        for path, file_class, kind, file_id in tree.list_files():
716
 
            if file_class != 'I':
717
 
                continue
718
 
            ## XXX: Slightly inefficient since this was already calculated
719
 
            pat = tree.is_ignored(path)
720
 
            print '%-50s %s' % (path, pat)
721
 
 
722
 
 
723
 
class cmd_lookup_revision(Command):
724
 
    """Lookup the revision-id from a revision-number
725
 
 
726
 
    example:
727
 
        bzr lookup-revision 33
728
 
    """
729
 
    hidden = True
730
 
    takes_args = ['revno']
731
 
    
732
 
    def run(self, revno):
733
 
        try:
734
 
            revno = int(revno)
735
 
        except ValueError:
736
 
            raise BzrCommandError("not a valid revision-number: %r" % revno)
737
 
 
738
 
        print Branch('.').lookup_revision(revno)
739
 
 
740
 
 
741
 
class cmd_export(Command):
742
 
    """Export past revision to destination directory.
743
 
 
744
 
    If no revision is specified this exports the last committed revision."""
745
 
    takes_args = ['dest']
746
 
    takes_options = ['revision']
747
 
    def run(self, dest, revision=None):
748
 
        b = Branch('.')
749
 
        if revision == None:
750
 
            rh = b.revision_history()[-1]
751
 
        else:
752
 
            rh = b.lookup_revision(int(revision))
753
 
        t = b.revision_tree(rh)
754
 
        t.export(dest)
755
 
 
756
 
 
757
 
class cmd_cat(Command):
758
 
    """Write a file's text from a previous revision."""
759
 
 
760
 
    takes_options = ['revision']
761
 
    takes_args = ['filename']
762
 
 
763
 
    def run(self, filename, revision=None):
764
 
        if revision == None:
765
 
            raise BzrCommandError("bzr cat requires a revision number")
766
 
        b = Branch('.')
767
 
        b.print_file(b.relpath(filename), int(revision))
768
 
 
769
 
 
770
 
class cmd_local_time_offset(Command):
771
 
    """Show the offset in seconds from GMT to local time."""
772
 
    hidden = True    
773
 
    def run(self):
774
 
        print bzrlib.osutils.local_time_offset()
775
 
 
776
 
 
777
 
 
778
 
class cmd_commit(Command):
779
 
    """Commit changes into a new revision.
780
 
 
781
 
    If selected files are specified, only changes to those files are
782
 
    committed.  If a directory is specified then its contents are also
783
 
    committed.
784
 
 
785
 
    A selected-file commit may fail in some cases where the committed
786
 
    tree would be invalid, such as trying to commit a file in a
787
 
    newly-added directory that is not itself committed.
788
 
 
789
 
    TODO: Run hooks on tree to-be-committed, and after commit.
790
 
 
791
 
    TODO: Strict commit that fails if there are unknown or deleted files.
792
 
    """
793
 
    takes_args = ['selected*']
794
 
    takes_options = ['message', 'file', 'verbose']
795
 
    aliases = ['ci', 'checkin']
796
 
 
797
 
    def run(self, message=None, file=None, verbose=True, selected_list=None):
798
 
        from bzrlib.commit import commit
799
 
 
800
 
        ## Warning: shadows builtin file()
801
 
        if not message and not file:
802
 
            raise BzrCommandError("please specify a commit message",
803
 
                                  ["use either --message or --file"])
804
 
        elif message and file:
805
 
            raise BzrCommandError("please specify either --message or --file")
 
407
    for f in Branch('.').unknowns():
 
408
        print quotefn(f)
 
409
 
 
410
 
 
411
def cmd_lookup_revision(revno):
 
412
    try:
 
413
        revno = int(revno)
 
414
    except ValueError:
 
415
        bailout("usage: lookup-revision REVNO",
 
416
                ["REVNO is a non-negative revision number for this branch"])
 
417
 
 
418
    print Branch('.').lookup_revision(revno) or NONE_STRING
 
419
 
 
420
 
 
421
 
 
422
def cmd_export(revno, dest):
 
423
    """Export past revision to destination directory."""
 
424
    b = Branch('.')
 
425
    rh = b.lookup_revision(int(revno))
 
426
    t = b.revision_tree(rh)
 
427
    t.export(dest)
 
428
 
 
429
 
 
430
 
 
431
######################################################################
 
432
# internal/test commands
 
433
 
 
434
 
 
435
def cmd_uuid():
 
436
    """Print a newly-generated UUID."""
 
437
    print uuid()
 
438
 
 
439
 
 
440
 
 
441
def cmd_local_time_offset():
 
442
    print bzrlib.osutils.local_time_offset()
 
443
 
 
444
 
 
445
 
 
446
def cmd_commit(message, verbose=False):
 
447
    Branch('.').commit(message, verbose=verbose)
 
448
 
 
449
 
 
450
def cmd_check():
 
451
    """Check consistency of the branch."""
 
452
    check()
 
453
 
 
454
 
 
455
def cmd_is(pred, *rest):
 
456
    """Test whether PREDICATE is true."""
 
457
    try:
 
458
        cmd_handler = globals()['assert_' + pred.replace('-', '_')]
 
459
    except KeyError:
 
460
        bailout("unknown predicate: %s" % quotefn(pred))
806
461
        
807
 
        if file:
808
 
            import codecs
809
 
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
810
 
 
811
 
        b = Branch('.')
812
 
        commit(b, message, verbose=verbose, specific_files=selected_list)
813
 
 
814
 
 
815
 
class cmd_check(Command):
816
 
    """Validate consistency of branch history.
817
 
 
818
 
    This command checks various invariants about the branch storage to
819
 
    detect data corruption or bzr bugs.
820
 
    """
821
 
    takes_args = ['dir?']
822
 
    def run(self, dir='.'):
823
 
        import bzrlib.check
824
 
        bzrlib.check.check(Branch(dir))
825
 
 
826
 
 
827
 
 
828
 
class cmd_whoami(Command):
829
 
    """Show bzr user id."""
830
 
    takes_options = ['email']
 
462
    try:
 
463
        cmd_handler(*rest)
 
464
    except BzrCheckError:
 
465
        # by default we don't print the message so that this can
 
466
        # be used from shell scripts without producing noise
 
467
        sys.exit(1)
 
468
 
 
469
 
 
470
def cmd_username():
 
471
    print bzrlib.osutils.username()
 
472
 
 
473
 
 
474
def cmd_user_email():
 
475
    print bzrlib.osutils.user_email()
 
476
 
 
477
 
 
478
def cmd_gen_revision_id():
 
479
    import time
 
480
    print bzrlib.branch._gen_revision_id(time.time())
 
481
 
 
482
 
 
483
def cmd_doctest():
 
484
    """Run internal doctest suite"""
 
485
    ## -v, if present, is seen by doctest; the argument is just here
 
486
    ## so our parser doesn't complain
 
487
 
 
488
    ## TODO: --verbose option
831
489
    
832
 
    def run(self, email=False):
833
 
        if email:
834
 
            print bzrlib.osutils.user_email()
835
 
        else:
836
 
            print bzrlib.osutils.username()
837
 
 
838
 
 
839
 
class cmd_selftest(Command):
840
 
    """Run internal test suite"""
841
 
    hidden = True
842
 
    def run(self):
843
 
        failures, tests = 0, 0
844
 
 
845
 
        import doctest, bzrlib.store, bzrlib.tests
846
 
        bzrlib.trace.verbose = False
847
 
 
848
 
        for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
849
 
            bzrlib.tree, bzrlib.commands, bzrlib.add:
850
 
            mf, mt = doctest.testmod(m)
851
 
            failures += mf
852
 
            tests += mt
853
 
            print '%-40s %3d tests' % (m.__name__, mt),
854
 
            if mf:
855
 
                print '%3d FAILED!' % mf
856
 
            else:
857
 
                print
858
 
 
859
 
        print '%-40s %3d tests' % ('total', tests),
860
 
        if failures:
861
 
            print '%3d FAILED!' % failures
862
 
            return 1
863
 
        else:
864
 
            print
865
 
            return 0
866
 
 
867
 
 
868
 
 
869
 
class cmd_version(Command):
870
 
    """Show version of bzr"""
871
 
    def run(self):
872
 
        show_version()
873
 
 
874
 
def show_version():
875
 
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
876
 
    print bzrlib.__copyright__
 
490
    import bzr, doctest, bzrlib.store
 
491
    bzrlib.trace.verbose = False
 
492
    doctest.testmod(bzr)
 
493
    doctest.testmod(bzrlib.store)
 
494
    doctest.testmod(bzrlib.inventory)
 
495
    doctest.testmod(bzrlib.branch)
 
496
    doctest.testmod(bzrlib.osutils)
 
497
    doctest.testmod(bzrlib.tree)
 
498
 
 
499
    # more strenuous tests;
 
500
    import bzrlib.tests
 
501
    doctest.testmod(bzrlib.tests)
 
502
 
 
503
 
 
504
######################################################################
 
505
# help
 
506
 
 
507
 
 
508
def cmd_help():
 
509
    # TODO: Specific help for particular commands
 
510
    print __doc__
 
511
 
 
512
 
 
513
def cmd_version():
 
514
    print "bzr (bazaar-ng) %s" % __version__
 
515
    print __copyright__
877
516
    print "http://bazaar-ng.org/"
878
517
    print
879
 
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
880
 
    print "you may use, modify and redistribute it under the terms of the GNU"
881
 
    print "General Public License version 2 or later."
882
 
 
883
 
 
884
 
class cmd_rocks(Command):
 
518
    print \
 
519
"""bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and
 
520
you may use, modify and redistribute it under the terms of the GNU 
 
521
General Public License version 2 or later."""
 
522
 
 
523
 
 
524
def cmd_rocks():
885
525
    """Statement of optimism."""
886
 
    hidden = True
887
 
    def run(self):
888
 
        print "it sure does!"
889
 
 
890
 
def parse_spec(spec):
891
 
    if '/@' in spec:
892
 
        parsed = spec.split('/@')
893
 
        assert len(parsed) == 2
894
 
        if parsed[1] == "":
895
 
            parsed[1] = -1
896
 
        else:
897
 
            parsed[1] = int(parsed[1])
898
 
            assert parsed[1] >=0
899
 
    else:
900
 
        parsed = [spec, None]
901
 
    return parsed
902
 
 
903
 
class cmd_merge(Command):
904
 
    """Perform a three-way merge of trees."""
905
 
    takes_args = ['other_spec', 'base_spec']
906
 
 
907
 
    def run(self, other_spec, base_spec):
908
 
        merge.merge(parse_spec(other_spec), parse_spec(base_spec))
909
 
 
910
 
class cmd_assert_fail(Command):
911
 
    """Test reporting of assertion failures"""
912
 
    hidden = True
913
 
    def run(self):
914
 
        assert False, "always fails"
915
 
 
916
 
 
917
 
class cmd_help(Command):
918
 
    """Show help on a command or other topic.
919
 
 
920
 
    For a list of all available commands, say 'bzr help commands'."""
921
 
    takes_args = ['topic?']
922
 
    aliases = ['?']
923
 
    
924
 
    def run(self, topic=None):
925
 
        import help
926
 
        help.help(topic)
927
 
 
928
 
 
929
 
class cmd_update_stat_cache(Command):
930
 
    """Update stat-cache mapping inodes to SHA-1 hashes.
931
 
 
932
 
    For testing only."""
933
 
    hidden = True
934
 
    def run(self):
935
 
        import statcache
936
 
        b = Branch('.')
937
 
        statcache.update_cache(b.base, b.read_working_inventory())
 
526
    print "it sure does!"
 
527
 
938
528
 
939
529
 
940
530
######################################################################
947
537
OPTIONS = {
948
538
    'all':                    None,
949
539
    'help':                   None,
950
 
    'file':                   unicode,
951
540
    'message':                unicode,
952
 
    'profile':                None,
953
541
    'revision':               int,
954
542
    'show-ids':               None,
955
543
    'timezone':               str,
956
544
    'verbose':                None,
957
545
    'version':                None,
958
 
    'email':                  None,
959
546
    }
960
547
 
961
548
SHORT_OPTIONS = {
962
549
    'm':                      'message',
963
 
    'F':                      'file', 
964
550
    'r':                      'revision',
965
551
    'v':                      'verbose',
966
552
}
967
553
 
 
554
# List of options that apply to particular commands; commands not
 
555
# listed take none.
 
556
cmd_options = {
 
557
    'add':                    ['verbose'],
 
558
    'commit':                 ['message', 'verbose'],
 
559
    'diff':                   ['revision'],
 
560
    'inventory':              ['revision'],
 
561
    'log':                    ['show-ids', 'timezone'],
 
562
    'ls':                     ['revision', 'verbose'],
 
563
    'remove':                 ['verbose'],
 
564
    'status':                 ['all'],
 
565
    }
 
566
 
 
567
 
 
568
cmd_args = {
 
569
    'init':                   [],
 
570
    'add':                    ['file+'],
 
571
    'commit':                 [],
 
572
    'diff':                   [],
 
573
    'file-id':                ['filename'],
 
574
    'get-file-text':          ['text_id'],
 
575
    'get-inventory':          ['inventory_id'],
 
576
    'get-revision':           ['revision_id'],
 
577
    'get-revision-inventory': ['revision_id'],
 
578
    'log':                    [],
 
579
    'lookup-revision':        ['revno'],
 
580
    'export':                 ['revno', 'dest'],
 
581
    'remove':                 ['file+'],
 
582
    'status':                 [],
 
583
    }
 
584
 
968
585
 
969
586
def parse_args(argv):
970
587
    """Parse command line.
991
608
    while argv:
992
609
        a = argv.pop(0)
993
610
        if a[0] == '-':
994
 
            # option names must not be unicode
995
 
            a = str(a)
996
611
            optarg = None
997
612
            if a[1] == '-':
998
613
                mutter("  got option %r" % a)
1020
635
                    else:
1021
636
                        optarg = argv.pop(0)
1022
637
                opts[optname] = optargfn(optarg)
 
638
                mutter("    option argument %r" % opts[optname])
1023
639
            else:
1024
640
                if optarg != None:
1025
641
                    bailout('option %r takes no argument' % optname)
1031
647
 
1032
648
 
1033
649
 
 
650
def _match_args(cmd, args):
 
651
    """Check non-option arguments match required pattern.
1034
652
 
1035
 
def _match_argform(cmd, takes_args, args):
 
653
    >>> _match_args('status', ['asdasdsadasd'])
 
654
    Traceback (most recent call last):
 
655
    ...
 
656
    BzrError: ("extra arguments to command status: ['asdasdsadasd']", [])
 
657
    >>> _match_args('add', ['asdasdsadasd'])
 
658
    {'file_list': ['asdasdsadasd']}
 
659
    >>> _match_args('add', 'abc def gj'.split())
 
660
    {'file_list': ['abc', 'def', 'gj']}
 
661
    """
 
662
    # match argument pattern
 
663
    argform = cmd_args.get(cmd, [])
1036
664
    argdict = {}
 
665
    # TODO: Need a way to express 'cp SRC... DEST', where it matches
 
666
    # all but one.
1037
667
 
1038
 
    # step through args and takes_args, allowing appropriate 0-many matches
1039
 
    for ap in takes_args:
 
668
    for ap in argform:
1040
669
        argname = ap[:-1]
1041
670
        if ap[-1] == '?':
1042
 
            if args:
1043
 
                argdict[argname] = args.pop(0)
1044
 
        elif ap[-1] == '*': # all remaining arguments
1045
 
            if args:
1046
 
                argdict[argname + '_list'] = args[:]
1047
 
                args = []
1048
 
            else:
1049
 
                argdict[argname + '_list'] = None
 
671
            assert 0
 
672
        elif ap[-1] == '*':
 
673
            assert 0
1050
674
        elif ap[-1] == '+':
1051
675
            if not args:
1052
 
                raise BzrCommandError("command %r needs one or more %s"
 
676
                bailout("command %r needs one or more %s"
1053
677
                        % (cmd, argname.upper()))
1054
678
            else:
1055
679
                argdict[argname + '_list'] = args[:]
1056
680
                args = []
1057
 
        elif ap[-1] == '$': # all but one
1058
 
            if len(args) < 2:
1059
 
                raise BzrCommandError("command %r needs one or more %s"
1060
 
                        % (cmd, argname.upper()))
1061
 
            argdict[argname + '_list'] = args[:-1]
1062
 
            args[:-1] = []                
1063
681
        else:
1064
682
            # just a plain arg
1065
683
            argname = ap
1066
684
            if not args:
1067
 
                raise BzrCommandError("command %r requires argument %s"
 
685
                bailout("command %r requires argument %s"
1068
686
                        % (cmd, argname.upper()))
1069
687
            else:
1070
688
                argdict[argname] = args.pop(0)
1071
689
            
1072
690
    if args:
1073
 
        raise BzrCommandError("extra argument to command %s: %s"
1074
 
                              % (cmd, args[0]))
 
691
        bailout("extra arguments to command %s: %r"
 
692
                % (cmd, args))
1075
693
 
1076
694
    return argdict
1077
695
 
1081
699
    """Execute a command.
1082
700
 
1083
701
    This is similar to main(), but without all the trappings for
1084
 
    logging and error handling.  
 
702
    logging and error handling.
1085
703
    """
1086
 
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
1087
 
    
1088
704
    try:
1089
705
        args, opts = parse_args(argv[1:])
1090
706
        if 'help' in opts:
1091
 
            import help
1092
 
            if args:
1093
 
                help.help(args[0])
1094
 
            else:
1095
 
                help.help()
 
707
            # TODO: pass down other arguments in case they asked for
 
708
            # help on a command name?
 
709
            cmd_help()
1096
710
            return 0
1097
711
        elif 'version' in opts:
1098
 
            show_version()
 
712
            cmd_version()
1099
713
            return 0
1100
 
        cmd = str(args.pop(0))
 
714
        cmd = args.pop(0)
1101
715
    except IndexError:
1102
 
        import help
1103
 
        help.help()
 
716
        log_error('usage: bzr COMMAND\n')
 
717
        log_error('  try "bzr help"\n')
1104
718
        return 1
1105
 
          
1106
 
 
1107
 
    canonical_cmd, cmd_class = get_cmd_class(cmd)
1108
 
 
1109
 
    # global option
1110
 
    if 'profile' in opts:
1111
 
        profile = True
1112
 
        del opts['profile']
1113
 
    else:
1114
 
        profile = False
 
719
            
 
720
    try:
 
721
        cmd_handler = globals()['cmd_' + cmd.replace('-', '_')]
 
722
    except KeyError:
 
723
        bailout("unknown command " + `cmd`)
 
724
 
 
725
    # TODO: special --profile option to turn on the Python profiler
1115
726
 
1116
727
    # check options are reasonable
1117
 
    allowed = cmd_class.takes_options
 
728
    allowed = cmd_options.get(cmd, [])
1118
729
    for oname in opts:
1119
730
        if oname not in allowed:
1120
 
            raise BzrCommandError("option '--%s' is not allowed for command %r"
1121
 
                                  % (oname, cmd))
1122
 
 
1123
 
    # mix arguments and options into one dictionary
1124
 
    cmdargs = _match_argform(cmd, cmd_class.takes_args, args)
1125
 
    cmdopts = {}
1126
 
    for k, v in opts.items():
1127
 
        cmdopts[k.replace('-', '_')] = v
1128
 
 
1129
 
    if profile:
1130
 
        import hotshot, tempfile
1131
 
        pffileno, pfname = tempfile.mkstemp()
1132
 
        try:
1133
 
            prof = hotshot.Profile(pfname)
1134
 
            ret = prof.runcall(cmd_class, cmdopts, cmdargs) or 0
1135
 
            prof.close()
1136
 
 
1137
 
            import hotshot.stats
1138
 
            stats = hotshot.stats.load(pfname)
1139
 
            #stats.strip_dirs()
1140
 
            stats.sort_stats('time')
1141
 
            ## XXX: Might like to write to stderr or the trace file instead but
1142
 
            ## print_stats seems hardcoded to stdout
1143
 
            stats.print_stats(20)
1144
 
            
1145
 
            return ret.status
1146
 
 
1147
 
        finally:
1148
 
            os.close(pffileno)
1149
 
            os.remove(pfname)
1150
 
    else:
1151
 
        return cmd_class(cmdopts, cmdargs).status 
1152
 
 
1153
 
 
1154
 
def _report_exception(summary, quiet=False):
1155
 
    import traceback
1156
 
    log_error('bzr: ' + summary)
1157
 
    bzrlib.trace.log_exception()
1158
 
 
1159
 
    if not quiet:
1160
 
        tb = sys.exc_info()[2]
1161
 
        exinfo = traceback.extract_tb(tb)
1162
 
        if exinfo:
1163
 
            sys.stderr.write('  at %s:%d in %s()\n' % exinfo[-1][:3])
1164
 
        sys.stderr.write('  see ~/.bzr.log for debug information\n')
 
731
            bailout("option %r is not allowed for command %r"
 
732
                    % (oname, cmd))
 
733
 
 
734
    cmdargs = _match_args(cmd, args)
 
735
    cmdargs.update(opts)
 
736
 
 
737
    ret = cmd_handler(**cmdargs) or 0
1165
738
 
1166
739
 
1167
740
 
1168
741
def main(argv):
1169
 
    import errno
1170
 
    
1171
 
    bzrlib.open_tracefile(argv)
 
742
    ## TODO: Handle command-line options; probably know what options are valid for
 
743
    ## each command
 
744
 
 
745
    ## TODO: If the arguments are wrong, give a usage message rather
 
746
    ## than just a backtrace.
1172
747
 
1173
748
    try:
1174
 
        try:
1175
 
            try:
1176
 
                return run_bzr(argv)
1177
 
            finally:
1178
 
                # do this here inside the exception wrappers to catch EPIPE
1179
 
                sys.stdout.flush()
1180
 
        except BzrError, e:
1181
 
            quiet = isinstance(e, (BzrCommandError))
1182
 
            _report_exception('error: ' + e.args[0], quiet=quiet)
1183
 
            if len(e.args) > 1:
1184
 
                for h in e.args[1]:
1185
 
                    # some explanation or hints
1186
 
                    log_error('  ' + h)
1187
 
            return 1
1188
 
        except AssertionError, e:
1189
 
            msg = 'assertion failed'
1190
 
            if str(e):
1191
 
                msg += ': ' + str(e)
1192
 
            _report_exception(msg)
1193
 
            return 2
1194
 
        except KeyboardInterrupt, e:
1195
 
            _report_exception('interrupted', quiet=True)
1196
 
            return 2
1197
 
        except Exception, e:
1198
 
            quiet = False
1199
 
            if (isinstance(e, IOError) 
1200
 
                and hasattr(e, 'errno')
1201
 
                and e.errno == errno.EPIPE):
1202
 
                quiet = True
1203
 
                msg = 'broken pipe'
1204
 
            else:
1205
 
                msg = str(e).rstrip('\n')
1206
 
            _report_exception(msg, quiet)
1207
 
            return 2
1208
 
    finally:
1209
 
        bzrlib.trace.close_trace()
 
749
        # TODO: Lift into separate function in trace.py
 
750
        # TODO: Also show contents of /etc/lsb-release, if it can be parsed.
 
751
        #       Perhaps that should eventually go into the platform library?
 
752
        # TODO: If the file doesn't exist, add a note describing it.
 
753
        t = bzrlib.trace._tracefile
 
754
        t.write('-' * 60 + '\n')
 
755
        t.write('bzr invoked at %s\n' % format_date(time.time()))
 
756
        t.write('  by %s on %s\n' % (bzrlib.osutils.username(), socket.getfqdn()))
 
757
        t.write('  arguments: %r\n' % argv)
 
758
 
 
759
        starttime = os.times()[4]
 
760
 
 
761
        import platform
 
762
        t.write('  platform: %s\n' % platform.platform())
 
763
        t.write('  python: %s\n' % platform.python_version())
 
764
 
 
765
        ret = run_bzr(argv)
 
766
        
 
767
        times = os.times()
 
768
        mutter("finished, %.3fu/%.3fs cpu, %.3fu/%.3fs cum"
 
769
               % times[:4])
 
770
        mutter("    %.3f elapsed" % (times[4] - starttime))
 
771
 
 
772
        return ret
 
773
    except BzrError, e:
 
774
        log_error('bzr: error: ' + e.args[0] + '\n')
 
775
        if len(e.args) > 1:
 
776
            for h in e.args[1]:
 
777
                log_error('  ' + h + '\n')
 
778
        return 1
 
779
    except Exception, e:
 
780
        log_error('bzr: exception: %s\n' % e)
 
781
        log_error('    see .bzr.log for details\n')
 
782
        traceback.print_exc(None, bzrlib.trace._tracefile)
 
783
        traceback.print_exc(None, sys.stderr)
 
784
        return 1
 
785
 
 
786
    # TODO: Maybe nicer handling of IOError?
 
787
 
1210
788
 
1211
789
 
1212
790
if __name__ == '__main__':
1213
791
    sys.exit(main(sys.argv))
 
792
    ##import profile
 
793
    ##profile.run('main(sys.argv)')
 
794