Esempio n. 1
0
    def setUp(self):
        super(TestRegistryIter, self).setUp()

        # We create a registry with "official" objects and "hidden"
        # objects. The later represent the side effects that led to bug #277048
        # and #430510
        _registry = registry.Registry()

        def register_more():
           _registry.register('hidden', None)

        # Avoid closing over self by binding local variable
        self.registry = _registry
        self.registry.register('passive', None)
        self.registry.register('active', register_more)
        self.registry.register('passive-too', None)

        class InvasiveGetter(registry._ObjectGetter):

            def get_obj(inner_self):
                # Surprise ! Getting a registered object (think lazy loaded
                # module) register yet another object !
                _registry.register('more hidden', None)
                return inner_self._obj

        self.registry.register('hacky', None)
        # We peek under the covers because the alternative is to use lazy
        # registration and create a module that can reference our test registry
        # it's too much work for such a corner case -- vila 090916
        self.registry._dict['hacky'] = InvasiveGetter(None)
Esempio n. 2
0
    def test_registry_info(self):
        a_registry = registry.Registry()
        a_registry.register('one', 1, info='string info')
        # We should not have to import the module to return the info
        a_registry.register_lazy('two', 'nonexistent_module', 'member',
                                 info=2)

        # We should be able to handle a callable to get information
        a_registry.register('three', 3, info=['a', 'list'])
        obj = object()
        a_registry.register_lazy('four', 'nonexistent_module', 'member2',
                                 info=obj)
        a_registry.register('five', 5)

        self.assertEqual('string info', a_registry.get_info('one'))
        self.assertEqual(2, a_registry.get_info('two'))
        self.assertEqual(['a', 'list'], a_registry.get_info('three'))
        self.assertIs(obj, a_registry.get_info('four'))
        self.assertIs(None, a_registry.get_info('five'))

        self.assertRaises(KeyError, a_registry.get_info, None)
        self.assertRaises(KeyError, a_registry.get_info, 'six')

        a_registry.default_key = 'one'
        self.assertEqual('string info', a_registry.get_info(None))
        self.assertRaises(KeyError, a_registry.get_info, 'six')

        self.assertEqual([('five', None),
                          ('four', obj),
                          ('one', 'string info'),
                          ('three', ['a', 'list']),
                          ('two', 2),
                         ], sorted((key, a_registry.get_info(key))
                                    for key in a_registry.keys()))
Esempio n. 3
0
    def from_kwargs(name_,
                    help=None,
                    title=None,
                    value_switches=False,
                    enum_switch=True,
                    **kwargs):
        """Convenience method to generate string-map registry options

        name, help, value_switches and enum_switch are passed to the
        RegistryOption constructor.  Any other keyword arguments are treated
        as values for the option, and their value is treated as the help.
        """
        reg = _mod_registry.Registry()
        for name, switch_help in sorted(kwargs.items()):
            name = name.replace('_', '-')
            reg.register(name, name, help=switch_help)
            if not value_switches:
                help = help + '  "' + name + '": ' + switch_help
                if not help.endswith("."):
                    help = help + "."
        return RegistryOption(name_,
                              help,
                              reg,
                              title=title,
                              value_switches=value_switches,
                              enum_switch=enum_switch)
Esempio n. 4
0
 def setUp(self):
     super(TestCaseWithoutPropsHandler, self).setUp()
     # keep a reference to the "current" custom prop. handler registry
     self.properties_handler_registry = \
         log.properties_handler_registry
     # clean up the registry in log
     log.properties_handler_registry = registry.Registry()
Esempio n. 5
0
 def test_normal_get_module(self):
     class AThing(object):
         """Something"""
     a_registry = registry.Registry()
     a_registry.register("obj", AThing())
     self.assertEqual("bzrlib.tests.test_registry",
         a_registry._get_module("obj"))
