/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: Robert Collins
  • Date: 2005-08-25 12:46:42 UTC
  • mfrom: (1116)
  • mto: (974.1.50) (1185.1.10) (1092.3.1)
  • mto: This revision was merged to the branch mainline in revision 1139.
  • Revision ID: robertc@robertcollins.net-20050825124642-45ed1cd74db10370
merge from mpool

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 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
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
 
18
 
# TODO: Define arguments by objects, rather than just using names.
19
 
# Those objects can specify the expected type of the argument, which
20
 
# would help with validation and shell completion.  They could also provide
21
 
# help/explanation for that argument in a structured way.
22
 
 
23
 
# TODO: Specific "examples" property on commands for consistent formatting.
24
 
 
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
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
25
38
import os
26
 
import sys
27
 
 
28
 
from bzrlib.lazy_import import lazy_import
29
 
lazy_import(globals(), """
30
 
import codecs
31
 
import errno
32
 
import threading
33
 
from warnings import warn
34
39
 
35
40
import bzrlib
36
 
from bzrlib import (
37
 
    cleanup,
38
 
    cmdline,
39
 
    debug,
40
 
    errors,
41
 
    option,
42
 
    osutils,
43
 
    trace,
44
 
    ui,
45
 
    win32utils,
46
 
    )
47
 
""")
48
 
 
49
 
from bzrlib.hooks import HookPoint, Hooks
50
 
# Compatibility - Option used to be in commands.
51
 
from bzrlib.option import Option
52
 
from bzrlib.plugin import disable_plugins, load_plugins
53
 
from bzrlib import registry
54
 
from bzrlib.symbol_versioning import (
55
 
    deprecated_function,
56
 
    deprecated_in,
57
 
    deprecated_method,
58
 
    )
59
 
 
60
 
 
61
 
class CommandInfo(object):
62
 
    """Information about a command."""
63
 
 
64
 
    def __init__(self, aliases):
65
 
        """The list of aliases for the command."""
66
 
        self.aliases = aliases
67
 
 
68
 
    @classmethod
69
 
    def from_command(klass, command):
70
 
        """Factory to construct a CommandInfo from a command."""
71
 
        return klass(command.aliases)
72
 
 
73
 
 
74
 
class CommandRegistry(registry.Registry):
75
 
    """Special registry mapping command names to command classes.
76
 
    
77
 
    :ivar overridden_registry: Look in this registry for commands being
78
 
        overridden by this registry.  This can be used to tell plugin commands
79
 
        about the builtin they're decorating.
80
 
    """
81
 
 
82
 
    def __init__(self):
83
 
        registry.Registry.__init__(self)
84
 
        self.overridden_registry = None
85
 
        # map from aliases to the real command that implements the name
86
 
        self._alias_dict = {}
87
 
 
88
 
    def get(self, command_name):
89
 
        real_name = self._alias_dict.get(command_name, command_name)
90
 
        return registry.Registry.get(self, real_name)
91
 
 
92
 
    @staticmethod
93
 
    def _get_name(command_name):
94
 
        if command_name.startswith("cmd_"):
95
 
            return _unsquish_command_name(command_name)
96
 
        else:
97
 
            return command_name
98
 
 
99
 
    def register(self, cmd, decorate=False):
100
 
        """Utility function to help register a command
101
 
 
102
 
        :param cmd: Command subclass to register
103
 
        :param decorate: If true, allow overriding an existing command
104
 
            of the same name; the old command is returned by this function.
105
 
            Otherwise it is an error to try to override an existing command.
106
 
        """
107
 
        k = cmd.__name__
108
 
        k_unsquished = self._get_name(k)
109
 
        try:
110
 
            previous = self.get(k_unsquished)
111
 
        except KeyError:
112
 
            previous = None
113
 
            if self.overridden_registry:
114
 
                try:
115
 
                    previous = self.overridden_registry.get(k_unsquished)
116
 
                except KeyError:
117
 
                    pass
118
 
        info = CommandInfo.from_command(cmd)
119
 
        try:
120
 
            registry.Registry.register(self, k_unsquished, cmd,
121
 
                                       override_existing=decorate, info=info)
122
 
        except KeyError:
123
 
            trace.warning('Two plugins defined the same command: %r' % k)
124
 
            trace.warning('Not loading the one in %r' %
125
 
                sys.modules[cmd.__module__])
126
 
            trace.warning('Previously this command was registered from %r' %
127
 
                sys.modules[previous.__module__])
128
 
        for a in cmd.aliases:
129
 
            self._alias_dict[a] = k_unsquished
130
 
        return previous
131
 
 
132
 
    def register_lazy(self, command_name, aliases, module_name):
133
 
        """Register a command without loading its module.
134
 
 
135
 
        :param command_name: The primary name of the command.
136
 
        :param aliases: A list of aliases for the command.
137
 
        :module_name: The module that the command lives in.
138
 
        """
139
 
        key = self._get_name(command_name)
140
 
        registry.Registry.register_lazy(self, key, module_name, command_name,
141
 
                                        info=CommandInfo(aliases))
142
 
        for a in aliases:
143
 
            self._alias_dict[a] = key
144
 
 
145
 
 
146
 
plugin_cmds = CommandRegistry()
147
 
builtin_command_registry = CommandRegistry()
148
 
plugin_cmds.overridden_registry = builtin_command_registry
149
 
 
150
 
 
151
 
def register_command(cmd, decorate=False):
152
 
    """Register a plugin command.
153
 
 
154
 
    Should generally be avoided in favor of lazy registration. 
155
 
    """
 
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"
156
53
    global plugin_cmds
157
 
    return plugin_cmds.register(cmd, decorate)
 
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__])
158
64
 
159
65
 
160
66
def _squish_command_name(cmd):
162
68
 
163
69
 
164
70
def _unsquish_command_name(cmd):
 
71
    assert cmd.startswith("cmd_")
165
72
    return cmd[4:].replace('_','-')
166
73
 
167
74
 
168
 
@deprecated_function(deprecated_in((2, 2, 0)))
169
 
def _builtin_commands():
170
 
    """Return a dict of {name: cmd_class} for builtin commands.
171
 
 
172
 
    :deprecated: Use the builtin_command_registry registry instead
173
 
    """
174
 
    # return dict(name: cmd_class)
175
 
    return dict(builtin_command_registry.items())
176
 
 
177
 
 
178
 
def _register_builtin_commands():
179
 
    if builtin_command_registry.keys():
180
 
        # only load once
181
 
        return
182
 
    import bzrlib.builtins
183
 
    for cmd_class in _scan_module_for_commands(bzrlib.builtins).values():
184
 
        builtin_command_registry.register(cmd_class)
185
 
    bzrlib.builtins._register_lazy_builtins()
186
 
 
187
 
 
188
 
def _scan_module_for_commands(module):
189
 
    r = {}
190
 
    for name, obj in module.__dict__.iteritems():
191
 
        if name.startswith("cmd_"):
192
 
            real_name = _unsquish_command_name(name)
193
 
            r[real_name] = obj
194
 
    return r
195
 
 
196
 
 
197
 
def _list_bzr_commands(names):
198
 
    """Find commands from bzr's core and plugins.
199
 
    
200
 
    This is not the public interface, just the default hook called by all_command_names.
201
 
    """
202
 
    # to eliminate duplicates
203
 
    names.update(builtin_command_names())
204
 
    names.update(plugin_command_names())
205
 
    return names
206
 
 
207
 
 
208
 
def all_command_names():
209
 
    """Return a set of all command names."""
210
 
    names = set()
211
 
    for hook in Command.hooks['list_commands']:
212
 
        names = hook(names)
213
 
        if names is None:
214
 
            raise AssertionError(
215
 
                'hook %s returned None' % Command.hooks.get_hook_name(hook))
216
 
    return names
217
 
 
218
 
 
219
 
def builtin_command_names():
220
 
    """Return list of builtin command names.
221
 
    
222
 
    Use of all_command_names() is encouraged rather than builtin_command_names
223
 
    and/or plugin_command_names.
224
 
    """
225
 
    return builtin_command_registry.keys()
226
 
 
227
 
 
228
 
def plugin_command_names():
229
 
    """Returns command names from commands registered by plugins."""
230
 
    return plugin_cmds.keys()
231
 
 
232
 
 
233
 
def get_cmd_object(cmd_name, plugins_override=True):
234
 
    """Return the command object for a command.
235
 
 
236
 
    plugins_override
237
 
        If true, plugin commands can override builtins.
238
 
    """
