def test_iter_switches(self):
     opt = option.Option('hello', help='fg')
     self.assertEqual(list(opt.iter_switches()),
                      [('hello', None, None, 'fg')])
     opt = option.Option('hello', help='fg', type=int)
     self.assertEqual(list(opt.iter_switches()),
                      [('hello', None, 'ARG', 'fg')])
     opt = option.Option('hello', help='fg', type=int, argname='gar')
     self.assertEqual(list(opt.iter_switches()),
                      [('hello', None, 'GAR', 'fg')])
     registry = controldir.ControlDirFormatRegistry()
     bzrdir.register_metadir(registry, 'one', 'RepositoryFormat7', 'one help')
     bzrdir.register_metadir(registry, 'two',
             'bzrlib.repofmt.knitrepo.RepositoryFormatKnit1',
             'two help',
             )
     registry.set_default('one')
     opt = option.RegistryOption('format', 'format help', registry,
                                 value_switches=False)
     self.assertEqual(list(opt.iter_switches()),
                      [('format', None, 'ARG', 'format help')])
     opt = option.RegistryOption('format', 'format help', registry,
                                 value_switches=True)
     self.assertEqual(list(opt.iter_switches()),
                      [('format', None, 'ARG', 'format help'),
                       ('default', None, None, 'one help'),
                       ('one', None, None, 'one help'),
                       ('two', None, None, 'two help'),
                       ])
 def test_override(self):
     options = [option.Option('hello', type=str),
                option.Option('hi', type=str, param_name='hello')]
     opts, args = self.parse(options, ['--hello', 'a', '--hello', 'b'])
     self.assertEqual('b', opts.hello)
     opts, args = self.parse(options, ['--hello', 'b', '--hello', 'a'])
     self.assertEqual('a', opts.hello)
     opts, args = self.parse(options, ['--hello', 'a', '--hi', 'b'])
     self.assertEqual('b', opts.hello)
     opts, args = self.parse(options, ['--hi', 'b', '--hello', 'a'])
     self.assertEqual('a', opts.hello)
 def test_conversion(self):
     options = [option.Option('hello')]
     opts, args = self.parse(options, ['--no-hello', '--hello'])
     self.assertEqual(True, opts.hello)
     opts, args = self.parse(options, [])
     self.assertFalse(hasattr(opts, 'hello'))
     opts, args = self.parse(options, ['--hello', '--no-hello'])
     self.assertEqual(False, opts.hello)
     options = [option.Option('number', type=int)]
     opts, args = self.parse(options, ['--number', '6'])
     self.assertEqual(6, opts.number)
     self.assertRaises(errors.BzrCommandError, self.parse, options,
                       ['--number'])
     self.assertRaises(errors.BzrCommandError, self.parse, options,
                       ['--no-number'])
示例#4
0
class cmd_conflicts(commands.Command):
    __doc__ = """List files with conflicts.

    Merge will do its best to combine the changes in two branches, but there
    are some kinds of problems only a human can fix.  When it encounters those,
    it will mark a conflict.  A conflict means that you need to fix something,
    before you can commit.

    Conflicts normally are listed as short, human-readable messages.  If --text
    is supplied, the pathnames of files with text conflicts are listed,
    instead.  (This is useful for editing all files with text conflicts.)

    Use bzr resolve when you have fixed a problem.
    """
    takes_options = [
            'directory',
            option.Option('text',
                          help='List paths of files with text conflicts.'),
        ]
    _see_also = ['resolve', 'conflict-types']

    def run(self, text=False, directory=u'.'):
        wt = workingtree.WorkingTree.open_containing(directory)[0]
        for conflict in wt.conflicts():
            if text:
                if conflict.typestring != 'text conflict':
                    continue
                self.outf.write(conflict.path + '\n')
            else:
                self.outf.write(unicode(conflict) + '\n')