Esempio n. 6
0
    def test_registry_help(self):
        a_registry = registry.Registry()
        a_registry.register('one', 1, help='help text for one')
        # We should not have to import the module to return the help
        # information
        a_registry.register_lazy('two', 'nonexistent_module', 'member',
                                 help='help text for two')

        # We should be able to handle a callable to get information
        help_calls = []
        def generic_help(reg, key):
            help_calls.append(key)
            return 'generic help for %s' % (key,)
        a_registry.register('three', 3, help=generic_help)
        a_registry.register_lazy('four', 'nonexistent_module', 'member2',
                                 help=generic_help)
        a_registry.register('five', 5)

        def help_from_object(reg, key):
            obj = reg.get(key)
            return obj.help()

        class SimpleObj(object):
            def help(self):
                return 'this is my help'
        a_registry.register('six', SimpleObj(), help=help_from_object)

        self.assertEqual('help text for one', a_registry.get_help('one'))
        self.assertEqual('help text for two', a_registry.get_help('two'))
        self.assertEqual('generic help for three',
                         a_registry.get_help('three'))
        self.assertEqual(['three'], help_calls)
        self.assertEqual('generic help for four',
                         a_registry.get_help('four'))
        self.assertEqual(['three', 'four'], help_calls)
        self.assertEqual(None, a_registry.get_help('five'))
        self.assertEqual('this is my help', a_registry.get_help('six'))

        self.assertRaises(KeyError, a_registry.get_help, None)
        self.assertRaises(KeyError, a_registry.get_help, 'seven')

        a_registry.default_key = 'one'
        self.assertEqual('help text for one', a_registry.get_help(None))
        self.assertRaises(KeyError, a_registry.get_help, 'seven')

        self.assertEqual([('five', None),
                          ('four', 'generic help for four'),
                          ('one', 'help text for one'),
                          ('six', 'this is my help'),
                          ('three', 'generic help for three'),
                          ('two', 'help text for two'),
                         ], sorted((key, a_registry.get_help(key))
                                    for key in a_registry.keys()))

        # We don't know what order it was called in, but we should get
        # 2 more calls to three and four
        self.assertEqual(['four', 'four', 'three', 'three'],
                         sorted(help_calls))
 def test_short_value_switches(self):
     reg = registry.Registry()
     reg.register('short', 'ShortChoice')
     reg.register('long', 'LongChoice')
     ropt = option.RegistryOption('choice', '', reg, value_switches=True,
         short_value_switches={'short': 's'})
     opts, args = parse([ropt], ['--short'])
     self.assertEqual('ShortChoice', opts.choice)
     opts, args = parse([ropt], ['-s'])
     self.assertEqual('ShortChoice', opts.choice)
Esempio n. 8
0
 def test_get_prefix(self):
     my_registry = registry.Registry()
     http_object = object()
     sftp_object = object()
     my_registry.register('http:', http_object)
     my_registry.register('sftp:', sftp_object)
     found_object, suffix = my_registry.get_prefix('http://foo/bar')
     self.assertEqual('//foo/bar', suffix)
     self.assertIs(http_object, found_object)
     self.assertIsNot(sftp_object, found_object)
     found_object, suffix = my_registry.get_prefix('sftp://baz/qux')
     self.assertEqual('//baz/qux', suffix)
     self.assertIs(sftp_object, found_object)
Esempio n. 9
0
    def test_registry_funcs(self):
        a_registry = registry.Registry()
        self.register_stuff(a_registry)

        self.failUnless('one' in a_registry)
        a_registry.remove('one')
        self.failIf('one' in a_registry)
        self.assertRaises(KeyError, a_registry.get, 'one')

        a_registry.register('one', 'one')

        self.assertEqual(['five', 'four', 'one', 'two'],
                         sorted(a_registry.keys()))
        self.assertEqual([('five', 5), ('four', 4), ('one', 'one'),
                          ('two', 2)], sorted(a_registry.iteritems()))
Esempio n. 10
0
    def test_register_override(self):
        a_registry = registry.Registry()
        a_registry.register('one', 'one')
        self.assertRaises(KeyError, a_registry.register, 'one', 'two')
        self.assertRaises(KeyError, a_registry.register, 'one', 'two',
                                    override_existing=False)

        a_registry.register('one', 'two', override_existing=True)
        self.assertEqual('two', a_registry.get('one'))

        self.assertRaises(KeyError, a_registry.register_lazy,
                          'one', 'three', 'four')

        a_registry.register_lazy('one', 'module', 'member',
                                 override_existing=True)