239
 
    try:
240
 
        return _get_cmd_object(cmd_name, plugins_override)
241
 
    except KeyError:
242
 
        raise errors.BzrCommandError('unknown command "%s"' % cmd_name)
243
 
 
244
 
 
245
 
def _get_cmd_object(cmd_name, plugins_override=True, check_missing=True):
246
 
    """Get a command object.
247
 
 
248
 
    :param cmd_name: The name of the command.
249
 
    :param plugins_override: Allow plugins to override builtins.
250
 
    :param check_missing: Look up commands not found in the regular index via
251
 
        the get_missing_command hook.
252
 
    :return: A Command object instance
253
 
    :raises KeyError: If no command is found.
254
 
    """
255
 
    # We want only 'ascii' command names, but the user may have typed
256
 
    # in a Unicode name. In that case, they should just get a
257
 
    # 'command not found' error later.
258
 
    # In the future, we may actually support Unicode command names.
259
 
    cmd = None
260
 
    # Get a command
261
 
    for hook in Command.hooks['get_command']:
262
 
        cmd = hook(cmd, cmd_name)
263
 
        if cmd is not None and not plugins_override and not cmd.plugin_name():
264
 
            # We've found a non-plugin command, don't permit it to be
265
 
            # overridden.
266
 
            break
267
 
    if cmd is None and check_missing:
268
 
        for hook in Command.hooks['get_missing_command']:
269
 
            cmd = hook(cmd_name)
270
 
            if cmd is not None:
271
 
                break
272
 
    if cmd is None:
273
 
        # No command found.
274
 
        raise KeyError
275
 
    # Allow plugins to extend commands
276
 
    for hook in Command.hooks['extend_command']:
277
 
        hook(cmd)
278
 
    return cmd
279
 
 
280
 
 
281
 
def _try_plugin_provider(cmd_name):
282
 
    """Probe for a plugin provider having cmd_name."""
283
 
    try:
284
 
        plugin_metadata, provider = probe_for_provider(cmd_name)
285
 
        raise errors.CommandAvailableInPlugin(cmd_name,
286
 
            plugin_metadata, provider)
287
 
    except errors.NoPluginAvailable:
288
 
        pass
289
 
 
290
 
 
291
 
def probe_for_provider(cmd_name):
292
 
    """Look for a provider for cmd_name.
293
 
 
294
 
    :param cmd_name: The command name.
295
 
    :return: plugin_metadata, provider for getting cmd_name.
296
 
    :raises NoPluginAvailable: When no provider can supply the plugin.
297
 
    """
298
 
    # look for providers that provide this command but aren't installed
299
 
    for provider in command_providers_registry:
300
 
        try:
301
 
            return provider.plugin_for_command(cmd_name), provider
302
 
        except errors.NoPluginAvailable:
303
 
            pass
304
 
    raise errors.NoPluginAvailable(cmd_name)
305
 
 
306
 
 
307
 
def _get_bzr_command(cmd_or_None, cmd_name):
308
 
    """Get a command from bzr's core."""
309
 
    try:
310
 
        cmd_class = builtin_command_registry.get(cmd_name)
311
 
    except KeyError:
312
 
        pass
 
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)
313
182
    else:
314
 
        return cmd_class()
315
 
    return cmd_or_None
316
 
 
317
 
 
318
 
def _get_external_command(cmd_or_None, cmd_name):
319
 
    """Lookup a command that is a shell script."""
320
 
    # Only do external command lookups when no command is found so far.
321
 
    if cmd_or_None is not None:
322
 
        return cmd_or_None
323
 
    from bzrlib.externalcommand import ExternalCommand
324
 
    cmd_obj = ExternalCommand.find_command(cmd_name)
325
 
    if cmd_obj:
326
 
        return cmd_obj
327
 
 
328
 
 
329
 
def _get_plugin_command(cmd_or_None, cmd_name):
330
 
    """Get a command from bzr's plugins."""
 
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)
331
202
    try:
332
 
        return plugin_cmds.get(cmd_name)()
 
203
        return cmd, cmds[cmd]
333
204
    except KeyError:
334
205
        pass
335
 
    for key in plugin_cmds.keys():
336
 
        info = plugin_cmds.get_info(key)
337
 
        if cmd_name in info.aliases:
338
 
            return plugin_cmds.get(key)()
339
 
    return cmd_or_None
 
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)
340
217
 
341
218
 
342
219
class Command(object):
343
220
    """Base class for commands.
344
221
 
345
 
    Commands are the heart of the command-line bzr interface.
346
 
 
347
 
    The command object mostly handles the mapping of command-line
348
 
    parameters into one or more bzrlib operations, and of the results
349
 
    into textual output.
350
 
 
351
 
    Commands normally don't have any state.  All their arguments are
352
 
    passed in to the run method.  (Subclasses may take a different
353
 
    policy if the behaviour of the instance needs to depend on e.g. a
354
 
    shell plugin and not just its Python class.)
355
 
 
356
222
    The docstring for an actual command should give a single-line
357
223
    summary, then a complete description of the command.  A grammar
358
224
    description will be inserted.
359
225
 
360
 
    aliases
361
 
        Other accepted names for this command.
362
 
 
363
226
    takes_args
364
227
        List of argument forms, marked with whether they are optional,
365
228
        repeated, etc.
366
229
 
367
 
                Examples:
368
 
 
369
 
                ['to_location', 'from_branch?', 'file*']
370
 
 
371
 
                'to_location' is required
372
 
                'from_branch' is optional
373
 
                'file' can be specified 0 or more times
374
 
 
375
230
    takes_options
376
 
        List of options that may be given for this command.  These can
377
 
        be either strings, referring to globally-defined options,
378
 
        or option objects.  Retrieve through options().
 
231
        List of options that may be given for this command.
379
232
 
380
233
    hidden
381
 
        If true, this command isn't advertised.  This is typically
382
 
        for commands intended for expert users.
383
 
 
384
 
    encoding_type
385
 
        Command objects will get a 'outf' attribute, which has been
386
 
        setup to properly handle encoding of unicode strings.
387
 
        encoding_type determines what will happen when characters cannot
388
 
        be encoded
389
 
            strict - abort if we cannot decode
390
 
            replace - put in a bogus character (typically '?')
391
 
            exact - do not encode sys.stdout
392
 
 
393
 
            NOTE: by default on Windows, sys.stdout is opened as a text
394
 
            stream, therefore LF line-endings are converted to CRLF.
395
 
            When a command uses encoding_type = 'exact', then
396
 
            sys.stdout is forced to be a binary stream, and line-endings
397
 
            will not mangled.
398
 
 
399
 
    :cvar hooks: An instance of CommandHooks.
 
234
        If true, this command isn't advertised.
400
235
    """
401
236
    aliases = []
 
237
    
402
238
    takes_args = []
403
239
    takes_options = []
404
 
    encoding_type = 'strict'
405
240
 
406
241
    hidden = False
 
242
    
 
243
    def __init__(self, options, arguments):
 
244
        """Construct and run the command.
407
245
 
408
 
    def __init__(self):
409
 
        """Construct an instance of this command."""
 
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)
410
251
        if self.__doc__ == Command.__doc__:
 
252
            from warnings import warn
411
253
            warn("No help message set for %r" % self)
412
 
        # List of standard options directly supported
413
 
        self.supported_std_options = []
414
 
        self._setup_run()
415
 
 
416
 
    def add_cleanup(self, cleanup_func, *args, **kwargs):
417
 
        """Register a function to call after self.run returns or raises.
418
 
 
419
 
        Functions will be called in LIFO order.
420
 
        """
421
 
        self._operation.add_cleanup(cleanup_func, *args, **kwargs)
422
 
 
423
 
    def cleanup_now(self):
424
 
        """Execute and empty pending cleanup functions immediately.
425
 
 
426
 
        After cleanup_now all registered cleanups are forgotten.  add_cleanup
427
 
        may be called again after cleanup_now; these cleanups will be called
428
 
        after self.run returns or raises (or when cleanup_now is next called).
429
 
 
430
 
        This is useful for releasing expensive or contentious resources (such
431
 
        as write locks) before doing further work that does not require those
432
 
        resources (such as writing results to self.outf). Note though, that
433
 
        as it releases all resources, this may release locks that the command
434
 
        wants to hold, so use should be done with care.
