/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-05-31 03:03:54 UTC
  • Revision ID: mbp@sourcefrog.net-20050531030354-561dbe9ec2862d46
doc

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 by Canonical Ltd
2
 
#
 
1
# Copyright (C) 2004, 2005 by Canonical Ltd
 
2
 
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
#
 
12
 
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
# TODO: probably should say which arguments are candidates for glob
19
 
# expansion on windows and do that at the command level.
20
 
 
21
 
# TODO: Define arguments by objects, rather than just using names.
22
 
# Those objects can specify the expected type of the argument, which
23
 
# would help with validation and shell completion.  They could also provide
24
 
# help/explanation for that argument in a structured way.
25
 
 
26
 
# TODO: Specific "examples" property on commands for consistent formatting.
27
 
 
28
 
# TODO: "--profile=cum", to change sort order.  Is there any value in leaving
29
 
# the profile output behind so it can be interactively examined?
30
 
 
31
 
import sys
32
 
import os
33
 
from warnings import warn
34
 
import errno
 
18
 
 
19
import sys, os
35
20
 
36
21
import bzrlib
37
 
from bzrlib.errors import (BzrError,
38
 
                           BzrCheckError,
39
 
                           BzrCommandError,
40
 
                           BzrOptionError,
41
 
                           NotBranchError)
42
 
from bzrlib.option import Option
43
 
from bzrlib.revisionspec import RevisionSpec
44
 
from bzrlib.symbol_versioning import *
45
 
import bzrlib.trace
46
 
from bzrlib.trace import mutter, note, log_error, warning, be_quiet
47
 
 
48
 
plugin_cmds = {}
49
 
 
50
 
 
51
 
def register_command(cmd, decorate=False):
52
 
    """Utility function to help register a command
53
 
 
54
 
    :param cmd: Command subclass to register
55
 
    :param decorate: If true, allow overriding an existing command
56
 
        of the same name; the old command is returned by this function.
57
 
        Otherwise it is an error to try to override an existing command.
58
 
    """
59
 
    global plugin_cmds
60
 
    k = cmd.__name__
61
 
    if k.startswith("cmd_"):
62
 
        k_unsquished = _unsquish_command_name(k)
63
 
    else:
64
 
        k_unsquished = k
65
 
    if not plugin_cmds.has_key(k_unsquished):
66
 
        plugin_cmds[k_unsquished] = cmd
67
 
        mutter('registered plugin command %s', k_unsquished)
68
 
        if decorate and k_unsquished in builtin_command_names():
69
 
            return _builtin_commands()[k_unsquished]
70
 
    elif decorate:
71
 
        result = plugin_cmds[k_unsquished]
72
 
        plugin_cmds[k_unsquished] = cmd
73
 
        return result
74
 
    else:
75
 
        log_error('Two plugins defined the same command: %r' % k)
76
 
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
 
22
from bzrlib.trace import mutter, note, log_error
 
23
from bzrlib.errors import bailout, BzrError, BzrCheckError, BzrCommandError
 
24
from bzrlib.osutils import quotefn
 
25
from bzrlib import Branch, Inventory, InventoryEntry, BZRDIR, \
 
26
     format_date
77
27
 
78
28
 
79
29
def _squish_command_name(cmd):
84
34
    assert cmd.startswith("cmd_")
85
35
    return cmd[4:].replace('_','-')
86
36
 
87
 
 
88
 
def _builtin_commands():
89
 
    import bzrlib.builtins
90
 
    r = {}
91
 
    builtins = bzrlib.builtins.__dict__
92
 
    for name in builtins:
93
 
        if name.startswith("cmd_"):
94
 
            real_name = _unsquish_command_name(name)
95
 
            r[real_name] = builtins[name]
96
 
    return r
97
 
            
98
 
 
99
 
def builtin_command_names():
100
 
    """Return list of builtin command names."""
101
 
    return _builtin_commands().keys()
102
 
    
103
 
 
104
 
def plugin_command_names():
105
 
    return plugin_cmds.keys()
106
 
 
107
 
 
108
 
def _get_cmd_dict(plugins_override=True):
109
 
    """Return name->class mapping for all commands."""
110
 
    d = _builtin_commands()
111
 
    if plugins_override:
112
 
        d.update(plugin_cmds)
113
 
    return d
114
 
 
115
 
    
116
 
def get_all_cmds(plugins_override=True):
 
37
def _parse_revision_str(revstr):
 
38
    """This handles a revision string -> revno. 
 
39
 
 
40
    There are several possibilities:
 
41
 
 
42
        '234'       -> 234
 
43
        '234:345'   -> [234, 345]
 
44
        ':234'      -> [None, 234]
 
45
        '234:'      -> [234, None]
 
46
 
 
47
    In the future we will also support:
 
48
        'uuid:blah-blah-blah'   -> ?
 
49
        'hash:blahblahblah'     -> ?
 
50
        potentially:
 
51
        'tag:mytag'             -> ?
 
52
    """
 
53
    if revstr.find(':') != -1:
 
54
        revs = revstr.split(':')
 
55
        if len(revs) > 2:
 
56
            raise ValueError('More than 2 pieces not supported for --revision: %r' % revstr)
 
57
 
 
58
        if not revs[0]:
 
59
            revs[0] = None
 
60
        else:
 
61
            revs[0] = int(revs[0])
 
62
 
 
63
        if not revs[1]:
 
64
            revs[1] = None
 
65
        else:
 
66
            revs[1] = int(revs[1])
 
67
    else:
 
68
        revs = int(revstr)
 
69
    return revs
 
70
 
 
71
def get_all_cmds():
117
72
    """Return canonical name and class for all registered commands."""
118
 
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
119
 
        yield k,v
120
 
 
121
 
 
122
 
def get_cmd_object(cmd_name, plugins_override=True):
 
73
    for k, v in globals().iteritems():
 
74
        if k.startswith("cmd_"):
 
75
            yield _unsquish_command_name(k), v
 
76
 
 
77
def get_cmd_class(cmd):
123
78
    """Return the canonical name and command class for a command.
124
 
 
125
 
    plugins_override
126
 
        If true, plugin commands can override builtins.
127
79
    """
128
 
    from bzrlib.externalcommand import ExternalCommand
129
 
 
130
 
    cmd_name = str(cmd_name)            # not unicode
 
80
    cmd = str(cmd)                      # not unicode
131
81
 
132
82
    # first look up this command under the specified name
133
 
    cmds = _get_cmd_dict(plugins_override=plugins_override)
134
83
    try:
135
 
        return cmds[cmd_name]()
 
84
        return cmd, globals()[_squish_command_name(cmd)]
136
85
    except KeyError:
137
86
        pass
138
87
 
139
88
    # look for any command which claims this as an alias
140
 
    for real_cmd_name, cmd_class in cmds.iteritems():
141
 
        if cmd_name in cmd_class.aliases:
142
 
            return cmd_class()
143
 
 
144
 
    cmd_obj = ExternalCommand.find_command(cmd_name)
145
 
    if cmd_obj:
146
 
        return cmd_obj
147
 
 
148
 
    raise BzrCommandError("unknown command %r" % cmd_name)
 
89
    for cmdname, cmdclass in get_all_cmds():
 
90
        if cmd in cmdclass.aliases:
 
91
            return cmdname, cmdclass
 
92
 
 
93
    cmdclass = ExternalCommand.find_command(cmd)
 
94
    if cmdclass:
 
95
        return cmd, cmdclass
 
96
 
 
97
    raise BzrCommandError("unknown command %r" % cmd)
149
98
 
150
99
 
