~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

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

Show diffs side-by-side

added added

removed removed

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