435
 
        """
436
 
        self._operation.cleanup_now()
437
 
 
438
 
    @deprecated_method(deprecated_in((2, 1, 0)))
439
 
    def _maybe_expand_globs(self, file_list):
440
 
        """Glob expand file_list if the platform does not do that itself.
441
 
 
442
 
        Not used anymore, now that the bzr command-line parser globs on
443
 
        Windows.
444
 
 
445
 
        :return: A possibly empty list of unicode paths.
446
 
 
447
 
        Introduced in bzrlib 0.18.
448
 
        """
449
 
        return file_list
450
 
 
451
 
    def _usage(self):
452
 
        """Return single-line grammar for this command.
453
 
 
454
 
        Only describes arguments, not options.
455
 
        """
456
 
        s = 'bzr ' + self.name() + ' '
457
 
        for aname in self.takes_args:
458
 
            aname = aname.upper()
459
 
            if aname[-1] in ['$', '+']:
460
 
                aname = aname[:-1] + '...'
461
 
            elif aname[-1] == '?':
462
 
                aname = '[' + aname[:-1] + ']'
463
 
            elif aname[-1] == '*':
464
 
                aname = '[' + aname[:-1] + '...]'
465
 
            s += aname + ' '
466
 
        s = s[:-1]      # remove last space
467
 
        return s
468
 
 
469
 
    def get_help_text(self, additional_see_also=None, plain=True,
470
 
                      see_also_as_links=False, verbose=True):
471
 
        """Return a text string with help for this command.
472
 
 
473
 
        :param additional_see_also: Additional help topics to be
474
 
            cross-referenced.
475
 
        :param plain: if False, raw help (reStructuredText) is
476
 
            returned instead of plain text.
477
 
        :param see_also_as_links: if True, convert items in 'See also'
478
 
            list to internal links (used by bzr_man rstx generator)
479
 
        :param verbose: if True, display the full help, otherwise
480
 
            leave out the descriptive sections and just display
481
 
            usage help (e.g. Purpose, Usage, Options) with a
482
 
            message explaining how to obtain full help.
483
 
        """
484
 
        doc = self.help()
485
 
        if doc is None:
486
 
            raise NotImplementedError("sorry, no detailed help yet for %r" % self.name())
487
 
 
488
 
        # Extract the summary (purpose) and sections out from the text
489
 
        purpose,sections,order = self._get_help_parts(doc)
490
 
 
491
 
        # If a custom usage section was provided, use it
492
 
        if sections.has_key('Usage'):
493
 
            usage = sections.pop('Usage')
494
 
        else:
495
 
            usage = self._usage()
496
 
 
497
 
        # The header is the purpose and usage
498
 
        result = ""
499
 
        result += ':Purpose: %s\n' % purpose
500
 
        if usage.find('\n') >= 0:
501
 
            result += ':Usage:\n%s\n' % usage
502
 
        else:
503
 
            result += ':Usage:   %s\n' % usage
504
 
        result += '\n'
505
 
 
506
 
        # Add the options
507
 
        #
508
 
        # XXX: optparse implicitly rewraps the help, and not always perfectly,
509
 
        # so we get <https://bugs.launchpad.net/bzr/+bug/249908>.  -- mbp
510
 
        # 20090319
511
 
        options = option.get_optparser(self.options()).format_option_help()
512
 
        # XXX: According to the spec, ReST option lists actually don't support 
513
 
        # options like --1.9 so that causes syntax errors (in Sphinx at least).
514
 
        # As that pattern always appears in the commands that break, we trap
515
 
        # on that and then format that block of 'format' options as a literal
516
 
        # block.
517
 
        if not plain and options.find('  --1.9  ') != -1:
518
 
            options = options.replace(' format:\n', ' format::\n\n', 1)
519
 
        if options.startswith('Options:'):
520
 
            result += ':' + options
521
 
        elif options.startswith('options:'):
522
 
            # Python 2.4 version of optparse
523
 
            result += ':Options:' + options[len('options:'):]
524
 
        else:
525
 
            result += options
526
 
        result += '\n'
527
 
 
528
 
        if verbose:
529
 
            # Add the description, indenting it 2 spaces
530
 
            # to match the indentation of the options
531
 
            if sections.has_key(None):
532
 
                text = sections.pop(None)
533
 
                text = '\n  '.join(text.splitlines())
534
 
                result += ':%s:\n  %s\n\n' % ('Description',text)
535
 
 
536
 
            # Add the custom sections (e.g. Examples). Note that there's no need
537
 
            # to indent these as they must be indented already in the source.
538
 
            if sections:
539
 
                for label in order:
540
 
                    if sections.has_key(label):
541
 
                        result += ':%s:\n%s\n' % (label,sections[label])
542
 
                result += '\n'
543
 
        else:
544
 
            result += ("See bzr help %s for more details and examples.\n\n"
545
 
                % self.name())
546
 
 
547
 
        # Add the aliases, source (plug-in) and see also links, if any
548
 
        if self.aliases:
549
 
            result += ':Aliases:  '
550
 
            result += ', '.join(self.aliases) + '\n'
551
 
        plugin_name = self.plugin_name()
552
 
        if plugin_name is not None:
553
 
            result += ':From:     plugin "%s"\n' % plugin_name
554
 
        see_also = self.get_see_also(additional_see_also)
555
 
        if see_also:
556
 
            if not plain and see_also_as_links:
557
 
                see_also_links = []
558
 
                for item in see_also:
559
 
                    if item == 'topics':
560
 
                        # topics doesn't have an independent section
561
 
                        # so don't create a real link
562
 
                        see_also_links.append(item)
563
 
                    else:
564
 
                        # Use a Sphinx link for this entry
565
 
                        link_text = ":doc:`%s <%s-help>`" % (item, item)
566
 
                        see_also_links.append(link_text)
567
 
                see_also = see_also_links
568
 
            result += ':See also: '
569
 
            result += ', '.join(see_also) + '\n'
570
 
 
571
 
        # If this will be rendered as plain text, convert it
572
 
        if plain:
573
 
            import bzrlib.help_topics
574
 
            result = bzrlib.help_topics.help_as_plain_text(result)
575
 
        return result
576
 
 
577
 
    @staticmethod
578
 
    def _get_help_parts(text):
579
 
        """Split help text into a summary and named sections.
580
 
 
581
 
        :return: (summary,sections,order) where summary is the top line and
582
 
            sections is a dictionary of the rest indexed by section name.
583
 
            order is the order the section appear in the text.
584
 
            A section starts with a heading line of the form ":xxx:".
585
 
            Indented text on following lines is the section value.
586
 
            All text found outside a named section is assigned to the
587
 
            default section which is given the key of None.
588
 
        """
589
 
        def save_section(sections, order, label, section):
590
 
            if len(section) > 0:
591
 
                if sections.has_key(label):
592
 
                    sections[label] += '\n' + section
593
 
                else:
594
 
                    order.append(label)
595
 
                    sections[label] = section
596
 
 
597
 
        lines = text.rstrip().splitlines()
598
 
        summary = lines.pop(0)
599
 
        sections = {}
600
 
        order = []
601
 
        label,section = None,''
602
 
        for line in lines:
603
 
            if line.startswith(':') and line.endswith(':') and len(line) > 2:
604
 
                save_section(sections, order, label, section)
605
 
                label,section = line[1:-1],''
606
 
            elif (label is not None) and len(line) > 1 and not line[0].isspace():
607
 
                save_section(sections, order, label, section)
608
 
                label,section = None,line
609
 
            else:
610
 
                if len(section) > 0:
611
 
                    section += '\n' + line
612
 
                else:
613
 
                    section = line
614
 
        save_section(sections, order, label, section)
615
 
        return summary, sections, order
616
 
 
617
 
    def get_help_topic(self):
618
 
        """Return the commands help topic - its name."""
619
 
        return self.name()
620
 
 
621
 
    def get_see_also(self, additional_terms=None):
622
 
        """Return a list of help topics that are related to this command.
623
 
 
624
 
        The list is derived from the content of the _see_also attribute. Any
625
 
        duplicates are removed and the result is in lexical order.
626
 
        :param additional_terms: Additional help topics to cross-reference.
627
 
        :return: A list of help topics.
628
 
        """
629
 
        see_also = set(getattr(self, '_see_also', []))
630
 
        if additional_terms:
631
 
            see_also.update(additional_terms)
632
 
        return sorted(see_also)
633
 
 
634
 
    def options(self):
635
 
        """Return dict of valid options for this command.