151
100
class Command(object):
152
101
    """Base class for commands.
153
102
 
154
 
    Commands are the heart of the command-line bzr interface.
155
 
 
156
 
    The command object mostly handles the mapping of command-line
157
 
    parameters into one or more bzrlib operations, and of the results
158
 
    into textual output.
159
 
 
160
 
    Commands normally don't have any state.  All their arguments are
161
 
    passed in to the run method.  (Subclasses may take a different
162
 
    policy if the behaviour of the instance needs to depend on e.g. a
163
 
    shell plugin and not just its Python class.)
164
 
 
165
103
    The docstring for an actual command should give a single-line
166
104
    summary, then a complete description of the command.  A grammar
167
105
    description will be inserted.
168
106
 
169
 
    aliases
170
 
        Other accepted names for this command.
171
 
 
172
107
    takes_args
173
108
        List of argument forms, marked with whether they are optional,
174
109
        repeated, etc.
175
110
 
176
 
                Examples:
177
 
 
178
 
                ['to_location', 'from_branch?', 'file*']
179
 
 
180
 
                'to_location' is required
181
 
                'from_branch' is optional
182
 
                'file' can be specified 0 or more times
183
 
 
184
111
    takes_options
185
 
        List of options that may be given for this command.  These can
186
 
        be either strings, referring to globally-defined options,
187
 
        or option objects.  Retrieve through options().
 
112
        List of options that may be given for this command.
188
113
 
189
114
    hidden
190
 
        If true, this command isn't advertised.  This is typically
191
 
        for commands intended for expert users.
 
115
        If true, this command isn't advertised.
192
116
    """
193
117
    aliases = []
 
118
    
194
119
    takes_args = []
195
120
    takes_options = []
196
121
 
197
122
    hidden = False
198
123
    
199
 
    def __init__(self):
200
 
        """Construct an instance of this command."""
201
 
        if self.__doc__ == Command.__doc__:
202
 
            warn("No help message set for %r" % self)
203
 
 
204
 
    def options(self):
205
 
        """Return dict of valid options for this command.
206
 
 
207
 
        Maps from long option name to option object."""
208
 
        r = dict()
209
 
        r['help'] = Option.OPTIONS['help']
210
 
        for o in self.takes_options:
211
 
            if not isinstance(o, Option):
212
 
                o = Option.OPTIONS[o]
213
 
            r[o.name] = o
214
 
        return r
215
 
 
216
 
    @deprecated_method(zero_eight)
217
 
    def run_argv(self, argv):
218
 
        """Parse command line and run.
219
 
        
220
 
        See run_argv_aliases for the 0.8 and beyond api.
221
 
        """
222
 
        return self.run_argv_aliases(argv)
223
 
 
224
 
    def run_argv_aliases(self, argv, alias_argv=None):
225
 
        """Parse the command line and run with extra aliases in alias_argv."""
226
 
        args, opts = parse_args(self, argv, alias_argv)
227
 
        if 'help' in opts:  # e.g. bzr add --help
228
 
            from bzrlib.help import help_on_command
229
 
            help_on_command(self.name())
230
 
            return 0
231
 
        # XXX: This should be handled by the parser
232
 
        allowed_names = self.options().keys()
233
 
        for oname in opts:
234
 
            if oname not in allowed_names:
235
 
                raise BzrCommandError("option '--%s' is not allowed for"
236
 
                                      " command %r" % (oname, self.name()))
237
 
        # mix arguments and options into one dictionary
238
 
        cmdargs = _match_argform(self.name(), self.takes_args, args)
239
 
        cmdopts = {}
240
 
        for k, v in opts.items():
241
 
            cmdopts[k.replace('-', '_')] = v
242
 
 
243
 
        all_cmd_args = cmdargs.copy()
244
 
        all_cmd_args.update(cmdopts)
245
 
 
246
 
        return self.run(**all_cmd_args)
 
124
    def __init__(self, options, arguments):
 
125
        """Construct and run the command.
 
126
 
 
127
        Sets self.status to the return value of run()."""
 
128
        assert isinstance(options, dict)
 
129
        assert isinstance(arguments, dict)
 
130
        cmdargs = options.copy()
 
131
        cmdargs.update(arguments)
 
132
        assert self.__doc__ != Command.__doc__, \
 
133
               ("No help message set for %r" % self)
 
134
        self.status = self.run(**cmdargs)
 
135
 
247
136
    
248
137
    def run(self):
249
 
        """Actually run the command.
 
138
        """Override this in sub-classes.
250
139
 
251
140
        This is invoked with the options and arguments bound to
252
141
        keyword parameters.
253
142
 
254
 
        Return 0 or None if the command was successful, or a non-zero
255
 
        shell error code if not.  It's OK for this method to allow
256
 
        an exception to raise up.
 
143
        Return 0 or None if the command was successful, or a shell
 
144
        error code if not.
257
145
        """
258
 
        raise NotImplementedError('no implementation of command %r' 
259
 
                                  % self.name())
260
 
 
261
 
    def help(self):
262
 
        """Return help message for this class."""
263
 
        from inspect import getdoc
264
 
        if self.__doc__ is Command.__doc__:
265
 
            return None
266
 
        return getdoc(self)
267
 
 
268
 
    def name(self):
269
 
        return _unsquish_command_name(self.__class__.__name__)
270
 
 
 
146
        return 0
 
147
 
 
148
 
 
149
class ExternalCommand(Command):
 
150
    """Class to wrap external commands.
 
151
 
 
152
    We cheat a little here, when get_cmd_class() calls us we actually give it back
 
153
    an object we construct that has the appropriate path, help, options etc for the
 
154
    specified command.
 
155
 
 
156
    When run_bzr() tries to instantiate that 'class' it gets caught by the __call__
 
157
    method, which we override to call the Command.__init__ method. That then calls
 
158
    our run method which is pretty straight forward.
 
159
 
 
160
    The only wrinkle is that we have to map bzr's dictionary of options and arguments
 
161
    back into command line options and arguments for the script.
 
162
    """
 
163
 
 
164
    def find_command(cls, cmd):
 
165
        import os.path
 
166
        bzrpath = os.environ.get('BZRPATH', '')
 
167
 
 
168
        for dir in bzrpath.split(':'):
 
169
            path = os.path.join(dir, cmd)
 
170
            if os.path.isfile(path):
 
171
                return ExternalCommand(path)
 
172
 
 
173
        return None
 
174
 
 
175
    find_command = classmethod(find_command)
 
176
 
 
177
    def __init__(self, path):
 
178
        self.path = path
 
179
 
 
180
        # TODO: If either of these fail, we should detect that and
 
181
        # assume that path is not really a bzr plugin after all.
 
182
 
 
183
        pipe = os.popen('%s --bzr-usage' % path, 'r')
 
184
        self.takes_options = pipe.readline().split()
 
185
        self.takes_args = pipe.readline().split()
 
186
        pipe.close()
 
187
 
 
188
        pipe = os.popen('%s --bzr-help' % path, 'r')
 
189
        self.__doc__ = pipe.read()
 
190
        pipe.close()
 
191
 
 
192
    def __call__(self, options, arguments):
 
193
        Command.__init__(self, options, arguments)
 
194
        return self
 
195
 
 
196
    def run(self, **kargs):
 
197
        opts = []
 
198
        args = []
 
199
 
 
200
        keys = kargs.keys()
 
201
        keys.sort()
 
202
        for name in keys:
 
203
            value = kargs[name]
 
204
            if OPTIONS.has_key(name):
 
205
                # it's an option
 
206
                opts.append('--%s' % name)
 
207
                if value is not None and value is not True:
 
208
                    opts.append(str(value))
 
209
            else:
 
210
                # it's an arg, or arg list
 
211
                if type(value) is not list:
 
212
                    value = [value]
 
213
                for v in value:
 
214
                    if v is not None:
 
215
                        args.append(str(v))
 
216
 
 
217
        self.status = os.spawnv(os.P_WAIT, self.path, [self.path] + opts + args)
 
218
        return self.status
 
219
 
 
220
 
 
221
class cmd_status(Command):
 
222
    """Display status summary.
 
223
 
 
224
    This reports on versioned and unknown files, reporting them
 
225
    grouped by state.  Possible states are:
 
226
 
 
227
    added
 
228
        Versioned in the working copy but not in the previous revision.
 
229
 
 
230
    removed
 
231
        Versioned in the previous revision but removed or deleted
 
232
        in the working copy.
 
233
 
 
234
    renamed
 
235
        Path of this file changed from the previous revision;
 
236
        the text may also have changed.  This includes files whose
 
237
        parent directory was renamed.
 
238
 
 
239
    modified
 
240
        Text has changed since the previous revision.
 
241
 
 
242
    unchanged
 
243
        Nothing about this file has changed since the previous revision.
 