Esempio n. 11
0
    def test_lazy_import_registry(self):
        plugin_name = self.create_simple_plugin()
        a_registry = registry.Registry()
        a_registry.register_lazy('obj', plugin_name, 'object1')
        a_registry.register_lazy('function', plugin_name, 'function')
        a_registry.register_lazy('klass', plugin_name, 'MyClass')
        a_registry.register_lazy('module', plugin_name, None)

        self.assertEqual(['function', 'klass', 'module', 'obj'],
                         sorted(a_registry.keys()))
        # The plugin should not be loaded until we grab the first object
        self.assertFalse(plugin_name in sys.modules)

        # By default the plugin won't be in the search path
        self.assertRaises(ImportError, a_registry.get, 'obj')

        plugin_path = os.getcwd() + '/tmp'
        sys.path.append(plugin_path)
        try:
            obj = a_registry.get('obj')
            self.assertEqual('foo', obj)
            self.assertTrue(plugin_name in sys.modules)

            # Now grab another object
            func = a_registry.get('function')
            self.assertEqual(plugin_name, func.__module__)
            self.assertEqual('function', func.__name__)
            self.assertEqual((1, [], '3'), func(1, [], '3'))

            # And finally a class
            klass = a_registry.get('klass')
            self.assertEqual(plugin_name, klass.__module__)
            self.assertEqual('MyClass', klass.__name__)

            inst = klass(1)
            self.assertIsInstance(inst, klass)
            self.assertEqual(1, inst.a)

            module = a_registry.get('module')
            self.assertIs(obj, module.object1)
            self.assertIs(func, module.function)
            self.assertIs(klass, module.MyClass)
        finally:
            sys.path.remove(plugin_path)
Esempio n. 12
0
    def test_registry_option_value_switches_hidden(self):
        reg = registry.Registry()

        class Hider(object):
            hidden = True

        reg.register("new", 1, "Current.")
        reg.register("old", 0, "Legacy.", info=Hider())
        opt = option.RegistryOption("protocol",
                                    "Talking.",
                                    reg,
                                    value_switches=True,
                                    enum_switch=False)
        pot = self.pot_from_option(opt)
        self.assertContainsString(
            pot, "\n"
            "# help of 'protocol' test\n"
            "msgid \"Talking.\"\n")
        self.assertContainsString(
            pot, "\n"
            "# help of 'protocol=new' test\n"
            "msgid \"Current.\"\n")
        self.assertNotContainsString(pot, "'protocol=old'")
Esempio n. 13
0
    def test_registry(self):
        a_registry = registry.Registry()
        self.register_stuff(a_registry)

        self.assertTrue(a_registry.default_key is None)

        # test get() (self.default_key is None)
        self.assertRaises(KeyError, a_registry.get)
        self.assertRaises(KeyError, a_registry.get, None)
        self.assertEqual(2, a_registry.get('two'))
        self.assertRaises(KeyError, a_registry.get, 'three')

        # test _set_default_key
        a_registry.default_key = 'five'
        self.assertTrue(a_registry.default_key == 'five')
        self.assertEqual(5, a_registry.get())
        self.assertEqual(5, a_registry.get(None))
        # If they ask for a specific entry, they should get KeyError
        # not the default value. They can always pass None if they prefer
        self.assertRaises(KeyError, a_registry.get, 'six')
        self.assertRaises(KeyError, a_registry._set_default_key, 'six')

        # test keys()
        self.assertEqual(['five', 'four', 'one', 'two'], a_registry.keys())
Esempio n. 14
0
        if self._working_tree is not None:
            return self._working_tree.last_revision()
        return self._branch.last_revision()

    def generate(self, to_file):
        """Output the version information to the supplied file.

        :param to_file: The file to write the stream to. The output
                will already be encoded, so to_file should not try
                to change encodings.
        :return: None
        """
        raise NotImplementedError(VersionInfoBuilder.generate)


format_registry = registry.Registry()


format_registry.register_lazy(
    'rio',
    'bzrlib.version_info_formats.format_rio',
    'RioVersionInfoBuilder',
    'Version info in RIO (simple text) format (default).')
format_registry.default_key = 'rio'
format_registry.register_lazy(
    'python',
    'bzrlib.version_info_formats.format_python',
    'PythonVersionInfoBuilder',
    'Version info in Python format.')