636
 
 
637
 
        Maps from long option name to option object."""
638
 
        r = Option.STD_OPTIONS.copy()
639
 
        std_names = r.keys()
640
 
        for o in self.takes_options:
641
 
            if isinstance(o, basestring):
642
 
                o = option.Option.OPTIONS[o]
643
 
            r[o.name] = o
644
 
            if o.name in std_names:
645
 
                self.supported_std_options.append(o.name)
646
 
        return r
647
 
 
648
 
    def _setup_outf(self):
649
 
        """Return a file linked to stdout, which has proper encoding."""
650
 
        self.outf = ui.ui_factory.make_output_stream(
651
 
            encoding_type=self.encoding_type)
652
 
 
653
 
    def run_argv_aliases(self, argv, alias_argv=None):
654
 
        """Parse the command line and run with extra aliases in alias_argv."""
655
 
        args, opts = parse_args(self, argv, alias_argv)
656
 
 
657
 
        # Process the standard options
658
 
        if 'help' in opts:  # e.g. bzr add --help
659
 
            sys.stdout.write(self.get_help_text())
660
 
            return 0
661
 
        if 'usage' in opts:  # e.g. bzr add --usage
662
 
            sys.stdout.write(self.get_help_text(verbose=False))
663
 
            return 0
664
 
        trace.set_verbosity_level(option._verbosity_level)
665
 
        if 'verbose' in self.supported_std_options:
666
 
            opts['verbose'] = trace.is_verbose()
667
 
        elif opts.has_key('verbose'):
668
 
            del opts['verbose']
669
 
        if 'quiet' in self.supported_std_options:
670
 
            opts['quiet'] = trace.is_quiet()
671
 
        elif opts.has_key('quiet'):
672
 
            del opts['quiet']
673
 
 
674
 
        # mix arguments and options into one dictionary
675
 
        cmdargs = _match_argform(self.name(), self.takes_args, args)
676
 
        cmdopts = {}
677
 
        for k, v in opts.items():
678
 
            cmdopts[k.replace('-', '_')] = v
679
 
 
680
 
        all_cmd_args = cmdargs.copy()
681
 
        all_cmd_args.update(cmdopts)
682
 
 
683
 
        self._setup_outf()
684
 
 
685
 
        return self.run(**all_cmd_args)
686
 
 
687
 
    def _setup_run(self):
688
 
        """Wrap the defined run method on self with a cleanup.
689
 
 
690
 
        This is called by __init__ to make the Command be able to be run
691
 
        by just calling run(), as it could be before cleanups were added.
692
 
 
693
 
        If a different form of cleanups are in use by your Command subclass,
694
 
        you can override this method.
695
 
        """
696
 
        class_run = self.run
697
 
        def run(*args, **kwargs):
698
 
            self._operation = cleanup.OperationWithCleanups(class_run)
699
 
            try:
700
 
                return self._operation.run_simple(*args, **kwargs)
701
 
            finally:
702
 
                del self._operation
703
 
        self.run = run
704
 
 
705
 
    @deprecated_method(deprecated_in((2, 2, 0)))
706
 
    def run_direct(self, *args, **kwargs):
707
 
        """Deprecated thunk from bzrlib 2.1."""
708
 
        return self.run(*args, **kwargs)
709
 
 
 
254
        self.status = self.run(**cmdargs)
 
255
        if self.status is None:
 
256
            self.status = 0
 
257
 
 
258
    
710
259
    def run(self):
711
 
        """Actually run the command.
 
260
        """Override this in sub-classes.
712
261
 
713
262
        This is invoked with the options and arguments bound to
714
263
        keyword parameters.
715
264
 
716
 
        Return 0 or None if the command was successful, or a non-zero
717
 
        shell error code if not.  It's OK for this method to allow
718
 
        an exception to raise up.
719
 
 
720
 
        This method is automatically wrapped by Command.__init__ with a 
721
 
        cleanup operation, stored as self._operation. This can be used
722
 
        via self.add_cleanup to perform automatic cleanups at the end of
723
 
        run().
724
 
 
725
 
        The argument for run are assembled by introspection. So for instance,
726
 
        if your command takes an argument files, you would declare::
727
 
 
728
 
            def run(self, files=None):
729
 
                pass
 
265
        Return 0 or None if the command was successful, or a shell
 
266
        error code if not.
730
267
        """
731
 
        raise NotImplementedError('no implementation of command %r'
732
 
                                  % self.name())
733
 
 
734
 
    def help(self):
735
 
        """Return help message for this class."""
 
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):
 
354
    """Display status summary.
 
355
 
 
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):
 
453
    """Add specified files or directories.
 
454
 
 
455
    In non-recursive mode, all the named items are added, regardless
 
456
    of whether they were previously ignored.  A warning is given if
 
457
    any of the named files are already versioned.
 
458
 
 
459
    In recursive mode (the default), files are treated the same way
 
460
    but the behaviour for directories is different.  Directories that
 
461
    are already versioned do not give a warning.  All directories,
 
462
    whether already versioned or not, are searched for files or
 
463
    subdirectories that are neither versioned or ignored, and these
 
464
    are added.  This search proceeds recursively into versioned
 
465
    directories.  If no names are given '.' is assumed.
 
466
 
 
467
    Therefore simply saying 'bzr add' will version all files that
 
468
    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):
 
962
    """Show log of this branch.
 
963
 
 
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
  
 
973
    """
 
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):
 
1061
    """List files in a tree.
 
1062
 
 
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):
 
1382
    """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():
 
1413
    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
    print bzrlib.__copyright__
 
1419
    print "http://bazaar-ng.org/"
 
1420
    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):
 
1427
    """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
        if file_list is not None:
 
1557
            if len(file_list) == 0:
 
1558
                raise BzrCommandError("No files specified")
 
1559
        if revision is None:
 
1560
            revision = [-1]
 
1561
        elif len(revision) != 1:
 
1562
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
1563
        merge(('.', revision[0]), parse_spec('.'),
 
1564
              check_clean=False,
 
1565
              ignore_zero=True,
 
1566
              backup_files=not no_backup,
 
1567
              file_list=file_list)
 
1568
 
 
1569
 
 
1570
class cmd_assert_fail(Command):
 
1571
    """Test reporting of assertion failures"""
 
1572
    hidden = True
 
1573
    def run(self):
 
1574
        assert False, "always fails"
 
1575
 
 
1576
 
 
1577
class cmd_help(Command):
 
1578
    """Show help on a command or other topic.
 
1579
 
 
1580
    For a list of all available commands, say 'bzr help commands'."""
 
1581
    takes_options = ['long']
 
1582
    takes_args = ['topic?']
 
1583
    aliases = ['?']
 
1584
    
 
1585
    def run(self, topic=None, long=False):
 
1586
        import help
 
1587
        if topic is None and long:
 
1588
            topic = "commands"
 
1589
        help.help(topic)
 
1590
 
 
1591
 
 
1592
class cmd_shell_complete(Command):
 
1593
    """Show appropriate completions for context.
 
1594
 
 
1595
    For a list of all available commands, say 'bzr shell-complete'."""
 
1596
    takes_args = ['context?']
 
1597
    aliases = ['s-c']
 
1598
    hidden = True
 
1599
    
 
1600
    def run(self, context=None):
 
1601
        import shellcomplete
 
1602
        shellcomplete.shellcomplete(context)
 
1603
 
 
1604
 
 
1605
class cmd_missing(Command):
 
1606
    """What is missing in this branch relative to other branch.
 
1607
    """
 
1608
    takes_args = ['remote?']
 
1609
    aliases = ['mis', 'miss']
 
1610
    # We don't have to add quiet to the list, because 
 
1611
    # unknown options are parsed as booleans
 
1612
    takes_options = ['verbose', 'quiet']
 
1613
 
 
1614
    def run(self, remote=None, verbose=False, quiet=False):
 
1615
        from bzrlib.branch import find_branch, DivergedBranches
 
1616
        from bzrlib.errors import BzrCommandError
 
1617
        from bzrlib.missing import get_parent, show_missing
 
1618
 
 
1619
        if verbose and quiet:
 
1620
            raise BzrCommandError('Cannot pass both quiet and verbose')
 
1621
 
 
1622
        b = find_branch('.')
 
1623
        parent = get_parent(b)
 
1624
        if remote is None:
 
1625
            if parent is None:
 
1626
                raise BzrCommandError("No missing location known or specified.")
 
1627
            else:
 
1628
                if not quiet:
 
1629
                    print "Using last location: %s" % parent
 
1630
                remote = parent
 
1631
        elif parent is None:
 
1632
            # We only update x-pull if it did not exist, missing should not change the parent
 
1633
            b.controlfile('x-pull', 'wb').write(remote + '\n')
 
1634
        br_remote = find_branch(remote)
 
1635
 
 
1636
        return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
 
1637
 
 
1638
 
 
1639
 
 
1640
class cmd_plugins(Command):
 
1641
    """List plugins"""
 
1642
    hidden = True
 
1643
    def run(self):
 
1644
        import bzrlib.plugin
736
1645
        from inspect import getdoc
737
 
        if self.__doc__ is Command.__doc__:
738
 
            return None
739
 
        return getdoc(self)
740
 
 
741
 
    def name(self):
742
 
        return _unsquish_command_name(self.__class__.__name__)
743
 
 
744
 
    def plugin_name(self):
745
 
        """Get the name of the plugin that provides this command.