244
        Only shown with --all.
 
245
 
 
246
    unknown
 
247
        Not versioned and not matching an ignore pattern.
 
248
 
 
249
    To see ignored files use 'bzr ignored'.  For details in the
 
250
    changes to file texts, use 'bzr diff'.
 
251
 
 
252
    If no arguments are specified, the status of the entire working
 
253
    directory is shown.  Otherwise, only the status of the specified
 
254
    files or directories is reported.  If a directory is given, status
 
255
    is reported for everything inside that directory.
 
256
    """
 
257
    takes_args = ['file*']
 
258
    takes_options = ['all', 'show-ids']
 
259
    aliases = ['st', 'stat']
 
260
    
 
261
    def run(self, all=False, show_ids=False, file_list=None):
 
262
        if file_list:
 
263
            b = Branch(file_list[0])
 
264
            file_list = [b.relpath(x) for x in file_list]
 
265
            # special case: only one path was given and it's the root
 
266
            # of the branch
 
267
            if file_list == ['']:
 
268
                file_list = None
 
269
        else:
 
270
            b = Branch('.')
 
271
        import status
 
272
        status.show_status(b, show_unchanged=all, show_ids=show_ids,
 
273
                           specific_files=file_list)
 
274
 
 
275
 
 
276
class cmd_cat_revision(Command):
 
277
    """Write out metadata for a revision."""
 
278
 
 
279
    hidden = True
 
280
    takes_args = ['revision_id']
 
281
    
 
282
    def run(self, revision_id):
 
283
        Branch('.').get_revision(revision_id).write_xml(sys.stdout)
 
284
 
 
285
 
 
286
class cmd_revno(Command):
 
287
    """Show current revision number.
 
288
 
 
289
    This is equal to the number of revisions on this branch."""
 
290
    def run(self):
 
291
        print Branch('.').revno()
 
292
 
 
293
    
 
294
class cmd_add(Command):
 
295
    """Add specified files or directories.
 
296
 
 
297
    In non-recursive mode, all the named items are added, regardless
 
298
    of whether they were previously ignored.  A warning is given if
 
299
    any of the named files are already versioned.
 
300
 
 
301
    In recursive mode (the default), files are treated the same way
 
302
    but the behaviour for directories is different.  Directories that
 
303
    are already versioned do not give a warning.  All directories,
 
304
    whether already versioned or not, are searched for files or
 
305
    subdirectories that are neither versioned or ignored, and these
 
306
    are added.  This search proceeds recursively into versioned
 
307
    directories.
 
308
 
 
309
    Therefore simply saying 'bzr add .' will version all files that
 
310
    are currently unknown.
 
311
 
 
312
    TODO: Perhaps adding a file whose directly is not versioned should
 
313
    recursively add that parent, rather than giving an error?
 
314
    """
 
315
    takes_args = ['file+']
 
316
    takes_options = ['verbose', 'no-recurse']
 
317
    
 
318
    def run(self, file_list, verbose=False, no_recurse=False):
 
319
        bzrlib.add.smart_add(file_list, verbose, not no_recurse)
 
320
 
 
321
 
 
322
class cmd_relpath(Command):
 
323
    """Show path of a file relative to root"""
 
324
    takes_args = ['filename']
 
325
    hidden = True
 
326
    
 
327
    def run(self, filename):
 
328
        print Branch(filename).relpath(filename)
 
329
 
 
330
 
 
331
 
 
332
class cmd_inventory(Command):
 
333
    """Show inventory of the current working copy or a revision."""
 
334
    takes_options = ['revision', 'show-ids']
 
335
    
 
336
    def run(self, revision=None, show_ids=False):
 
337
        b = Branch('.')
 
338
        if revision == None:
 
339
            inv = b.read_working_inventory()
 
340
        else:
 
341
            inv = b.get_revision_inventory(b.lookup_revision(revision))
 
342
 
 
343
        for path, entry in inv.entries():
 
344
            if show_ids:
 
345
                print '%-50s %s' % (path, entry.file_id)
 
346
            else:
 
347
                print path
 
348
 
 
349
 
 
350
class cmd_move(Command):
 
351
    """Move files to a different directory.
 
352
 
 
353
    examples:
 
354
        bzr move *.txt doc
 
355
 
 
356
    The destination must be a versioned directory in the same branch.
 
357
    """
 
358
    takes_args = ['source$', 'dest']
 
359
    def run(self, source_list, dest):
 
360
        b = Branch('.')
 
361
 
 
362
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
 
363
 
 
364
 
 
365
class cmd_rename(Command):
 
366
    """Change the name of an entry.
 
367
 
 
368
    examples:
 
369
      bzr rename frob.c frobber.c
 
370
      bzr rename src/frob.c lib/frob.c
 
371
 
 
372
    It is an error if the destination name exists.
 
373
 
 
374
    See also the 'move' command, which moves files into a different
 
375
    directory without changing their name.
 
376
 
 
377
    TODO: Some way to rename multiple files without invoking bzr for each
 
378
    one?"""
 
379
    takes_args = ['from_name', 'to_name']
 
380
    
 
381
    def run(self, from_name, to_name):
 
382
        b = Branch('.')
 
383
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
 
384
 
 
385
 
 
386
 
 
387
class cmd_renames(Command):
 
388
    """Show list of renamed files.
 
389
 
 
390
    TODO: Option to show renames between two historical versions.
 
391
 
 
392
    TODO: Only show renames under dir, rather than in the whole branch.
 
393
    """
 
394
    takes_args = ['dir?']
 
395
 
 
396
    def run(self, dir='.'):
 
397
        b = Branch(dir)
 
398
        old_inv = b.basis_tree().inventory
 
399
        new_inv = b.read_working_inventory()
 
400
 
 
401
        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
 
402
        renames.sort()
 
403
        for old_name, new_name in renames:
 
404
            print "%s => %s" % (old_name, new_name)        
 
405
 
 
406
 
 
407
class cmd_info(Command):
 
408
    """Show statistical information about a branch."""
 
409
    takes_args = ['branch?']
 
410
    
 
411
    def run(self, branch=None):
 
412
        import info
 
413
 
 
414
        from branch import find_branch
 
415
        b = find_branch(branch)
 
416
        info.show_info(b)
 
417
 
 
418
 
 
419
class cmd_remove(Command):
 
420
    """Make a file unversioned.
 
421
 
 
422
    This makes bzr stop tracking changes to a versioned file.  It does
 
423
    not delete the working copy.
 
424
    """
 
425
    takes_args = ['file+']
 
426
    takes_options = ['verbose']
 
427
    
 
428
    def run(self, file_list, verbose=False):
 
429
        b = Branch(file_list[0])
 
430
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
 
431
 
 
432
 
 
433
class cmd_file_id(Command):
 
434
    """Print file_id of a particular file or directory.
 
435
 
 
436
    The file_id is assigned when the file is first added and remains the
 
437
    same through all revisions where the file exists, even when it is
 
438
    moved or renamed.
 
439
    """
 
440
    hidden = True
 
441
    takes_args = ['filename']
 
442
    def run(self, filename):
 
443
        b = Branch(filename)
 
444
        i = b.inventory.path2id(b.relpath(filename))
 
445
        if i == None:
 
446
            bailout("%r is not a versioned file" % filename)
 
447
        else:
 
448
            print i
 
449
 
 
450
 
 
451
class cmd_file_path(Command):
 
452
    """Print path of file_ids to a file or directory.
 
453
 
 
454
    This prints one line for each directory down to the target,
 
455
    starting at the branch root."""
 
456
    hidden = True
 
457
    takes_args = ['filename']
 
458
    def run(self, filename):
 
459
        b = Branch(filename)
 
460
        inv = b.inventory
 
461
        fid = inv.path2id(b.relpath(filename))
 
462
        if fid == None:
 
463
            bailout("%r is not a versioned file" % filename)
 
464
        for fip in inv.get_idpath(fid):
 
465
            print fip
 
466
 
 
467
 
 
468
class cmd_revision_history(Command):
 
469
    """Display list of revision ids on this branch."""
 
470
    hidden = True
 
471
    def run(self):
 
472
        for patchid in Branch('.').revision_history():
 
473
            print patchid
 
474
 
 
475
 
 
476
class cmd_directories(Command):
 
477
    """Display list of versioned directories in this branch."""
 
478
    def run(self):
 
479
        for name, ie in Branch('.').read_working_inventory().directories():
 
480
            if name == '':
 
481
                print '.'
 
482
            else:
 
483
                print name
 
484
 
 
485
 
 
486
class cmd_init(Command):
 
487
    """Make a directory into a versioned branch.
 