示例#5
0
class cmd_test_script(commands.Command):
    """Run a shell-like test from a file."""

    hidden = True
    takes_args = ['infile']
    takes_options = [
        option.Option('null-output',
                      help='Null command outputs match any output.'),
    ]

    @commands.display_command
    def run(self, infile, null_output=False):
        # local imports to defer testtools dependency
        from bzrlib import tests
        from bzrlib.tests.script import TestCaseWithTransportAndScript

        f = open(infile)
        try:
            script = f.read()
        finally:
            f.close()

        class Test(TestCaseWithTransportAndScript):

            script = None  # Set before running

            def test_it(self):
                self.run_script(script,
                                null_output_matches_anything=null_output)

        runner = tests.TextTestRunner(stream=self.outf)
        test = Test('test_it')
        test.path = os.path.realpath(infile)
        res = runner.run(test)
        return len(res.errors) + len(res.failures)
示例#6
0
 def test_option_context_string(self):
     s = "Literally."
     context = export_pot._ModuleContext("local.py", 3, ({}, {s: 17}))
     opt = option.Option("example", help=s)
     self.assertContainsString(
         self.pot_from_option(opt, context), "#: local.py:17\n"
         "# help of 'example' test\n")
示例#7
0
class cmd_bash_completion(commands.Command):
    __doc__ = """Generate a shell function for bash command line completion.

    This command generates a shell function which can be used by bash to
    automatically complete the currently typed command when the user presses
    the completion key (usually tab).
    
    Commonly used like this:
        eval "`bzr bash-completion`"
    """

    takes_options = [
        option.Option("function-name",
                      short_name="f",
                      type=str,
                      argname="name",
                      help="Name of the generated function (default: _bzr)"),
        option.Option(
            "function-only",
            short_name="o",
            type=None,
            help="Generate only the shell function, don't enable it"),
        option.Option("debug",
                      type=None,
                      hidden=True,
                      help="Enable shell code useful for debugging"),
        option.ListOption(
            "plugin",
            type=str,
            argname="name",
            # param_name="selected_plugins", # doesn't work, bug #387117
            help="Enable completions for the selected plugin" +
            " (default: all plugins)"),
    ]

    def run(self, **kwargs):
        if 'plugin' in kwargs:
            # work around bug #387117 which prevents us from using param_name
            if len(kwargs['plugin']) > 0:
                kwargs['selected_plugins'] = kwargs['plugin']
            del kwargs['plugin']
        bash_completion_function(sys.stdout, **kwargs)
 def test_option_callback_bool(self):
     "Test booleans get True and False passed correctly to a callback."""
     cb_calls = []
     def cb(option, name, value, parser):
         cb_calls.append((option,name,value,parser))
     options = [option.Option('hello', custom_callback=cb)]
     opts, args = self.parse(options, ['--hello', '--no-hello'])
     self.assertEqual(2, len(cb_calls))
     opt,name,value,parser = cb_calls[0]
     self.assertEqual('hello', name)
     self.assertTrue(value)
     opt,name,value,parser = cb_calls[1]
     self.assertEqual('hello', name)
     self.assertFalse(value)
 def test_option_callback_str(self):
     """Test callbacks work for string options both long and short."""
     cb_calls = []
     def cb(option, name, value, parser):
         cb_calls.append((option,name,value,parser))
     options = [option.Option('hello', type=str, custom_callback=cb,
         short_name='h')]
     opts, args = self.parse(options, ['--hello', 'world', '-h', 'mars'])
     self.assertEqual(2, len(cb_calls))
     opt,name,value,parser = cb_calls[0]
     self.assertEqual('hello', name)
     self.assertEqual('world', value)
     opt,name,value,parser = cb_calls[1]
     self.assertEqual('hello', name)
     self.assertEqual('mars', value)