746
 
 
747
 
        :return: The name of the plugin or None if the command is builtin.
748
 
        """
749
 
        mod_parts = self.__module__.split('.')
750
 
        if len(mod_parts) >= 3 and mod_parts[1] == 'plugins':
751
 
            return mod_parts[2]
752
 
        else:
753
 
            return None
754
 
 
755
 
 
756
 
class CommandHooks(Hooks):
757
 
    """Hooks related to Command object creation/enumeration."""
758
 
 
759
 
    def __init__(self):
760
 
        """Create the default hooks.
761
 
 
762
 
        These are all empty initially, because by default nothing should get
763
 
        notified.
764
 
        """
765
 
        Hooks.__init__(self)
766
 
        self.create_hook(HookPoint('extend_command',
767
 
            "Called after creating a command object to allow modifications "
768
 
            "such as adding or removing options, docs etc. Called with the "
769
 
            "new bzrlib.commands.Command object.", (1, 13), None))
770
 
        self.create_hook(HookPoint('get_command',
771
 
            "Called when creating a single command. Called with "
772
 
            "(cmd_or_None, command_name). get_command should either return "
773
 
            "the cmd_or_None parameter, or a replacement Command object that "
774
 
            "should be used for the command. Note that the Command.hooks "
775
 
            "hooks are core infrastructure. Many users will prefer to use "
776
 
            "bzrlib.commands.register_command or plugin_cmds.register_lazy.",
777
 
            (1, 17), None))
778
 
        self.create_hook(HookPoint('get_missing_command',
779
 
            "Called when creating a single command if no command could be "
780
 
            "found. Called with (command_name). get_missing_command should "
781
 
            "either return None, or a Command object to be used for the "
782
 
            "command.", (1, 17), None))
783
 
        self.create_hook(HookPoint('list_commands',
784
 
            "Called when enumerating commands. Called with a set of "
785
 
            "cmd_name strings for all the commands found so far. This set "
786
 
            " is safe to mutate - e.g. to remove a command. "
787
 
            "list_commands should return the updated set of command names.",
788
 
            (1, 17), None))
789
 
 
790
 
Command.hooks = CommandHooks()
791
 
 
792
 
 
793
 
def parse_args(command, argv, alias_argv=None):
 
1646
        from pprint import pprint
 
1647
        for plugin in bzrlib.plugin.all_plugins:
 
1648
            print plugin.__path__[0]
 
1649
            d = getdoc(plugin)
 
1650
            if d:
 
1651
                print '\t', d.split('\n')[0]
 
1652
 
 
1653
        #pprint(bzrlib.plugin.all_plugins)
 
1654
 
 
1655
 
 
1656
 
 
1657
# list of all available options; the rhs can be either None for an
 
1658
# option that takes no argument, or a constructor function that checks
 
1659
# the type.
 
1660
OPTIONS = {
 
1661
    'all':                    None,
 
1662
    'diff-options':           str,
 
1663
    'help':                   None,
 
1664
    'file':                   unicode,
 
1665
    'force':                  None,
 
1666
    'format':                 unicode,
 
1667
    'forward':                None,
 
1668
    'message':                unicode,
 
1669
    'no-recurse':             None,
 
1670
    'profile':                None,
 
1671
    'revision':               _parse_revision_str,
 
1672
    'short':                  None,
 
1673
    'show-ids':               None,
 
1674
    'timezone':               str,
 
1675
    'verbose':                None,
 
1676
    'version':                None,
 
1677
    'email':                  None,
 
1678
    'unchanged':              None,
 
1679
    'update':                 None,
 
1680
    'long':                   None,
 
1681
    'root':                   str,
 
1682
    'no-backup':              None,
 
1683
    'merge-type':             get_merge_type,
 
1684
    'pattern':                str,
 
1685
    }
 
1686
 
 
1687
SHORT_OPTIONS = {
 
1688
    'F':                      'file', 
 
1689
    'h':                      'help',
 
1690
    'm':                      'message',
 
1691
    'r':                      'revision',
 
1692
    'v':                      'verbose',
 
1693
    'l':                      'long',
 
1694
}
 
1695
 
 
1696
 
 
1697
def parse_args(argv):
794
1698
    """Parse command line.
795
 
 
 
1699
    
796
1700
    Arguments and options are parsed at this level before being passed
797
1701
    down to specific command handlers.  This routine knows, from a
798
1702
    lookup table, something about the available options, what optargs
799
1703
    they take, and which commands will accept them.
 
1704
 
 
1705
    >>> parse_args('--help'.split())
 
1706
    ([], {'help': True})
 
1707
    >>> parse_args('--version'.split())
 
1708
    ([], {'version': True})
 
1709
    >>> parse_args('status --all'.split())
 
1710
    (['status'], {'all': True})
 
1711
    >>> parse_args('commit --message=biter'.split())
 
1712
    (['commit'], {'message': u'biter'})
 
1713
    >>> parse_args('log -r 500'.split())
 
1714
    (['log'], {'revision': [500]})
 
1715
    >>> parse_args('log -r500..600'.split())
 
1716
    (['log'], {'revision': [500, 600]})
 
1717
    >>> parse_args('log -vr500..600'.split())
 
1718
    (['log'], {'verbose': True, 'revision': [500, 600]})
 
1719
    >>> parse_args('log -rv500..600'.split()) #the r takes an argument
 
1720
    (['log'], {'revision': ['v500', 600]})
