~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: mbp at sourcefrog
  • Date: 2005-03-29 01:16:16 UTC
  • Revision ID: mbp@sourcefrog.net-20050329011616-04e45f8670fe5141
Store.add defaults to adding gzipped files

Show diffs side-by-side

added added

removed removed

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