示例#10
0
class cmd_diff(builtins.cmd_diff):
  """
  The '--using TOOL' option can be used to run an external diff tool.

  Some examples of supported diff tools include 'kdiff3', 'kompare', 
  'meld', 'vimdiff', and 'xxdiff'.  Other external diff tools are likely
  to work as well, as long as their basic arguments are in the same form
  as 'diff'.
  
  Most of these tools allow merging or editing, so they can be used to
  change the working copy, but this should be done carefully.  Changes 
  to temporary files will not be saved.
  
  External diff tools may need customization to filter out the '.bzr'
  control files.
  """

  # Add a new option to the builtin 'diff' command:
  takes_options = builtins.cmd_diff.takes_options + [
           option.Option('using', type=str, help='Use alternate diff tool.')]

  # Override the inherited run() and help() methods:

  def run(self, *args, **kwargs):
    """
    Choose which diff tool (external or builtin) to run.
    """
    from controller import Controller
    if 'using' in kwargs:
      # Run the specified external diff tool:
      return Controller().run(*args, **kwargs)
    else:
      # Run the builtin diff command normally:
      return super(cmd_diff, self).run(*args, **kwargs)


  def help(self):
    """
    Return help message for this class, including text from superclass.
    """
    from inspect import getdoc
    return getdoc(super(cmd_diff, self)) + '\n\n' + getdoc(self)
示例#11
0
 def test_set_short_name(self):
     o = option.Option('wiggle')
     o.set_short_name('w')
     self.assertEqual(o.short_name(), 'w')
示例#12
0
 def test_option_with_help(self):
     opt = option.Option("helpful", help="Info.")
     self.assertContainsString(
         self.pot_from_option(opt), "\n"
         "# help of 'helpful' test\n"
         "msgid \"Info.\"\n")
示例#13
0
 def test_help_not_hidden(self):
     c = self.get_command([option.Option('foo', hidden=False)])
     self.assertContainsRe(c.get_help_text(), '--foo')
示例#14
0
 def test_option_context_missing(self):
     context = export_pot._ModuleContext("remote.py", 3)
     opt = option.Option("metaphor", help="Not a literal in the source.")
     self.assertContainsString(
         self.pot_from_option(opt, context), "#: remote.py:3\n"
         "# help of 'metaphor' test\n")
示例#15
0
 def test_option_hidden(self):
     opt = option.Option("hidden", help="Unseen.", hidden=True)
     self.assertEqual("", self.pot_from_option(opt))
示例#16
0
class cmd_resolve(commands.Command):
    __doc__ = """Mark a conflict as resolved.

    Merge will do its best to combine the changes in two branches, but there
    are some kinds of problems only a human can fix.  When it encounters those,
    it will mark a conflict.  A conflict means that you need to fix something,
    before you can commit.

    Once you have fixed a problem, use "bzr resolve" to automatically mark
    text conflicts as fixed, "bzr resolve FILE" to mark a specific conflict as
    resolved, or "bzr resolve --all" to mark all conflicts as resolved.
    """
    aliases = ['resolved']
    takes_args = ['file*']
    takes_options = [
            'directory',
            option.Option('all', help='Resolve all conflicts in this tree.'),
            ResolveActionOption(),
            ]
    _see_also = ['conflicts']
    def run(self, file_list=None, all=False, action=None, directory=None):
        if all:
            if file_list:
                raise errors.BzrCommandError(gettext("If --all is specified,"
                                             " no FILE may be provided"))
            if directory is None:
                directory = u'.'
            tree = workingtree.WorkingTree.open_containing(directory)[0]
            if action is None:
                action = 'done'
        else:
            tree, file_list = workingtree.WorkingTree.open_containing_paths(
                file_list, directory)
            if file_list is None:
                if action is None:
                    # FIXME: There is a special case here related to the option
                    # handling that could be clearer and easier to discover by
                    # providing an --auto action (bug #344013 and #383396) and
                    # make it mandatory instead of implicit and active only
                    # when no file_list is provided -- vila 091229
                    action = 'auto'
            else:
                if action is None:
                    action = 'done'
        if action == 'auto':
            if file_list is None:
                un_resolved, resolved = tree.auto_resolve()
                if len(un_resolved) > 0:
                    trace.note(ngettext('%d conflict auto-resolved.',
                        '%d conflicts auto-resolved.', len(resolved)),
                        len(resolved))
                    trace.note(gettext('Remaining conflicts:'))
                    for conflict in un_resolved:
                        trace.note(unicode(conflict))
                    return 1
                else:
                    trace.note(gettext('All conflicts resolved.'))
                    return 0
            else:
                # FIXME: This can never occur but the block above needs some
                # refactoring to transfer tree.auto_resolve() to
                # conflict.auto(tree) --vila 091242
                pass
        else:
            before, after = resolve(tree, file_list, action=action)
            trace.note(ngettext('{0} conflict resolved, {1} remaining',
                                '{0} conflicts resolved, {1} remaining',
                                before-after).format(before - after, after))