800
1721
    """
801
 
    # TODO: make it a method of the Command?
802
 
    parser = option.get_optparser(command.options())
803
 
    if alias_argv is not None:
804
 
        args = alias_argv + argv
805
 
    else:
806
 
        args = argv
807
 
 
808
 
    options, args = parser.parse_args(args)
809
 
    opts = dict([(k, v) for k, v in options.__dict__.iteritems() if
810
 
                 v is not option.OptionParser.DEFAULT_VALUE])
 
1722
    args = []
 
1723
    opts = {}
 
1724
 
 
1725
    # TODO: Maybe handle '--' to end options?
 
1726
 
 
1727
    while argv:
 
1728
        a = argv.pop(0)
 
1729
        if a[0] == '-':
 
1730
            # option names must not be unicode
 
1731
            a = str(a)
 
1732
            optarg = None
 
1733
            if a[1] == '-':
 
1734
                mutter("  got option %r" % a)
 
1735
                if '=' in a:
 
1736
                    optname, optarg = a[2:].split('=', 1)
 
1737
                else:
 
1738
                    optname = a[2:]
 
1739
                if optname not in OPTIONS:
 
1740
                    raise BzrError('unknown long option %r' % a)
 
1741
            else:
 
1742
                shortopt = a[1:]
 
1743
                if shortopt in SHORT_OPTIONS:
 
1744
                    # Multi-character options must have a space to delimit
 
1745
                    # their value
 
1746
                    optname = SHORT_OPTIONS[shortopt]
 
1747
                else:
 
1748
                    # Single character short options, can be chained,
 
1749
                    # and have their value appended to their name
 
1750
                    shortopt = a[1:2]
 
1751
                    if shortopt not in SHORT_OPTIONS:
 
1752
                        # We didn't find the multi-character name, and we
 
1753
                        # didn't find the single char name
 
1754
                        raise BzrError('unknown short option %r' % a)
 
1755
                    optname = SHORT_OPTIONS[shortopt]
 
1756
 
 
1757
                    if a[2:]:
 
1758
                        # There are extra things on this option
 
1759
                        # see if it is the value, or if it is another
 
1760
                        # short option
 
1761
                        optargfn = OPTIONS[optname]
 
1762
                        if optargfn is None:
 
1763
                            # This option does not take an argument, so the
 
1764
                            # next entry is another short option, pack it back
 
1765
                            # into the list
 
1766
                            argv.insert(0, '-' + a[2:])
 
1767
                        else:
 
1768
                            # This option takes an argument, so pack it
 
1769
                            # into the array
 
1770
                            optarg = a[2:]
 
1771
            
 
1772
            if optname in opts:
 
1773
                # XXX: Do we ever want to support this, e.g. for -r?
 
1774
                raise BzrError('repeated option %r' % a)
 
1775
                
 
1776
            optargfn = OPTIONS[optname]
 
1777
            if optargfn:
 
1778
                if optarg == None:
 
1779
                    if not argv:
 
1780
                        raise BzrError('option %r needs an argument' % a)
 
1781
                    else:
 
1782
                        optarg = argv.pop(0)
 
1783
                opts[optname] = optargfn(optarg)
 
1784
            else:
 
1785
                if optarg != None:
 
1786
                    raise BzrError('option %r takes no argument' % optname)
 
1787
                opts[optname] = True
 
1788
        else:
 
1789
            args.append(a)
 
1790
 
811
1791
    return args, opts
812
1792
 
813
1793
 
 
1794
 
 
1795
 
814
1796
def _match_argform(cmd, takes_args, args):
815
1797
    argdict = {}
816
1798
 
828
1810
                argdict[argname + '_list'] = None
829
1811
        elif ap[-1] == '+':
830
1812
            if not args:
831
 
                raise errors.BzrCommandError("command %r needs one or more %s"
832
 
                                             % (cmd, argname.upper()))
 
1813
                raise BzrCommandError("command %r needs one or more %s"
 
1814
                        % (cmd, argname.upper()))
833
1815
            else:
834
1816
                argdict[argname + '_list'] = args[:]
835
1817
                args = []
836
1818
        elif ap[-1] == '$': # all but one
837
1819
            if len(args) < 2:
838
 
                raise errors.BzrCommandError("command %r needs one or more %s"
839
 
                                             % (cmd, argname.upper()))
 
1820
                raise BzrCommandError("command %r needs one or more %s"
 
1821
                        % (cmd, argname.upper()))
840
1822
            argdict[argname + '_list'] = args[:-1]
841
 
            args[:-1] = []
 
1823
            args[:-1] = []                
842
1824
        else:
843
1825
            # just a plain arg
844
1826
            argname = ap
845
1827
            if not args:
846
 
                raise errors.BzrCommandError("command %r requires argument %s"
847
 
                               % (cmd, argname.upper()))
 
1828
                raise BzrCommandError("command %r requires argument %s"
 
1829
                        % (cmd, argname.upper()))
848
1830
            else:
849
1831
                argdict[argname] = args.pop(0)
850
 
 
 
1832
            
851
1833
    if args:
852
 
        raise errors.BzrCommandError("extra argument to command %s: %s"
853
 
                                     % (cmd, args[0]))
 
1834
        raise BzrCommandError("extra argument to command %s: %s"
 
1835
                              % (cmd, args[0]))
854
1836
 
855
1837
    return argdict
856
1838
 
857
 
def apply_coveraged(dirname, the_callable, *args, **kwargs):
858
 
    # Cannot use "import trace", as that would import bzrlib.trace instead of
859
 
    # the standard library's trace.
860
 
    trace = __import__('trace')
861
 
 
862
 
    tracer = trace.Trace(count=1, trace=0)
863
 
    sys.settrace(tracer.globaltrace)
864
 
    threading.settrace(tracer.globaltrace)
865
 
 
866
 
    try:
867
 
        return exception_to_return_code(the_callable, *args, **kwargs)
868
 
    finally:
869
 
        sys.settrace(None)
870
 
        results = tracer.results()
871
 
        results.write_results(show_missing=1, summary=False,
872
 
                              coverdir=dirname)
873
 
 
874
 
 
875
 
def apply_profiled(the_callable, *args, **kwargs):
876
 
    import hotshot
877
 
    import tempfile
878
 
    import hotshot.stats
879
 
    pffileno, pfname = tempfile.mkstemp()
880
 
    try:
881
 
        prof = hotshot.Profile(pfname)
882
 
        try:
883
 
            ret = prof.runcall(exception_to_return_code, the_callable, *args,
884
 
                **kwargs) or 0
885
 
        finally:
886
 
            prof.close()
887
 
        stats = hotshot.stats.load(pfname)
888
 
        stats.strip_dirs()
889
 
        stats.sort_stats('cum')   # 'time'
890
 
        ## XXX: Might like to write to stderr or the trace file instead but
891
 
        ## print_stats seems hardcoded to stdout
892
 
        stats.print_stats(20)
893
 
        return ret
894
 
    finally:
895
 
        os.close(pffileno)
896
 
        os.remove(pfname)
897
 
 
898
 
 
899
 
def exception_to_return_code(the_callable, *args, **kwargs):
900
 
    """UI level helper for profiling and coverage.
901
 
 
902
 
    This transforms exceptions into a return value of 3. As such its only
903
 
    relevant to the UI layer, and should never be called where catching
904
 
    exceptions may be desirable.
905
 
    """
906
 
    try:
907
 
        return the_callable(*args, **kwargs)
908
 
    except (KeyboardInterrupt, Exception), e:
909
 
        # used to handle AssertionError and KeyboardInterrupt
910
 
        # specially here, but hopefully they're handled ok by the logger now
911
 
        exc_info = sys.exc_info()
912
 
        exitcode = trace.report_exception(exc_info, sys.stderr)
913
 
        if os.environ.get('BZR_PDB'):
914
 
            print '**** entering debugger'
915
 
            tb = exc_info[2]
916
 
            import pdb
917
 
            if sys.version_info[:2] < (2, 6):
918
 
                # XXX: we want to do
919
 
                #    pdb.post_mortem(tb)
920
 
                # but because pdb.post_mortem gives bad results for tracebacks
921
 
                # from inside generators, we do it manually.
922
 
                # (http://bugs.python.org/issue4150, fixed in Python 2.6)
923
 
 
924
 
                # Setup pdb on the traceback
925
 
                p = pdb.Pdb()
926
 
                p.reset()
927
 
                p.setup(tb.tb_frame, tb)
928
 
                # Point the debugger at the deepest frame of the stack
929
 
                p.curindex = len(p.stack) - 1
930
 
                p.curframe = p.stack[p.curindex][0]
931
 
                # Start the pdb prompt.
932
 
                p.print_stack_entry(p.stack[p.curindex])
933
 
                p.execRcLines()
934
 
                p.cmdloop()
935
 
            else:
936
 
                pdb.post_mortem(tb)
937
 
        return exitcode
938
 
 
939
 
 
940
 
def apply_lsprofiled(filename, the_callable, *args, **kwargs):
941
 
    from bzrlib.lsprof import profile
942
 
    ret, stats = profile(exception_to_return_code, the_callable, *args, **kwargs)
943
 
    stats.sort()
944
 
    if filename is None:
945
 
        stats.pprint()
946
 
    else:
947
 
        stats.save(filename)
948
 
        trace.note('Profile data written to "%s".', filename)
949
 
    return ret
950
 
 
951
 
 
952
 
@deprecated_function(deprecated_in((2, 2, 0)))
953
 
def shlex_split_unicode(unsplit):
954
 
    return cmdline.split(unsplit)
955
 
 
956
 
 
957
 
def get_alias(cmd, config=None):
958
 
    """Return an expanded alias, or None if no alias exists.
959
 
 
960
 
    cmd
961
 
        Command to be checked for an alias.
962
 
    config
963
 
        Used to specify an alternative config to use,
964
 
        which is especially useful for testing.
965
 
        If it is unspecified, the global config will be used.
966
 
    """
967
 
    if config is None:
968
 
        import bzrlib.config
969
 
        config = bzrlib.config.GlobalConfig()
970
 
    alias = config.get_alias(cmd)
971
 
    if (alias):
972
 
        return cmdline.split(alias)
973
 
    return None
974
 
 
975
 
 
976
 
def run_bzr(argv, load_plugins=load_plugins, disable_plugins=disable_plugins):
 
1839
 
 
1840
 
 
1841
def run_bzr(argv):
977
1842
    """Execute a command.
978
1843
 
979
 
    :param argv: The command-line arguments, without the program name from
980
 
        argv[0] These should already be decoded. All library/test code calling