488
 
 
489
    Use this to create an empty branch, or before importing an
 
490
    existing project.
 
491
 
 
492
    Recipe for importing a tree of files:
 
493
        cd ~/project
 
494
        bzr init
 
495
        bzr add -v .
 
496
        bzr status
 
497
        bzr commit -m 'imported project'
 
498
    """
 
499
    def run(self):
 
500
        Branch('.', init=True)
 
501
 
 
502
 
 
503
class cmd_diff(Command):
 
504
    """Show differences in working tree.
 
505
    
 
506
    If files are listed, only the changes in those files are listed.
 
507
    Otherwise, all changes for the tree are listed.
 
508
 
 
509
    TODO: Given two revision arguments, show the difference between them.
 
510
 
 
511
    TODO: Allow diff across branches.
 
512
 
 
513
    TODO: Option to use external diff command; could be GNU diff, wdiff,
 
514
          or a graphical diff.
 
515
 
 
516
    TODO: Python difflib is not exactly the same as unidiff; should
 
517
          either fix it up or prefer to use an external diff.
 
518
 
 
519
    TODO: If a directory is given, diff everything under that.
 
520
 
 
521
    TODO: Selected-file diff is inefficient and doesn't show you
 
522
          deleted files.
 
523
 
 
524
    TODO: This probably handles non-Unix newlines poorly.
 
525
    """
 
526
    
 
527
    takes_args = ['file*']
 
528
    takes_options = ['revision', 'diff-options']
 
529
    aliases = ['di']
 
530
 
 
531
    def run(self, revision=None, file_list=None, diff_options=None):
 
532
        from bzrlib.diff import show_diff
 
533
        from bzrlib import find_branch
 
534
 
 
535
        if file_list:
 
536
            b = find_branch(file_list[0])
 
537
            file_list = [b.relpath(f) for f in file_list]
 
538
            if file_list == ['']:
 
539
                # just pointing to top-of-tree
 
540
                file_list = None
 
541
        else:
 
542
            b = Branch('.')
 
543
    
 
544
        show_diff(b, revision, specific_files=file_list,
 
545
                  external_diff_options=diff_options)
 
546
 
 
547
 
 
548
        
 
549
 
 
550
 
 
551
class cmd_deleted(Command):
 
552
    """List files deleted in the working tree.
 
553
 
 
554
    TODO: Show files deleted since a previous revision, or between two revisions.
 
555
    """
 
556
    def run(self, show_ids=False):
 
557
        b = Branch('.')
 
558
        old = b.basis_tree()
 
559
        new = b.working_tree()
 
560
 
 
561
        ## TODO: Much more efficient way to do this: read in new
 
562
        ## directories with readdir, rather than stating each one.  Same
 
563
        ## level of effort but possibly much less IO.  (Or possibly not,
 
564
        ## if the directories are very large...)
 
565
 
 
566
        for path, ie in old.inventory.iter_entries():
 
567
            if not new.has_id(ie.file_id):
 
568
                if show_ids:
 
569
                    print '%-50s %s' % (path, ie.file_id)
 
570
                else:
 
571
                    print path
 
572
 
 
573
 
 
574
class cmd_modified(Command):
 
575
    """List files modified in working tree."""
 
576
    hidden = True
 
577
    def run(self):
 
578
        import statcache
 
579
        b = Branch('.')
 
580
        inv = b.read_working_inventory()
 
581
        sc = statcache.update_cache(b, inv)
 
582
        basis = b.basis_tree()
 
583
        basis_inv = basis.inventory
 
584
        
 
585
        # We used to do this through iter_entries(), but that's slow
 
586
        # when most of the files are unmodified, as is usually the
 
587
        # case.  So instead we iterate by inventory entry, and only
 
588
        # calculate paths as necessary.
 
589
 
 
590
        for file_id in basis_inv:
 
591
            cacheentry = sc.get(file_id)
 
592
            if not cacheentry:                 # deleted
 
593
                continue
 
594
            ie = basis_inv[file_id]
 
595
            if cacheentry[statcache.SC_SHA1] != ie.text_sha1:
 
596
                path = inv.id2path(file_id)
 
597
                print path
 
598
 
 
599
 
 
600
 
 
601
class cmd_added(Command):
 
602
    """List files added in working tree."""
 
603
    hidden = True
 
604
    def run(self):
 
605
        b = Branch('.')
 
606
        wt = b.working_tree()
 
607
        basis_inv = b.basis_tree().inventory
 
608
        inv = wt.inventory
 
609
        for file_id in inv:
 
610
            if file_id in basis_inv:
 
611
                continue
 
612
            path = inv.id2path(file_id)
 
613
            if not os.access(b.abspath(path), os.F_OK):
 
614
                continue
 
615
            print path
 
616
                
 
617
        
 
618
 
 
619
class cmd_root(Command):
 
620
    """Show the tree root directory.
 
621
 
 
622
    The root is the nearest enclosing directory with a .bzr control
 
623
    directory."""
 
624
    takes_args = ['filename?']
 
625
    def run(self, filename=None):
 
626
        """Print the branch root."""
 
627
        from branch import find_branch
 
628
        b = find_branch(filename)
 
629
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
 
630
 
 
631
 
 
632
class cmd_log(Command):
 
633
    """Show log of this branch.
 
634
 
 
635
    To request a range of logs, you can use the command -r begin:end
 
636
    -r revision requests a specific revision, -r :end or -r begin: are
 
637
    also valid.
 
638
 
 
639
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
640
  
 
641
    """
 
642
 
 
643
    takes_args = ['filename?']
 
644
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision']
 
645
    
 
646
    def run(self, filename=None, timezone='original',
 
647
            verbose=False,
 
648
            show_ids=False,
 
649
            forward=False,
 
650
            revision=None):
 
651
        from bzrlib import show_log, find_branch
 
652
        import codecs
 
653
 
 
654
        direction = (forward and 'forward') or 'reverse'
 
655
        
 
656
        if filename:
 
657
            b = find_branch(filename)
 
658
            fp = b.relpath(filename)
 
659
            if fp:
 
660
                file_id = b.read_working_inventory().path2id(fp)
 
661
            else:
 
662
                file_id = None  # points to branch root
 
663
        else:
 
664
            b = find_branch('.')
 
665
            file_id = None
 
666
 
 
667
        if revision == None:
 
668
            revision = [None, None]
 
669
        elif isinstance(revision, int):
 
670
            revision = [revision, revision]
 
671
        else:
 
672
            # pair of revisions?
 
673
            pass
 
674
            
 
675
        assert len(revision) == 2
 
676
 
 
677
        mutter('encoding log as %r' % bzrlib.user_encoding)
 
678
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout)
 
679
 
 
680
        show_log(b, file_id,
 
681
                 show_timezone=timezone,
 
682
                 verbose=verbose,
 
683
                 show_ids=show_ids,
 
684
                 to_file=outf,
 
685
                 direction=direction,
 
686
                 start_revision=revision[0],
 
687
                 end_revision=revision[1])
 
688
 
 
689
 
 
690
 
 
691
class cmd_touching_revisions(Command):
 
692
    """Return revision-ids which affected a particular file.
 
693
 
 
694
    A more user-friendly interface is "bzr log FILE"."""
 
695
    hidden = True
 
696
    takes_args = ["filename"]
 
697
    def run(self, filename):
 
698
        b = Branch(filename)
 
699
        inv = b.read_working_inventory()
 
700
        file_id = inv.path2id(b.relpath(filename))
 
701
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
 
702
            print "%6d %s" % (revno, what)
 
703
 
 
704
 
 
705
class cmd_ls(Command):
 
706
    """List files in a tree.
 
707
 
 
708
    TODO: Take a revision or remote path and list that tree instead.
 