format_registry.register_lazy(
    'custom',
Esempio n. 15
0
#           use the lock, because you don't have the lock token. Calling lock
#           again will fail, because the lock is already taken. However, we
#           can't tell if the server received our request or not. If it didn't,
#           then retrying the request is fine, as it will actually do what we
#           want. If it did, we will interrupt the current operation, but we
#           are no worse off than interrupting the current operation because of
#           a ConnectionReset.
#   semivfs Similar to semi, but specific to a Virtual FileSystem request.
#   stream  This is a request that takes a stream that cannot be restarted if
#           consumed. This request is 'safe' in that if we determine the
#           connection is closed before we consume the stream, we can try
#           again.
#   mutate  State is updated in a way that replaying that request results in a
#           different state. For example 'append' writes more bytes to a given
#           file. If append succeeds, it moves the file pointer.
request_handlers = registry.Registry()
request_handlers.register_lazy('append',
                               'bzrlib.smart.vfs',
                               'AppendRequest',
                               info='mutate')
request_handlers.register_lazy('Branch.break_lock',
                               'bzrlib.smart.branch',
                               'SmartServerBranchBreakLock',
                               info='idem')
request_handlers.register_lazy('Branch.get_config_file',
                               'bzrlib.smart.branch',
                               'SmartServerBranchGetConfigFile',
                               info='read')
request_handlers.register_lazy('Branch.get_parent',
                               'bzrlib.smart.branch',
                               'SmartServerBranchGetParent',
Esempio n. 16
0
            raise errors.InvalidRevisionSpec(self.user_spec, context_branch)
        return result


# The order in which we want to DWIM a revision spec without any prefix.
# revno is always tried first and isn't listed here, this is used by
# RevisionSpec_dwim._match_on
dwim_revspecs = symbol_versioning.deprecated_list(
    symbol_versioning.deprecated_in((2, 4, 0)), "dwim_revspecs", [])

RevisionSpec_dwim.append_possible_revspec(RevisionSpec_tag)
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_revid)
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_date)
RevisionSpec_dwim.append_possible_revspec(RevisionSpec_branch)

revspec_registry = registry.Registry()


def _register_revspec(revspec):
    revspec_registry.register(revspec.prefix, revspec)


_register_revspec(RevisionSpec_revno)
_register_revspec(RevisionSpec_revid)
_register_revspec(RevisionSpec_last)
_register_revspec(RevisionSpec_before)
_register_revspec(RevisionSpec_tag)
_register_revspec(RevisionSpec_date)
_register_revspec(RevisionSpec_ancestor)
_register_revspec(RevisionSpec_branch)
_register_revspec(RevisionSpec_submit)
Esempio n. 17
0
 def setUp(self):
     super(TestVersionInfoFormatRegistry, self).setUp()
     self.overrideAttr(version_info_formats,
                       'format_registry', registry.Registry())
Esempio n. 18
0
                          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')


resolve_action_registry = registry.Registry()


resolve_action_registry.register(
    'done', 'done', 'Marks the conflict as resolved.')
resolve_action_registry.register(
    'take-this', 'take_this',
    'Resolve the conflict preserving the version in the working tree.')
resolve_action_registry.register(
    'take-other', 'take_other',
    'Resolve the conflict taking the merged version into account.')
resolve_action_registry.default_key = 'done'

class ResolveActionOption(option.RegistryOption):

    def __init__(self):