981
 
        run_bzr should be passing valid strings (don't need decoding).
982
 
    :param load_plugins: What function to call when triggering plugin loading.
983
 
        This function should take no arguments and cause all plugins to be
984
 
        loaded.
985
 
    :param disable_plugins: What function to call when disabling plugin
986
 
        loading. This function should take no arguments and cause all plugin
987
 
        loading to be prohibited (so that code paths in your application that
988
 
        know about some plugins possibly being present will fail to import
989
 
        those plugins even if they are installed.)
990
 
    :return: Returns a command exit code or raises an exception.
 
1844
    This is similar to main(), but without all the trappings for
 
1845
    logging and error handling.  
 
1846
    
 
1847
    argv
 
1848
       The command-line arguments, without the program name from argv[0]
 
1849
    
 
1850
    Returns a command status or raises an exception.
991
1851
 
992
1852
    Special master options: these must come before the command because
993
1853
    they control how the command is interpreted.
995
1855
    --no-plugins
996
1856
        Do not load plugin modules at all
997
1857
 
998
 
    --no-aliases
999
 
        Do not allow aliases
1000
 
 
1001
1858
    --builtin
1002
1859
        Only use builtin commands.  (Plugins are still allowed to change
1003
1860
        other behaviour.)
1004
1861
 
1005
1862
    --profile
1006
 
        Run under the Python hotshot profiler.
1007
 
 
1008
 
    --lsprof
1009
 
        Run under the Python lsprof profiler.
1010
 
 
1011
 
    --coverage
1012
 
        Generate line coverage report in the specified directory.
1013
 
 
1014
 
    --concurrency
1015
 
        Specify the number of processes that can be run concurrently (selftest).
 
1863
        Run under the Python profiler.
1016
1864
    """
1017
 
    trace.mutter("bazaar version: " + bzrlib.__version__)
1018
 
    argv = list(argv)
1019
 
    trace.mutter("bzr arguments: %r", argv)
 
1865
    
 
1866
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
1020
1867
 
1021
 
    opt_lsprof = opt_profile = opt_no_plugins = opt_builtin =  \
1022
 
                opt_no_aliases = False
1023
 
    opt_lsprof_file = opt_coverage_dir = None
 
1868
    opt_profile = opt_no_plugins = opt_builtin = False
1024
1869
 
1025
1870
    # --no-plugins is handled specially at a very early stage. We need
1026
1871
    # to load plugins before doing other command parsing so that they
1027
1872
    # can override commands, but this needs to happen first.
1028
1873
 
1029
 
    argv_copy = []
1030
 
    i = 0
1031
 
    while i < len(argv):
1032
 
        a = argv[i]
 
1874
    for a in argv[:]:
1033
1875
        if a == '--profile':
1034
1876
            opt_profile = True
1035
 
        elif a == '--lsprof':
1036
 
            opt_lsprof = True
1037
 
        elif a == '--lsprof-file':
1038
 
            opt_lsprof = True
1039
 
            opt_lsprof_file = argv[i + 1]
1040
 
            i += 1
1041
1877
        elif a == '--no-plugins':
1042
1878
            opt_no_plugins = True
1043
 
        elif a == '--no-aliases':
1044
 
            opt_no_aliases = True
1045
1879
        elif a == '--builtin':
1046
1880
            opt_builtin = True
1047
 
        elif a == '--concurrency':
1048
 
            os.environ['BZR_CONCURRENCY'] = argv[i + 1]
1049
 
            i += 1
1050
 
        elif a == '--coverage':
1051
 
            opt_coverage_dir = argv[i + 1]
1052
 
            i += 1
1053
 
        elif a.startswith('-D'):
1054
 
            debug.debug_flags.add(a[2:])
1055
1881
        else:
1056
 
            argv_copy.append(a)
1057
 
        i += 1
1058
 
 
1059
 
    debug.set_debug_flags_from_config()
 
1882
            break
 
1883
        argv.remove(a)
1060
1884
 
1061
1885
    if not opt_no_plugins:
 
1886
        from bzrlib.plugin import load_plugins
1062
1887
        load_plugins()
 
1888
 
 
1889
    args, opts = parse_args(argv)
 
1890
 
 
1891
    if 'help' in opts:
 
1892
        from bzrlib.help import help
 
1893
        if args:
 
1894
            help(args[0])
 
1895
        else:
 
1896
            help()
 
1897
        return 0            
 
1898
        
 
1899
    if 'version' in opts:
 
1900
        show_version()
 
1901
        return 0
 
1902
    
 
1903
    if not args:
 
1904
        from bzrlib.help import help
 
1905
        help(None)
 
1906
        return 0
 
1907
    
 
1908
    cmd = str(args.pop(0))
 
1909
 
 
1910
    canonical_cmd, cmd_class = \
 
1911
                   get_cmd_class(cmd, plugins_override=not opt_builtin)
 
1912
 
 
1913
    # check options are reasonable
 
1914
    allowed = cmd_class.takes_options
 
1915
    for oname in opts:
 
1916
        if oname not in allowed:
 
1917
            raise BzrCommandError("option '--%s' is not allowed for command %r"
 
1918
                                  % (oname, cmd))
 
1919
 
 
1920
    # mix arguments and options into one dictionary
 
1921
    cmdargs = _match_argform(cmd, cmd_class.takes_args, args)
 
1922
    cmdopts = {}
 
1923
    for k, v in opts.items():
 
1924
        cmdopts[k.replace('-', '_')] = v
 
1925
 
 
1926
    if opt_profile:
 
1927
        import hotshot, tempfile
 
1928
        pffileno, pfname = tempfile.mkstemp()
 
1929
        try:
 
1930
            prof = hotshot.Profile(pfname)
 
1931
            ret = prof.runcall(cmd_class, cmdopts, cmdargs) or 0
 
1932
            prof.close()
 
1933
 
 
1934
            import hotshot.stats
 
1935
            stats = hotshot.stats.load(pfname)
 
1936
            #stats.strip_dirs()
 
1937
            stats.sort_stats('time')
 
1938
            ## XXX: Might like to write to stderr or the trace file instead but
 
1939
            ## print_stats seems hardcoded to stdout
 
1940
            stats.print_stats(20)
 
1941
            
 
1942
            return ret.status
 
1943
 
 
1944
        finally:
 
1945
            os.close(pffileno)
 
1946
            os.remove(pfname)
1063
1947
    else:
1064
 
        disable_plugins()
1065
 
 
1066
 
    argv = argv_copy
1067
 
    if (not argv):
1068
 
        get_cmd_object('help').run_argv_aliases([])
1069
 
        return 0
1070
 
 
1071
 
    if argv[0] == '--version':
1072
 
        get_cmd_object('version').run_argv_aliases([])
1073
 
        return 0
1074
 
 
1075
 
    alias_argv = None
1076
 
 
1077
 
    if not opt_no_aliases:
1078
 
        alias_argv = get_alias(argv[0])
1079
 
        if alias_argv:
1080
 
            user_encoding = osutils.get_user_encoding()
1081
 
            alias_argv = [a.decode(user_encoding) for a in alias_argv]
1082
 
            argv[0] = alias_argv.pop(0)
1083
 
 
1084
 
    cmd = argv.pop(0)
1085
 
    # We want only 'ascii' command names, but the user may have typed
1086
 
    # in a Unicode name. In that case, they should just get a
1087
 
    # 'command not found' error later.
1088
 
 
1089
 
    cmd_obj = get_cmd_object(cmd, plugins_override=not opt_builtin)
1090
 
    run = cmd_obj.run_argv_aliases
1091
 
    run_argv = [argv, alias_argv]
 
1948
        return cmd_class(cmdopts, cmdargs).status 
 
1949
 
 
1950
 
 
1951
def main(argv):
 
1952
    import bzrlib.ui
 
1953
    bzrlib.trace.log_startup(argv)
 
1954
    bzrlib.ui.ui_factory = bzrlib.ui.TextUIFactory()
1092
1955
 
1093
1956
    try:
1094
 
        # We can be called recursively (tests for example), but we don't want
1095
 
        # the verbosity level to propagate.
1096
 
        saved_verbosity_level = option._verbosity_level
1097
 
        option._verbosity_level = 0
1098
 
        if opt_lsprof:
1099
 
            if opt_coverage_dir:
1100
 
                trace.warning(
1101
 
                    '--coverage ignored, because --lsprof is in use.')
1102
 
            ret = apply_lsprofiled(opt_lsprof_file, run, *run_argv)
1103
 
        elif opt_profile:
1104
 
            if opt_coverage_dir:
1105
 
                trace.warning(
1106
 
                    '--coverage ignored, because --profile is in use.')
1107
 
            ret = apply_profiled(run, *run_argv)
1108
 
        elif opt_coverage_dir:
1109
 
            ret = apply_coveraged(opt_coverage_dir, run, *run_argv)
1110
 
        else:
1111
 
            ret = run(*run_argv)
1112
 
        return ret or 0
1113
 
    finally:
1114
 
        # reset, in case we may do other commands later within the same
1115
 
        # process. Commands that want to execute sub-commands must propagate
1116
 
        # --verbose in their own way.
1117
 
        if 'memory' in debug.debug_flags:
1118
 
            trace.debug_memory('Process status after command:', short=False)
1119
 
        option._verbosity_level = saved_verbosity_level
1120
 
 
1121
 
 
1122
 
def display_command(func):
1123
 
    """Decorator that suppresses pipe/interrupt errors."""
1124
 
    def ignore_pipe(*args, **kwargs):
1125
1957
        try:
1126
 
            result = func(*args, **kwargs)
 
1958
            return run_bzr(argv[1:])
 
1959
        finally:
 
1960
            # do this here inside the exception wrappers to catch EPIPE
1127
1961
            sys.stdout.flush()
1128
 
            return result
1129
 
        except IOError, e:
1130
 
            if getattr(e, 'errno', None) is None:
1131
 
                raise
1132
 
            if e.errno != errno.EPIPE:
1133
 
                # Win32 raises IOError with errno=0 on a broken pipe
1134
 
                if sys.platform != 'win32' or (e.errno not in (0, errno.EINVAL)):
1135
 
                    raise
1136
 
            pass
1137
 
        except KeyboardInterrupt:
1138
 
            pass
1139
 
    return ignore_pipe
1140
 
 
1141
 
 
1142
 
def install_bzr_command_hooks():
1143
 
    """Install the hooks to supply bzr's own commands."""
1144
 
    if _list_bzr_commands in Command.hooks["list_commands"]:
1145
 
        return
1146
 
    Command.hooks.install_named_hook("list_commands", _list_bzr_commands,
1147
 
        "bzr commands")
1148
 
    Command.hooks.install_named_hook("get_command", _get_bzr_command,
1149
 
        "bzr commands")
1150
 
    Command.hooks.install_named_hook("get_command", _get_plugin_command,
1151
 
        "bzr plugin commands")
1152
 
    Command.hooks.install_named_hook("get_command", _get_external_command,
1153
 
        "bzr external command lookup")
1154
 
    Command.hooks.install_named_hook("get_missing_command", _try_plugin_provider,
1155
 
        "bzr plugin-provider-db check")
1156
 
 
1157
 
 
1158
 
 
1159
 
def _specified_or_unicode_argv(argv):
1160
 
    # For internal or testing use, argv can be passed.  Otherwise, get it from
1161
 
    # the process arguments in a unicode-safe way.
1162
 
    if argv is None:
1163
 
        return osutils.get_unicode_argv()
1164
 
    else:
1165
 
        new_argv = []
1166
 
        try:
1167
 
            # ensure all arguments are unicode strings
1168
 
            for a in argv[1:]:
1169
 
                if isinstance(a, unicode):
1170
 
                    new_argv.append(a)
1171
 
                else:
1172
 
                    new_argv.append(a.decode('ascii'))
1173
 
        except UnicodeDecodeError:
1174
 
            raise errors.BzrError("argv should be list of unicode strings.")
1175
 
        return new_argv
1176
 
 
1177
 
 
1178
 
def main(argv=None):
1179
 
    """Main entry point of command-line interface.
1180
 
 
1181
 
    Typically `bzrlib.initialize` should be called first.
1182
 
 
1183
 
    :param argv: list of unicode command-line arguments similar to sys.argv.
1184
 
        argv[0] is script name usually, it will be ignored.
1185
 
        Don't pass here sys.argv because this list contains plain strings
1186
 
        and not unicode; pass None instead.
1187
 
 
1188
 
    :return: exit code of bzr command.
1189
 
    """
1190
 
    argv = _specified_or_unicode_argv(argv)
1191
 
    _register_builtin_commands()
1192
 
    ret = run_bzr_catch_errors(argv)
1193
 
    bzrlib.ui.ui_factory.log_transport_activity(
1194
 
        display=('bytes' in debug.debug_flags))
1195
 
    trace.mutter("return code %d", ret)
1196
 
    return ret
1197
 
 
1198
 
 
1199
 
def run_bzr_catch_errors(argv):
1200
 
    """Run a bzr command with parameters as described by argv.
1201
 
 
1202
 
    This function assumed that that UI layer is setup, that symbol deprecations
1203
 
    are already applied, and that unicode decoding has already been performed on argv.
1204
 
    """
1205
 
    # done here so that they're covered for every test run
1206
 
    install_bzr_command_hooks()
1207
 
    return exception_to_return_code(run_bzr, argv)
1208
 
 
1209
 
 
1210
 
def run_bzr_catch_user_errors(argv):
1211
 
    """Run bzr and report user errors, but let internal errors propagate.
1212
 
 
1213
 
    This is used for the test suite, and might be useful for other programs
1214
 
    that want to wrap the commandline interface.
1215
 
    """
1216
 
    # done here so that they're covered for every test run
1217
 
    install_bzr_command_hooks()
1218
 
    try:
1219
 
        return run_bzr(argv)
 
1962
    except BzrCommandError, e:
 
1963
        # command line syntax error, etc
 
1964
        log_error(str(e))
 
1965
        return 1
 
1966
    except BzrError, e:
 
1967
        bzrlib.trace.log_exception()
 
1968
        return 1
 
1969
    except AssertionError, e:
 
1970
        bzrlib.trace.log_exception('assertion failed: ' + str(e))
 
1971
        return 3
 
1972
    except KeyboardInterrupt, e:
 
1973
        bzrlib.trace.note('interrupted')
 
1974
        return 2
1220
1975
    except Exception, e:
1221
 
        if (isinstance(e, (OSError, IOError))
1222
 
            or not getattr(e, 'internal_error', True)):
1223
 
            trace.report_exception(sys.exc_info(), sys.stderr)
1224
 
            return 3
1225
 
        else:
1226
 
            raise
1227
 
 
1228
 
 
1229
 
class HelpCommandIndex(object):
1230
 
    """A index for bzr help that returns commands."""
1231
 
 
1232
 
    def __init__(self):
1233
 
        self.prefix = 'commands/'
1234
 
 
1235
 
    def get_topics(self, topic):
1236
 
        """Search for topic amongst commands.
1237
 
 
1238
 
        :param topic: A topic to search for.
1239
 
        :return: A list which is either empty or contains a single
1240
 
            Command entry.
1241
 
        """
1242
 
        if topic and topic.startswith(self.prefix):
1243
 
            topic = topic[len(self.prefix):]
1244
 
        try:
1245
 
            cmd = _get_cmd_object(topic, check_missing=False)
1246
 
        except KeyError:
1247
 
            return []
1248
 
        else:
1249
 
            return [cmd]
1250
 
 
1251
 
 
1252
 
class Provider(object):
1253
 
    '''Generic class to be overriden by plugins'''
1254
 
 
1255
 
    def plugin_for_command(self, cmd_name):
1256
 
        '''Takes a command and returns the information for that plugin
1257
 
 
1258
 
        :return: A dictionary with all the available information
1259
 
        for the requested plugin
1260
 
        '''
1261
 
        raise NotImplementedError
1262
 
 
1263
 
 
1264
 
class ProvidersRegistry(registry.Registry):
1265
 
    '''This registry exists to allow other providers to exist'''
1266
 
 
1267
 
    def __iter__(self):
1268
 
        for key, provider in self.iteritems():
1269
 
            yield provider
1270
 
 
1271
 
command_providers_registry = ProvidersRegistry()
 
1976
        import errno
 
1977
        if (isinstance(e, IOError) 
 
1978
            and hasattr(e, 'errno')
 
1979
            and e.errno == errno.EPIPE):
 
1980
            bzrlib.trace.note('broken pipe')
 
1981
            return 2
 
1982
        else:
 
1983
            bzrlib.trace.log_exception()
 
1984
            return 2
 
1985
 
 
1986
 
 
1987
if __name__ == '__main__':
 
1988
    sys.exit(main(sys.argv))