709
    """
 
710
    hidden = True
 
711
    def run(self, revision=None, verbose=False):
 
712
        b = Branch('.')
 
713
        if revision == None:
 
714
            tree = b.working_tree()
 
715
        else:
 
716
            tree = b.revision_tree(b.lookup_revision(revision))
 
717
 
 
718
        for fp, fc, kind, fid in tree.list_files():
 
719
            if verbose:
 
720
                if kind == 'directory':
 
721
                    kindch = '/'
 
722
                elif kind == 'file':
 
723
                    kindch = ''
 
724
                else:
 
725
                    kindch = '???'
 
726
 
 
727
                print '%-8s %s%s' % (fc, fp, kindch)
 
728
            else:
 
729
                print fp
 
730
 
 
731
 
 
732
 
 
733
class cmd_unknowns(Command):
 
734
    """List unknown files"""
 
735
    def run(self):
 
736
        for f in Branch('.').unknowns():
 
737
            print quotefn(f)
 
738
 
 
739
 
 
740
 
 
741
class cmd_ignore(Command):
 
742
    """Ignore a command or pattern
 
743
 
 
744
    To remove patterns from the ignore list, edit the .bzrignore file.
 
745
 
 
746
    If the pattern contains a slash, it is compared to the whole path
 
747
    from the branch root.  Otherwise, it is comapred to only the last
 
748
    component of the path.
 
749
 
 
750
    Ignore patterns are case-insensitive on case-insensitive systems.
 
751
 
 
752
    Note: wildcards must be quoted from the shell on Unix.
 
753
 
 
754
    examples:
 
755
        bzr ignore ./Makefile
 
756
        bzr ignore '*.class'
 
757
    """
 
758
    takes_args = ['name_pattern']
 
759
    
 
760
    def run(self, name_pattern):
 
761
        from bzrlib.atomicfile import AtomicFile
 
762
        import os.path
 
763
 
 
764
        b = Branch('.')
 
765
        ifn = b.abspath('.bzrignore')
 
766
 
 
767
        if os.path.exists(ifn):
 
768
            f = open(ifn, 'rt')
 
769
            try:
 
770
                igns = f.read().decode('utf-8')
 
771
            finally:
 
772
                f.close()
 
773
        else:
 
774
            igns = ''
 
775
 
 
776
        # TODO: If the file already uses crlf-style termination, maybe
 
777
        # we should use that for the newly added lines?
 
778
 
 
779
        if igns and igns[-1] != '\n':
 
780
            igns += '\n'
 
781
        igns += name_pattern + '\n'
 
782
 
 
783
        try:
 
784
            f = AtomicFile(ifn, 'wt')
 
785
            f.write(igns.encode('utf-8'))
 
786
            f.commit()
 
787
        finally:
 
788
            f.close()
 
789
 
 
790
        inv = b.working_tree().inventory
 
791
        if inv.path2id('.bzrignore'):
 
792
            mutter('.bzrignore is already versioned')
 
793
        else:
 
794
            mutter('need to make new .bzrignore file versioned')
 
795
            b.add(['.bzrignore'])
 
796
 
 
797
 
 
798
 
 
799
class cmd_ignored(Command):
 
800
    """List ignored files and the patterns that matched them.
 
801
 
 
802
    See also: bzr ignore"""
 
803
    def run(self):
 
804
        tree = Branch('.').working_tree()
 
805
        for path, file_class, kind, file_id in tree.list_files():
 
806
            if file_class != 'I':
 
807
                continue
 
808
            ## XXX: Slightly inefficient since this was already calculated
 
809
            pat = tree.is_ignored(path)
 
810
            print '%-50s %s' % (path, pat)
 
811
 
 
812
 
 
813
class cmd_lookup_revision(Command):
 
814
    """Lookup the revision-id from a revision-number
 
815
 
 
816
    example:
 
817
        bzr lookup-revision 33
 
818
    """
 
819
    hidden = True
 
820
    takes_args = ['revno']
 
821
    
 
822
    def run(self, revno):
 
823
        try:
 
824
            revno = int(revno)
 
825
        except ValueError:
 
826
            raise BzrCommandError("not a valid revision-number: %r" % revno)
 
827
 
 
828
        print Branch('.').lookup_revision(revno)
 
829
 
 
830
 
 
831
class cmd_export(Command):
 
832
    """Export past revision to destination directory.
 
833
 
 
834
    If no revision is specified this exports the last committed revision."""
 
835
    takes_args = ['dest']
 
836
    takes_options = ['revision']
 
837
    def run(self, dest, revision=None):
 
838
        b = Branch('.')
 
839
        if revision == None:
 
840
            rh = b.revision_history()[-1]
 
841
        else:
 
842
            rh = b.lookup_revision(int(revision))
 
843
        t = b.revision_tree(rh)
 
844
        t.export(dest)
 
845
 
 
846
 
 
847
class cmd_cat(Command):
 
848
    """Write a file's text from a previous revision."""
 
849
 
 
850
    takes_options = ['revision']
 
851
    takes_args = ['filename']
 
852
 
 
853
    def run(self, filename, revision=None):
 
854
        if revision == None:
 
855
            raise BzrCommandError("bzr cat requires a revision number")
 
856
        b = Branch('.')
 
857
        b.print_file(b.relpath(filename), int(revision))
 
858
 
 
859
 
 
860
class cmd_local_time_offset(Command):
 
861
    """Show the offset in seconds from GMT to local time."""
 
862
    hidden = True    
 
863
    def run(self):
 
864
        print bzrlib.osutils.local_time_offset()
 
865
 
 
866
 
 
867
 
 
868
class cmd_commit(Command):
 
869
    """Commit changes into a new revision.
 
870
 
 
871
    If selected files are specified, only changes to those files are
 
872
    committed.  If a directory is specified then its contents are also
 
873
    committed.
 
874
 
 
875
    A selected-file commit may fail in some cases where the committed
 
876
    tree would be invalid, such as trying to commit a file in a
 
877
    newly-added directory that is not itself committed.
 
878
 
 
879
    TODO: Run hooks on tree to-be-committed, and after commit.
 
880
 
 
881
    TODO: Strict commit that fails if there are unknown or deleted files.
 
882
    """
 
883
    takes_args = ['selected*']
 
884
    takes_options = ['message', 'file', 'verbose']
 
885
    aliases = ['ci', 'checkin']
 
886
 
 
887
    def run(self, message=None, file=None, verbose=True, selected_list=None):
 
888
        from bzrlib.commit import commit
 
889
 
 
890
        ## Warning: shadows builtin file()
 
891
        if not message and not file:
 
892
            raise BzrCommandError("please specify a commit message",
 
893
                                  ["use either --message or --file"])
 
894
        elif message and file:
 
895
            raise BzrCommandError("please specify either --message or --file")
 
896
        
 
897
        if file:
 
898
            import codecs
 
899
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
 
900
 
 
901
        b = Branch('.')
 
902
        commit(b, message, verbose=verbose, specific_files=selected_list)
 
903
 
 
904
 
 
905
class cmd_check(Command):
 
906
    """Validate consistency of branch history.
 
907
 
 
908
    This command checks various invariants about the branch storage to
 
909
    detect data corruption or bzr bugs.
 
910
    """
 
911
    takes_args = ['dir?']
 
912
    def run(self, dir='.'):
 
913
        import bzrlib.check
 
914
        bzrlib.check.check(Branch(dir))
 
915
 
 
916
 
 
917
 
 
918
class cmd_whoami(Command):
 
919
    """Show bzr user id."""
 
920
    takes_options = ['email']
 
921
    
 
922
    def run(self, email=False):
 
923
        if email:
 
924
            print bzrlib.osutils.user_email()
 
925
        else:
 
926
            print bzrlib.osutils.username()
 
927
 
 
928
 
 
929
class cmd_selftest(Command):
 
930
    """Run internal test suite"""
 
931
    hidden = True
 
932
    def run(self):
 
933
        failures, tests = 0, 0
 
934
 
 
935
        import doctest, bzrlib.store
 
936
        bzrlib.trace.verbose = False
 
937
 
 
938
        for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
 
939
            bzrlib.tree, bzrlib.commands, bzrlib.add:
 