示例#17
0
 def test_is_hidden(self):
     self.assertTrue(option.Option('foo', hidden=True).is_hidden('foo'))
     self.assertFalse(option.Option('foo', hidden=False).is_hidden('foo'))
示例#18
0
class cmd_upload(commands.Command):
    """Upload a working tree, as a whole or incrementally.

    If no destination is specified use the last one used.
    If no revision is specified upload the changes since the last upload.

    Changes include files added, renamed, modified or removed.
    """
    takes_args = ['location?']
    takes_options = [
        'revision', 'remember',
        option.Option('full', 'Upload the full working tree.'),
        option.Option('quiet',
                      'Do not output what is being done.',
                      short_name='q'),
        option.Option(
            'directory',
            help='Branch to upload from, '
            'rather than the one containing the working directory.',
            short_name='d',
            type=unicode,
        ),
        option.Option(
            'auto', 'Trigger an upload from this branch whenever the tip '
            'revision changes.')
    ]

    def run(self,
            location=None,
            full=False,
            revision=None,
            remember=None,
            directory=None,
            quiet=False,
            auto=None):
        if directory is None:
            directory = u'.'

        if auto and not auto_hook_available:
            raise BzrCommandError("Your version of bzr does not have the "
                                  "hooks necessary for --auto to work")

        (wt, branch,
         relpath) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)

        if wt:
            changes = wt.changes_from(wt.basis_tree())

            if revision is None and changes.has_changed():
                raise errors.UncommittedChanges(wt)

        if location is None:
            stored_loc = get_upload_location(branch)
            if stored_loc is None:
                raise errors.BzrCommandError('No upload location'
                                             ' known or specified.')
            else:
                # FIXME: Not currently tested
                display_url = urlutils.unescape_for_display(
                    stored_loc, self.outf.encoding)
                self.outf.write("Using saved location: %s\n" % display_url)
                location = stored_loc

        to_transport = transport.get_transport(location)

        # Check that we are not uploading to a existing working tree.
        try:
            to_bzr_dir = bzrdir.BzrDir.open_from_transport(to_transport)
            has_wt = to_bzr_dir.has_workingtree()
        except errors.NotBranchError:
            has_wt = False
        except errors.NotLocalUrl:
            # The exception raised is a bit weird... but that's life.
            has_wt = True

        if has_wt:
            raise CannotUploadToWorkingTreeError(url=location)

        if revision is None:
            rev_id = branch.last_revision()
        else:
            if len(revision) != 1:
                raise errors.BzrCommandError(
                    'bzr upload --revision takes exactly 1 argument')
            rev_id = revision[0].in_history(branch).rev_id

        tree = branch.repository.revision_tree(rev_id)

        uploader = BzrUploader(branch,
                               to_transport,
                               self.outf,
                               tree,
                               rev_id,
                               quiet=quiet)

        if full:
            uploader.upload_full_tree()
        else:
            uploader.upload_tree()

        # We uploaded successfully, remember it
        if get_upload_location(branch) is None or remember:
            set_upload_location(branch, to_transport.base)
        if auto is not None:
            set_upload_auto(branch, auto)
示例#19
0
 def test_option_without_help(self):
     opt = option.Option("helpless")
     self.assertEqual("", self.pot_from_option(opt))