Esempio n. 19
0
class AliasDirectory(object):
    """Directory lookup for locations associated with a branch.

    :parent, :submit, :public, :push, :this, and :bound are currently
    supported.  On error, a subclass of DirectoryLookupFailure will be raised.
    """

    branch_aliases = registry.Registry()
    branch_aliases.register('parent',
                            lambda b: b.get_parent(),
                            help="The parent of this branch.")
    branch_aliases.register('submit',
                            lambda b: b.get_submit_branch(),
                            help="The submit branch for this branch.")
    branch_aliases.register('public',
                            lambda b: b.get_public_branch(),
                            help="The public location of this branch.")
    branch_aliases.register(
        'bound',
        lambda b: b.get_bound_location(),
        help="The branch this branch is bound to, for bound branches.")
    branch_aliases.register(
        'push',
        lambda b: b.get_push_location(),
        help="The saved location used for `bzr push` with no arguments.")
    branch_aliases.register('this', lambda b: b.base, help="This branch.")

    def look_up(self, name, url):
        branch = _mod_branch.Branch.open_containing('.')[0]
        parts = url.split('/', 1)
        if len(parts) == 2:
            name, extra = parts
        else:
            (name, ) = parts
            extra = None
        try:
            method = self.branch_aliases.get(name[1:])
        except KeyError:
            raise errors.InvalidLocationAlias(url)
        else:
            result = method(branch)
        if result is None:
            raise errors.UnsetLocationAlias(url)
        if extra is not None:
            result = urlutils.join(result, extra)
        return result

    @classmethod
    def help_text(cls, topic):
        alias_lines = []
        for key in cls.branch_aliases.keys():
            help = cls.branch_aliases.get_help(key)
            alias_lines.append("  :%-10s%s\n" % (key, help))
        return """\
Location aliases
================

Bazaar defines several aliases for locations associated with a branch.  These
can be used with most commands that expect a location, such as `bzr push`.

The aliases are::

%s
For example, to push to the parent location::

    bzr push :parent
""" % "".join(alias_lines)
Esempio n. 20
0
                        short_value_switches={'short': 'S'})
_global_registry_option('merge-type',
                        'Select a particular merge algorithm.',
                        lazy_registry=('bzrlib.merge', 'merge_type_registry'),
                        value_switches=True,
                        title='Merge algorithm')
_global_option('message', type=unicode, short_name='m', help='Message string.')
_global_option('null',
               short_name='0',
               help='Use an ASCII NUL (\\0) separator rather than '
               'a newline.')
_global_option('overwrite',
               help='Ignore differences between branches and '
               'overwrite unconditionally.')
_global_option('remember',
               help='Remember the specified location as a'
               ' default.')
_global_option('reprocess', help='Reprocess to reduce spurious conflicts.')
_global_option('revision',
               type=_parse_revision_str,
               short_name='r',
               help='See "help revisionspec" for details.')
_global_option('show-ids', help='Show internal object ids.')
_global_option('timezone',
               type=str,
               help='Display timezone as local, original, or utc.')

diff_writer_registry = _mod_registry.Registry()
diff_writer_registry.register('plain', lambda x: x, 'Plaintext diff output.')
diff_writer_registry.default_key = 'plain'
Esempio n. 21
0
 def test_lazy_import_registry_foo(self):
     a_registry = registry.Registry()
     a_registry.register_lazy('foo', 'bzrlib.branch', 'Branch')
     a_registry.register_lazy('bar', 'bzrlib.branch', 'Branch.hooks')
     self.assertEqual(branch.Branch, a_registry.get('foo'))
     self.assertEqual(branch.Branch.hooks, a_registry.get('bar'))
Esempio n. 22
0
 def test_lazy_import_get_module(self):
     a_registry = registry.Registry()
     a_registry.register_lazy('obj', "bzrlib.tests.test_registry",
         'object1')
     self.assertEqual("bzrlib.tests.test_registry",
         a_registry._get_module("obj"))
Esempio n. 23
0
            break

    if base_idx is None:
        to_file.write('Nothing seems to have changed\n')
        return
    ## TODO: It might be nice to do something like show_log
    ##       and show the merged entries. But since this is the
    ##       removed revisions, it shouldn't be as important
    if base_idx < len(old_rh):
        to_file.write('*'*60)
        to_file.write('\nRemoved Revisions:\n')
        for i in range(base_idx, len(old_rh)):
            rev = branch.repository.get_revision(old_rh[i])
            lr = LogRevision(rev, i+1, 0, None)
            lf.log_revision(lr)
        to_file.write('*'*60)
        to_file.write('\n\n')
    if base_idx < len(new_rh):
        to_file.write('Added Revisions:\n')
        show_log(branch,
                 lf,
                 None,
                 verbose=False,
                 direction='forward',
                 start_revision=base_idx+1,
                 end_revision=len(new_rh),
                 search=None)


properties_handler_registry = registry.Registry()