940
            mf, mt = doctest.testmod(m)
 
941
            failures += mf
 
942
            tests += mt
 
943
            print '%-40s %3d tests' % (m.__name__, mt),
 
944
            if mf:
 
945
                print '%3d FAILED!' % mf
 
946
            else:
 
947
                print
 
948
 
 
949
        print '%-40s %3d tests' % ('total', tests),
 
950
        if failures:
 
951
            print '%3d FAILED!' % failures
 
952
            return 1
 
953
        else:
 
954
            print
 
955
            return 0
 
956
 
 
957
 
 
958
 
 
959
class cmd_version(Command):
 
960
    """Show version of bzr"""
 
961
    def run(self):
 
962
        show_version()
 
963
 
 
964
def show_version():
 
965
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
966
    # is bzrlib itself in a branch?
 
967
    bzrrev = bzrlib.get_bzr_revision()
 
968
    if bzrrev:
 
969
        print "  (bzr checkout, revision %d {%s})" % bzrrev
 
970
    print bzrlib.__copyright__
 
971
    print "http://bazaar-ng.org/"
 
972
    print
 
973
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
 
974
    print "you may use, modify and redistribute it under the terms of the GNU"
 
975
    print "General Public License version 2 or later."
 
976
 
 
977
 
 
978
class cmd_rocks(Command):
 
979
    """Statement of optimism."""
 
980
    hidden = True
 
981
    def run(self):
 
982
        print "it sure does!"
271
983
 
272
984
def parse_spec(spec):
273
 
    """
274
 
    >>> parse_spec(None)
275
 
    [None, None]
276
 
    >>> parse_spec("./")
277
 
    ['./', None]
278
 
    >>> parse_spec("../@")
279
 
    ['..', -1]
280
 
    >>> parse_spec("../f/@35")
281
 
    ['../f', 35]
282
 
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
283
 
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
284
 
    """
285
 
    if spec is None:
286
 
        return [None, None]
287
985
    if '/@' in spec:
288
986
        parsed = spec.split('/@')
289
987
        assert len(parsed) == 2
290
988
        if parsed[1] == "":
291
989
            parsed[1] = -1
292
990
        else:
293
 
            try:
294
 
                parsed[1] = int(parsed[1])
295
 
            except ValueError:
296
 
                pass # We can allow stuff like ./@revid:blahblahblah
297
 
            else:
298
 
                assert parsed[1] >=0
 
991
            parsed[1] = int(parsed[1])
 
992
            assert parsed[1] >=0
299
993
    else:
300
994
        parsed = [spec, None]
301
995
    return parsed
302
996
 
303
 
def parse_args(command, argv, alias_argv=None):
 
997
class cmd_merge(Command):
 
998
    """Perform a three-way merge of trees."""
 
999
    takes_args = ['other_spec', 'base_spec']
 
1000
 
 
1001
    def run(self, other_spec, base_spec):
 
1002
        from bzrlib.merge import merge
 
1003
        merge(parse_spec(other_spec), parse_spec(base_spec))
 
1004
 
 
1005
class cmd_assert_fail(Command):
 
1006
    """Test reporting of assertion failures"""
 
1007
    hidden = True
 
1008
    def run(self):
 
1009
        assert False, "always fails"
 
1010
 
 
1011
 
 
1012
class cmd_help(Command):
 
1013
    """Show help on a command or other topic.
 
1014
 
 
1015
    For a list of all available commands, say 'bzr help commands'."""
 
1016
    takes_args = ['topic?']
 
1017
    aliases = ['?']
 
1018
    
 
1019
    def run(self, topic=None):
 
1020
        import help
 
1021
        help.help(topic)
 
1022
 
 
1023
 
 
1024
class cmd_update_stat_cache(Command):
 
1025
    """Update stat-cache mapping inodes to SHA-1 hashes.
 
1026
 
 
1027
    For testing only."""
 
1028
    hidden = True
 
1029
    def run(self):
 
1030
        import statcache
 
1031
        b = Branch('.')
 
1032
        statcache.update_cache(b.base, b.read_working_inventory())
 
1033
 
 
1034
 
 
1035
 
 
1036
# list of all available options; the rhs can be either None for an
 
1037
# option that takes no argument, or a constructor function that checks
 
1038
# the type.
 
1039
OPTIONS = {
 
1040
    'all':                    None,
 
1041
    'diff-options':           str,
 
1042
    'help':                   None,
 
1043
    'file':                   unicode,
 
1044
    'forward':                None,
 
1045
    'message':                unicode,
 
1046
    'no-recurse':             None,
 
1047
    'profile':                None,
 
1048
    'revision':               _parse_revision_str,
 
1049
    'show-ids':               None,
 
1050
    'timezone':               str,
 
1051
    'verbose':                None,
 
1052
    'version':                None,
 
1053
    'email':                  None,
 
1054
    }
 
1055
 
 
1056
SHORT_OPTIONS = {
 
1057
    'F':                      'file', 
 
1058
    'h':                      'help',
 
1059
    'm':                      'message',
 
1060
    'r':                      'revision',
 
1061
    'v':                      'verbose',
 
1062
}
 
1063
 
 
1064
 
 
1065
def parse_args(argv):
304
1066
    """Parse command line.
305
1067
    
306
1068
    Arguments and options are parsed at this level before being passed
307
1069
    down to specific command handlers.  This routine knows, from a
308
1070
    lookup table, something about the available options, what optargs
309
1071
    they take, and which commands will accept them.
 
1072
 
 
1073
    >>> parse_args('--help'.split())
 
1074
    ([], {'help': True})
 
1075
    >>> parse_args('--version'.split())
 
1076
    ([], {'version': True})
 
1077
    >>> parse_args('status --all'.split())
 
1078
    (['status'], {'all': True})
 
1079
    >>> parse_args('commit --message=biter'.split())
 
1080
    (['commit'], {'message': u'biter'})
310
1081
    """
311
 
    # TODO: chop up this beast; make it a method of the Command
312
1082
    args = []
313
1083
    opts = {}
314
 
    alias_opts = {}
315
 
 
316
 
    cmd_options = command.options()
317
 
    argsover = False
318
 
    proc_aliasarg = True # Are we processing alias_argv now?
319
 
    for proc_argv in alias_argv, argv:
320
 
        while proc_argv:
321
 
            a = proc_argv.pop(0)
322
 
            if argsover:
323
 
                args.append(a)
324
 
                continue
325
 
            elif a == '--':
326
 
                # We've received a standalone -- No more flags
327
 
                argsover = True
328
 
                continue
329
 
            if a[0] == '-':
330
 
                # option names must not be unicode
331
 
                a = str(a)
332
 
                optarg = None
333
 
                if a[1] == '-':
334
 
                    mutter("  got option %r", a)
335
 
                    if '=' in a:
336
 
                        optname, optarg = a[2:].split('=', 1)
337
 
                    else:
338
 
                        optname = a[2:]
339
 
                    if optname not in cmd_options:
340
 
                        raise BzrOptionError('unknown long option %r for'
341
 
                                             ' command %s' % 
342
 
                                             (a, command.name()))
 
1084
 
 
1085
    # TODO: Maybe handle '--' to end options?
 
1086
 
 
1087
    while argv:
 
1088
        a = argv.pop(0)
 
1089
        if a[0] == '-':
 
1090
            # option names must not be unicode
 
1091
            a = str(a)
 
1092
            optarg = None
 
1093
            if a[1] == '-':
 
1094
                mutter("  got option %r" % a)
 
1095
                if '=' in a:
 
1096
                    optname, optarg = a[2:].split('=', 1)
343
1097
                else:
344
 
                    shortopt = a[1:]
345
 
                    if shortopt in Option.SHORT_OPTIONS:
346
 
                        # Multi-character options must have a space to delimit
347
 
                        # their value
348
 
                        # ^^^ what does this mean? mbp 20051014
349
 
                        optname = Option.SHORT_OPTIONS[shortopt].name
350
 
                    else:
351
 
                        # Single character short options, can be chained,
352
 
                        # and have their value appended to their name
353
 
                        shortopt = a[1:2]
354
 
                        if shortopt not in Option.SHORT_OPTIONS:
355
 
                            # We didn't find the multi-character name, and we
356
 
                            # didn't find the single char name
357
 
                            raise BzrError('unknown short option %r' % a)
358
 
                        optname = Option.SHORT_OPTIONS[shortopt].name
359
 
 
360
 
                        if a[2:]:
361
 
                            # There are extra things on this option
362
 
                            # see if it is the value, or if it is another
363
 
                            # short option
364
 
                            optargfn = Option.OPTIONS[optname].type
365
 
                            if optargfn is None:
366
 
                                # This option does not take an argument, so the
367
 
                                # next entry is another short option, pack it
368
 
                                # back into the list
369
 
                                proc_argv.insert(0, '-' + a[2:])
370
 
                            else:
371
 
                                # This option takes an argument, so pack it
372
 
                                # into the array
373
 
                                optarg = a[2:]
 
1098
                    optname = a[2:]
 
1099
                if optname not in OPTIONS:
 
1100
                    bailout('unknown long option %r' % a)
 
1101
            else:
 
1102
                shortopt = a[1:]
 
1103
                if shortopt not in SHORT_OPTIONS:
 
1104
                    bailout('unknown short option %r' % a)
 
1105
                optname = SHORT_OPTIONS[shortopt]
 
1106
            
 
1107
            if optname in opts:
 
1108
                # XXX: Do we ever want to support this, e.g. for -r?
 
1109
                bailout('repeated option %r' % a)
374
1110
                
375
 
                    if optname not in cmd_options:
376
 
                        raise BzrOptionError('unknown short option %r for'
377
 
                                             ' command %s' % 
378
 
                                             (shortopt, command.name()))
379
 
                if optname in opts:
380
 
                    # XXX: Do we ever want to support this, e.g. for -r?
381
 
                    if proc_aliasarg:
382
 
                        raise BzrError('repeated option %r' % a)
383
 
                    elif optname in alias_opts:
384
 
                        # Replace what's in the alias with what's in the real
385
 
                        # argument
386
 
                        del alias_opts[optname]
387
 
                        del opts[optname]
388
 
                        proc_argv.insert(0, a)
389
 
                        continue
 
1111
            optargfn = OPTIONS[optname]
 
1112
            if optargfn:
 
1113
                if optarg == None:
 
1114
                    if not argv:
 
1115
                        bailout('option %r needs an argument' % a)
390
1116
                    else:
391
 
                        raise BzrError('repeated option %r' % a)
392
 
                    
393
 
                option_obj = cmd_options[optname]
394
 
                optargfn = option_obj.type
395
 
                if optargfn:
396
 
                    if optarg == None:
397
 
                        if not proc_argv:
398
 
                            raise BzrError('option %r needs an argument' % a)
399
 
                        else:
400
 
                            optarg = proc_argv.pop(0)
401
 
                    opts[optname] = optargfn(optarg)
402
 
                    if proc_aliasarg:
403
 
                        alias_opts[optname] = optargfn(optarg)
404
 
                else:
405
 
                    if optarg != None:
406
 
                        raise BzrError('option %r takes no argument' % optname)
407
 
                    opts[optname] = True
408
 
                    if proc_aliasarg:
409
 
                        alias_opts[optname] = True
 
1117
                        optarg = argv.pop(0)
 
1118
                opts[optname] = optargfn(optarg)
410
1119
            else:
411
 
                args.append(a)
412
 
        proc_aliasarg = False # Done with alias argv
 
1120
                if optarg != None:
 
1121
                    bailout('option %r takes no argument' % optname)
 
1122
                opts[optname] = True
 
1123
        else:
 
1124
            args.append(a)
 
1125
 
413
1126
    return args, opts
414
1127
 
415
1128
 
 
1129
 
 
1130
 
416
1131
def _match_argform(cmd, takes_args, args):
417
1132
    argdict = {}
418
1133
 
458
1173
 
459
1174
 
460
1175
 
461
 
def apply_profiled(the_callable, *args, **kwargs):
462
 
    import hotshot
463
 
    import tempfile
464
 
    import hotshot.stats
465
 
    pffileno, pfname = tempfile.mkstemp()
466
 
    try:
467
 
        prof = hotshot.Profile(pfname)
468
 
        try:
469
 
            ret = prof.runcall(the_callable, *args, **kwargs) or 0
470
 
        finally:
471
 
            prof.close()
472
 
        stats = hotshot.stats.load(pfname)
473
 
        stats.strip_dirs()
474
 
        stats.sort_stats('cum')   # 'time'
475
 
        ## XXX: Might like to write to stderr or the trace file instead but
476
 
        ## print_stats seems hardcoded to stdout
477
 
        stats.print_stats(20)
478
 
        return ret
479
 
    finally:
480
 
        os.close(pffileno)
481
 
        os.remove(pfname)
482
 
 
483
 
 
484
 
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
485
 
    from bzrlib.lsprof import profile
486
 
    import cPickle
487
 
    ret, stats = profile(the_callable, *args, **kwargs)
488
 
    stats.sort()
489
 
    if filename is None:
490
 
        stats.pprint()
491
 
    else:
492
 
        stats.freeze()
493
 
        cPickle.dump(stats, open(filename, 'w'), 2)
494
 
        print 'Profile data written to %r.' % filename
495
 
    return ret
496
 
 
497
 
 
498
 
def get_alias(cmd):
499
 
    """Return an expanded alias, or None if no alias exists"""
500
 
    import bzrlib.config
501
 
    alias = bzrlib.config.GlobalConfig().get_alias(cmd)
502
 
    if (alias):
503
 
        return alias.split(' ')
504
 
    return None
505
 
 
506
 
 
507
1176
def run_bzr(argv):
508
1177
    """Execute a command.
509
1178
 
510
1179
    This is similar to main(), but without all the trappings for
511
1180
    logging and error handling.  
512
 
    
513
 
    argv
514
 
       The command-line arguments, without the program name from argv[0]
515
 
    
516
 
    Returns a command status or raises an exception.
517
 
 
518
 
    Special master options: these must come before the command because
519
 
    they control how the command is interpreted.
520
 
 
521
 
    --no-plugins
522
 
        Do not load plugin modules at all
523
 
 
524
 
    --no-aliases
525
 
        Do not allow aliases
526
 
 
527
 
    --builtin
528
 
        Only use builtin commands.  (Plugins are still allowed to change
529
 
        other behaviour.)
530
 
 
531
 
    --profile
532
 
        Run under the Python hotshot profiler.
533
 
 
534
 
    --lsprof
535
 
        Run under the Python lsprof profiler.
536
1181
    """
537
1182
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
538
 
 
539
 
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
540
 
                opt_no_aliases = False
541
 
    opt_lsprof_file = None
542
 
 
543
 
    # --no-plugins is handled specially at a very early stage. We need
544
 
    # to load plugins before doing other command parsing so that they
545
 
    # can override commands, but this needs to happen first.
546
 
 
547
 
    argv_copy = []
548
 
    i = 0
549
 
    while i < len(argv):
550
 
        a = argv[i]
551
 
        if a == '--profile':
552
 
            opt_profile = True
553
 
        elif a == '--lsprof':
554
 
            opt_lsprof = True
555
 
        elif a == '--lsprof-file':
556
 
            opt_lsprof_file = argv[i + 1]
557
 
            i += 1
558
 
        elif a == '--no-plugins':
559
 
            opt_no_plugins = True
560
 
        elif a == '--no-aliases':
561
 
            opt_no_aliases = True
562
 
        elif a == '--builtin':
563
 
            opt_builtin = True
564
 
        elif a in ('--quiet', '-q'):
565
 
            be_quiet()
566
 
        else:
567
 
            argv_copy.append(a)
568
 
        i += 1
569
 
 
570
 
    argv = argv_copy
571
 
    if (not argv):
572
 
        from bzrlib.builtins import cmd_help
573
 
        cmd_help().run_argv([])
574
 
        return 0
575
 
 
576
 
    if argv[0] == '--version':
577
 
        from bzrlib.builtins import show_version
578
 
        show_version()
579
 
        return 0
580
 
        
581
 
    if not opt_no_plugins:
582
 
        from bzrlib.plugin import load_plugins
583
 
        load_plugins()
584
 
    else:
585
 
        from bzrlib.plugin import disable_plugins
586
 
        disable_plugins()
587
 
 
588
 
    alias_argv = None
589
 
 
590
 
    if not opt_no_aliases:
591
 
        alias_argv = get_alias(argv[0])
592
 
        if alias_argv:
593
 
            alias_argv = [a.decode(bzrlib.user_encoding) for a in alias_argv]
594
 
            argv[0] = alias_argv.pop(0)
595
 
 
596
 
    cmd = str(argv.pop(0))
597
 
 
598
 
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
599
 
    if not getattr(cmd_obj.run_argv, 'is_deprecated', False):
600
 
        run = cmd_obj.run_argv
601
 
        run_argv = [argv]
602
 
    else:
603
 
        run = cmd_obj.run_argv_aliases
604
 
        run_argv = [argv, alias_argv]
605
 
 
 
1183
    
606
1184
    try:
607
 
        if opt_lsprof:
608
 
            ret = apply_lsprofiled(opt_lsprof_file, run, *run_argv)
609
 
        elif opt_profile:
610
 
            ret = apply_profiled(run, *run_argv)
611
 
        else:
612
 
            ret = run(*run_argv)
613
 
        return ret or 0
614
 
    finally:
615
 
        # reset, in case we may do other commands later within the same process
616
 
        be_quiet(False)
617
 
 
618
 
def display_command(func):
619
 
    """Decorator that suppresses pipe/interrupt errors."""
620
 
    def ignore_pipe(*args, **kwargs):
 
1185
        args, opts = parse_args(argv[1:])
 
1186
        if 'help' in opts:
 
1187
            import help
 
1188
            if args:
 
1189
                help.help(args[0])
 
1190
            else:
 
1191
                help.help()
 
1192
            return 0
 
1193
        elif 'version' in opts:
 
1194
            show_version()
 
1195
            return 0
 
1196
        cmd = str(args.pop(0))
 
1197
    except IndexError:
 
1198
        import help
 
1199
        help.help()
 
1200
        return 1
 
1201
          
 
1202
 
 
1203
    canonical_cmd, cmd_class = get_cmd_class(cmd)
 
1204
 
 
1205
    # global option
 
1206
    if 'profile' in opts:
 
1207
        profile = True
 
1208
        del opts['profile']
 
1209
    else:
 
1210
        profile = False
 
1211
 
 
1212
    # check options are reasonable
 
1213
    allowed = cmd_class.takes_options
 
1214
    for oname in opts:
 
1215
        if oname not in allowed:
 
1216
            raise BzrCommandError("option '--%s' is not allowed for command %r"
 
1217
                                  % (oname, cmd))
 
1218
 
 
1219
    # mix arguments and options into one dictionary
 
1220
    cmdargs = _match_argform(cmd, cmd_class.takes_args, args)
 
1221
    cmdopts = {}
 
1222
    for k, v in opts.items():
 
1223
        cmdopts[k.replace('-', '_')] = v
 
1224
 
 
1225
    if profile:
 
1226
        import hotshot, tempfile
 
1227
        pffileno, pfname = tempfile.mkstemp()
621
1228
        try:
622
 
            result = func(*args, **kwargs)
623
 
            sys.stdout.flush()
624
 
            return result
625
 
        except IOError, e:
626
 
            if not hasattr(e, 'errno'):
627
 
                raise
628
 
            if e.errno != errno.EPIPE:
629
 
                raise
630
 
            pass
631
 
        except KeyboardInterrupt:
632
 
            pass
633
 
    return ignore_pipe
 
1229
            prof = hotshot.Profile(pfname)
 
1230
            ret = prof.runcall(cmd_class, cmdopts, cmdargs) or 0
 
1231
            prof.close()
 
1232
 
 
1233
            import hotshot.stats
 
1234
            stats = hotshot.stats.load(pfname)
 
1235
            #stats.strip_dirs()
 
1236
            stats.sort_stats('time')
 
1237
            ## XXX: Might like to write to stderr or the trace file instead but
 
1238
            ## print_stats seems hardcoded to stdout
 
1239
            stats.print_stats(20)
 
1240
            
 
1241
            return ret.status
 
1242
 
 
1243
        finally:
 
1244
            os.close(pffileno)
 
1245
            os.remove(pfname)
 
1246
    else:
 
1247
        return cmd_class(cmdopts, cmdargs).status 
 
1248
 
 
1249
 
 
1250
def _report_exception(summary, quiet=False):
 
1251
    import traceback
 
1252
    log_error('bzr: ' + summary)
 
1253
    bzrlib.trace.log_exception()
 
1254
 
 
1255
    if not quiet:
 
1256
        tb = sys.exc_info()[2]
 
1257
        exinfo = traceback.extract_tb(tb)
 
1258
        if exinfo:
 
1259
            sys.stderr.write('  at %s:%d in %s()\n' % exinfo[-1][:3])
 
1260
        sys.stderr.write('  see ~/.bzr.log for debug information\n')
 
1261
 
634
1262
 
635
1263
 
636
1264
def main(argv):
637
 
    import bzrlib.ui
638
 
    from bzrlib.ui.text import TextUIFactory
639
 
    ## bzrlib.trace.enable_default_logging()
640
 
    bzrlib.trace.log_startup(argv)
641
 
    bzrlib.ui.ui_factory = TextUIFactory()
642
 
    ret = run_bzr_catch_errors(argv[1:])
643
 
    mutter("return code %d", ret)
644
 
    return ret
645
 
 
646
 
 
647
 
def run_bzr_catch_errors(argv):
 
1265
    import errno
 
1266
    
 
1267
    bzrlib.open_tracefile(argv)
 
1268
 
648
1269
    try:
649
1270
        try:
650
 
            return run_bzr(argv)
651
 
        finally:
652
 
            # do this here inside the exception wrappers to catch EPIPE
653
 
            sys.stdout.flush()
654
 
    except Exception, e:
655
 
        # used to handle AssertionError and KeyboardInterrupt
656
 
        # specially here, but hopefully they're handled ok by the logger now
657
 
        import errno
658
 
        if (isinstance(e, IOError) 
659
 
            and hasattr(e, 'errno')
660
 
            and e.errno == errno.EPIPE):
661
 
            bzrlib.trace.note('broken pipe')
662
 
            return 3
663
 
        else:
664
 
            bzrlib.trace.log_exception()
665
 
            if os.environ.get('BZR_PDB'):
666
 
                print '**** entering debugger'
667
 
                import pdb
668
 
                pdb.post_mortem(sys.exc_traceback)
669
 
            return 3
 
1271
            try:
 
1272
                return run_bzr(argv)
 
1273
            finally:
 
1274
                # do this here inside the exception wrappers to catch EPIPE
 
1275
                sys.stdout.flush()
 
1276
        except BzrError, e:
 
1277
            quiet = isinstance(e, (BzrCommandError))
 
1278
            _report_exception('error: ' + e.args[0], quiet=quiet)
 
1279
            if len(e.args) > 1:
 
1280
                for h in e.args[1]:
 
1281
                    # some explanation or hints
 
1282
                    log_error('  ' + h)
 
1283
            return 1
 
1284
        except AssertionError, e:
 
1285
            msg = 'assertion failed'
 
1286
            if str(e):
 
1287
                msg += ': ' + str(e)
 
1288
            _report_exception(msg)
 
1289
            return 2
 
1290
        except KeyboardInterrupt, e:
 
1291
            _report_exception('interrupted', quiet=True)
 
1292
            return 2
 
1293
        except Exception, e:
 
1294
            quiet = False
 
1295
            if (isinstance(e, IOError) 
 
1296
                and hasattr(e, 'errno')
 
1297
                and e.errno == errno.EPIPE):
 
1298
                quiet = True
 
1299
                msg = 'broken pipe'
 
1300
            else:
 
1301
                msg = str(e).rstrip('\n')
 
1302
            _report_exception(msg, quiet)
 
1303
            return 2
 
1304
    finally:
 
1305
        bzrlib.trace.close_trace()
 
1306
 
670
1307
 
671
1308
if __name__ == '__main__':
672
1309
    sys.exit(main(sys.argv))