Example #1
0
 def test__ensure_unicode_deprecated(self):
     s = "text"
     u1 = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
         win32utils._ensure_unicode, s)
     self.assertEqual(s, u1)
     self.assertIsInstance(u1, unicode)
     u2 = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
         win32utils._ensure_unicode, u1)
     self.assertIs(u1, u2)
Example #2
0
 def test__ensure_unicode_deprecated(self):
     s = "text"
     u1 = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
         win32utils._ensure_unicode, s)
     self.assertEqual(s, u1)
     self.assertIsInstance(u1, unicode)
     u2 = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
         win32utils._ensure_unicode, u1)
     self.assertIs(u1, u2)
 def test_deprecation_string(self):
     """We can get a deprecation string for a method or function."""
     self.assertEqual('bzrlib.tests.test_symbol_versioning.'
         'TestDeprecationWarnings.test_deprecation_string was deprecated in '
         'version 0.11.0.',
         symbol_versioning.deprecation_string(
         self.test_deprecation_string,
         deprecated_in((0, 11, 0))))
     self.assertEqual('bzrlib.symbol_versioning.deprecated_function was '
         'deprecated in version 0.11.0.',
         symbol_versioning.deprecation_string(
             symbol_versioning.deprecated_function,
             deprecated_in((0, 11, 0))))
Example #4
0
 def test___contains__(self):
     work_tree = self.make_branch_and_tree('tree')
     self.build_tree(['tree/file'])
     work_tree.add('file', 'file-id')
     tree = self._convert_tree(work_tree)
     tree.lock_read()
     self.addCleanup(tree.unlock)
     self.assertTrue(
         self.applyDeprecated(deprecated_in((2, 4, 0)), tree.__contains__,
                              'file-id'))
     self.assertFalse(
         self.applyDeprecated(deprecated_in((2, 4, 0)), tree.__contains__,
                              'dir-id'))
Example #5
0
 def test_deprecation_string(self):
     """We can get a deprecation string for a method or function."""
     self.assertEqual(
         'bzrlib.tests.test_symbol_versioning.'
         'TestDeprecationWarnings.test_deprecation_string was deprecated in '
         'version 0.11.0.',
         symbol_versioning.deprecation_string(self.test_deprecation_string,
                                              deprecated_in((0, 11, 0))))
     self.assertEqual(
         'bzrlib.symbol_versioning.deprecated_function was '
         'deprecated in version 0.11.0.',
         symbol_versioning.deprecation_string(
             symbol_versioning.deprecated_function, deprecated_in(
                 (0, 11, 0))))
Example #6
0
    def test_get_revision_delta(self):
        tree_a = self.make_branch_and_tree("a")
        self.build_tree(["a/foo"])
        tree_a.add("foo", "file1")
        tree_a.commit("rev1", rev_id="rev1")
        self.build_tree(["a/vla"])
        tree_a.add("vla", "file2")
        tree_a.commit("rev2", rev_id="rev2")

        delta = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)), tree_a.branch.get_revision_delta, 1)
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
        self.assertEqual([("foo", "file1", "file")], delta.added)
        delta = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)), tree_a.branch.get_revision_delta, 2)
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
        self.assertEqual([("vla", "file2", "file")], delta.added)
Example #7
0
 def test___contains__(self):
     work_tree = self.make_branch_and_tree('tree')
     self.build_tree(['tree/file'])
     work_tree.add('file', 'file-id')
     tree = self._convert_tree(work_tree)
     tree.lock_read()
     self.addCleanup(tree.unlock)
     self.assertTrue(
         self.applyDeprecated(
             deprecated_in((2, 4, 0)),
             tree.__contains__, 'file-id'))
     self.assertFalse(
         self.applyDeprecated(
             deprecated_in((2, 4, 0)),
             tree.__contains__, 'dir-id'))
Example #8
0
 def test_host_unicode_deprecated(self):
     self.overrideEnv("COMPUTERNAME", "alienbox")
     s = win32utils.get_host_name()
     u = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
         win32utils.get_host_name_unicode)
     self.assertEqual(s, u)
     self.assertIsInstance(s, unicode)
Example #9
0
 def test_appdata_unicode_deprecated(self):
     self.overrideEnv("APPDATA", "fakepath")
     s = win32utils.get_appdata_location()
     u = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
         win32utils.get_appdata_location_unicode)
     self.assertEqual(s, u)
     self.assertIsInstance(s, unicode)
Example #10
0
 def test_host_unicode_deprecated(self):
     self.overrideEnv("COMPUTERNAME", "alienbox")
     s = win32utils.get_host_name()
     u = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
         win32utils.get_host_name_unicode)
     self.assertEqual(s, u)
     self.assertIsInstance(s, unicode)
Example #11
0
 def test_appdata_unicode_deprecated(self):
     self.overrideEnv("APPDATA", "fakepath")
     s = win32utils.get_appdata_location()
     u = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
         win32utils.get_appdata_location_unicode)
     self.assertEqual(s, u)
     self.assertIsInstance(s, unicode)
Example #12
0
 def assertToGzip(self, chunks):
     bytes = ''.join(chunks)
     gzfromchunks = tuned_gzip.chunks_to_gzip(chunks)
     gzfrombytes = tuned_gzip.bytes_to_gzip(bytes)
     self.assertEqual(gzfrombytes, gzfromchunks)
     decoded = self.applyDeprecated(
         symbol_versioning.deprecated_in((2, 3, 0)),
         tuned_gzip.GzipFile, fileobj=StringIO(gzfromchunks)).read()
     self.assertEqual(bytes, decoded)
Example #13
0
 def test_negative_crc(self):
     """Content with a negative crc should not break when written"""
     sio = StringIO()
     gfile = self.applyDeprecated(
         symbol_versioning.deprecated_in((2, 3, 0)),
         tuned_gzip.GzipFile, mode="w", fileobj=sio)
     gfile.write("\xFF")
     gfile.close()
     self.assertEqual(gfile.crc & 0xFFFFFFFFL, 0xFF000000L)
     self.assertEqual(sio.getvalue()[-8:-4], "\x00\x00\x00\xFF")
Example #14
0
class ExternalBase(tests.TestCaseWithTransport):
    """Don't use this class anymore, use TestCaseWithTransport or similar"""
    @deprecated_method(deprecated_in((2, 2, 0)))
    def check_output(self, output, *args):
        """Verify that the expected output matches what bzr says.

        The output is supplied first, so that you can supply a variable
        number of arguments to bzr.
        """
        self.assertEqual(self.run_bzr(*args)[0], output)
    def test_get_revision_delta(self):
        tree_a = self.make_branch_and_tree('a')
        self.build_tree(['a/foo'])
        tree_a.add('foo', 'file1')
        tree_a.commit('rev1', rev_id='rev1')
        self.build_tree(['a/vla'])
        tree_a.add('vla', 'file2')
        tree_a.commit('rev2', rev_id='rev2')

        delta = self.applyDeprecated(
            symbol_versioning.deprecated_in((2, 5, 0)),
            tree_a.branch.get_revision_delta, 1)
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
        self.assertEqual([('foo', 'file1', 'file')], delta.added)
        delta = self.applyDeprecated(
            symbol_versioning.deprecated_in((2, 5, 0)),
            tree_a.branch.get_revision_delta, 2)
        self.assertIsInstance(delta, _mod_delta.TreeDelta)
        self.assertEqual([('vla', 'file2', 'file')], delta.added)
Example #16
0
 def test_cleanup_function_deprecated(self):
     """Test that per-node cleanup functions are no longer allowed"""
     cache = lru_cache.LRUCache()
     self.assertRaises(ValueError,
                       self.applyDeprecated,
                       symbol_versioning.deprecated_in((2, 5, 0)),
                       cache.add,
                       "key",
                       1,
                       cleanup=lambda: None)
Example #17
0
 def assertToGzip(self, chunks):
     raw_bytes = ''.join(chunks)
     gzfromchunks = tuned_gzip.chunks_to_gzip(chunks)
     gzfrombytes = tuned_gzip.bytes_to_gzip(raw_bytes)
     self.assertEqual(gzfrombytes, gzfromchunks)
     decoded = self.applyDeprecated(
         symbol_versioning.deprecated_in((2, 3, 0)),
         tuned_gzip.GzipFile, fileobj=StringIO(gzfromchunks)).read()
     lraw, ldecoded = len(raw_bytes), len(decoded)
     self.assertEqual(lraw, ldecoded,
                      'Expecting data length %d, got %d' % (lraw, ldecoded))
     self.assertEqual(raw_bytes, decoded)
Example #18
0
    def test_missing_revisions(self):
        t1 = self.make_branch_and_tree('b1')
        rev1 = t1.commit('one')
        t2 = t1.bzrdir.sprout('b2').open_workingtree()
        rev2 = t1.commit('two')
        rev3 = t1.commit('three')

        self.assertEqual([rev2, rev3],
            self.applyDeprecated(deprecated_in((1, 6, 0)),
            t2.branch.missing_revisions, t1.branch))

        self.assertEqual([],
            self.applyDeprecated(deprecated_in((1, 6, 0)),
            t2.branch.missing_revisions, t1.branch, stop_revision=1))
        self.assertEqual([rev2],
            self.applyDeprecated(deprecated_in((1, 6, 0)),
            t2.branch.missing_revisions, t1.branch, stop_revision=2))
        self.assertEqual([rev2, rev3],
            self.applyDeprecated(deprecated_in((1, 6, 0)),
            t2.branch.missing_revisions, t1.branch, stop_revision=3))

        self.assertRaises(errors.NoSuchRevision,
            self.applyDeprecated, deprecated_in((1, 6, 0)),
            t2.branch.missing_revisions, t1.branch, stop_revision=4)

        rev4 = t2.commit('four')
        self.assertRaises(errors.DivergedBranches,
            self.applyDeprecated, deprecated_in((1, 6, 0)),
            t2.branch.missing_revisions, t1.branch)
Example #19
0
class LoopbackGPGStrategy(object):
    """A GPG Strategy that acts like 'cat' - data is just passed through.
    Used in tests.
    """

    @staticmethod
    def verify_signatures_available():
        return True

    def __init__(self, ignored):
        """Real strategies take a configuration."""

    def sign(self, content):
        return ("-----BEGIN PSEUDO-SIGNED CONTENT-----\n" + content +
                "-----END PSEUDO-SIGNED CONTENT-----\n")

    def verify(self, content, testament):
        return SIGNATURE_VALID, None

    def set_acceptable_keys(self, command_line_input):
        if command_line_input is not None:
            patterns = command_line_input.split(",")
            self.acceptable_keys = []
            for pattern in patterns:
                if pattern == "unknown":
                    pass
                else:
                    self.acceptable_keys.append(pattern)

    @deprecated_method(deprecated_in((2, 6, 0)))
    def do_verifications(self, revisions, repository):
        return bulk_verify_signatures(repository, revisions, self)

    @deprecated_method(deprecated_in((2, 6, 0)))
    def valid_commits_message(self, count):
        return valid_commits_message(count)

    @deprecated_method(deprecated_in((2, 6, 0)))
    def unknown_key_message(self, count):
        return unknown_key_message(count)

    @deprecated_method(deprecated_in((2, 6, 0)))
    def commit_not_valid_message(self, count):
        return commit_not_valid_message(count)

    @deprecated_method(deprecated_in((2, 6, 0)))
    def commit_not_signed_message(self, count):
        return commit_not_signed_message(count)

    @deprecated_method(deprecated_in((2, 6, 0)))
    def expired_commit_message(self, count):
        return expired_commit_message(count)
Example #20
0
 def test__read_short_remainder(self):
     # a _read call at the end of a compressed hunk should
     # read more bytes if there is less than 8 bytes (the
     # gzip trailer) unread.
     stream = StringIO('\0\0\0\0\0\0\0\0')
     myfile = self.applyDeprecated(
         symbol_versioning.deprecated_in((2, 3, 0)),
         tuned_gzip.GzipFile, fileobj=stream)
     # disable the _new_member check, we are microtesting.
     myfile._new_member = False
     myfile.crc = zlib.crc32('')
     myfile.decompress = FakeDecompress()
     myfile.size = 0
     myfile._read(1)
     # all the data should have been read now
     self.assertEqual('', stream.read())
     # and it should be new member time in the stream.
     self.assertTrue(myfile._new_member)
Example #21
0
 def test_reports_correct_location(self):
     a_feature = features._CompatabilityThunkFeature(
         symbol_versioning.deprecated_in((2, 1, 0)),
         'bzrlib.tests.test_features',
         'a_feature',
         'UnicodeFilenameFeature',
         replacement_module='bzrlib.tests.features')
     def test_caller(message, category=None, stacklevel=1):
         # Find ourselves back from the right frame
         caller = sys._getframe(stacklevel)
         reported_file = caller.f_globals['__file__']
         reported_lineno = caller.f_lineno
         self.assertEquals(__file__, reported_file)
         # The call we're tracking occurred the line after we grabbed the
         # lineno.
         self.assertEquals(self.lineno + 1, reported_lineno)
     self.overrideAttr(symbol_versioning, 'warn', test_caller)
     # Grab the current lineno
     self.lineno = sys._getframe().f_lineno
     self.requireFeature(a_feature)
Example #22
0
    def test_reconcile_fixes_invalid_revhistory(self):
        if not isinstance(self.branch_format, BzrBranch):
            raise TestNotApplicable("test only applies to bzr formats")
        # Different formats have different ways of handling invalid revision
        # histories, so the setup portion is customized
        tree = self.make_branch_and_tree('test')
        r1 = tree.commit('one')
        r2 = tree.commit('two')
        r3 = tree.commit('three')
        r4 = tree.commit('four')
        # create an alternate branch
        tree.set_parent_ids([r1])
        tree.branch.set_last_revision_info(1, r1)
        r2b = tree.commit('two-b')

        # now go back and merge the commit
        tree.set_parent_ids([r4, r2b])
        tree.branch.set_last_revision_info(4, r4)

        r5 = tree.commit('five')
        # Now, try to set an invalid history
        try:
            self.applyDeprecated(deprecated_in(
                (2, 4, 0)), tree.branch.set_revision_history, [r1, r2b, r5])
            if tree.branch.last_revision_info() != (3, r5):
                # RemoteBranch silently corrects an impossible revision
                # history given to set_revision_history.  It can be tricked
                # with set_last_revision_info though.
                tree.branch.set_last_revision_info(3, r5)
        except errors.NotLefthandHistory:
            # Branch5 allows set_revision_history to be wrong
            # Branch6 raises NotLefthandHistory, but we can force bogus stuff
            # with set_last_revision_info
            tree.branch.set_last_revision_info(3, r5)

        self.assertEqual((3, r5), tree.branch.last_revision_info())
        reconciler = tree.branch.reconcile()
        self.assertEqual((5, r5), tree.branch.last_revision_info())
        self.assertIs(True, reconciler.fixed_history)
Example #23
0
    def test_reports_correct_location(self):
        a_feature = features._CompatabilityThunkFeature(
            symbol_versioning.deprecated_in((2, 1, 0)),
            'bzrlib.tests.test_features',
            'a_feature',
            'UnicodeFilenameFeature',
            replacement_module='bzrlib.tests.features')

        def test_caller(message, category=None, stacklevel=1):
            # Find ourselves back from the right frame
            caller = sys._getframe(stacklevel)
            reported_file = caller.f_globals['__file__']
            reported_lineno = caller.f_lineno
            self.assertEqual(__file__, reported_file)
            # The call we're tracking occurred the line after we grabbed the
            # lineno.
            self.assertEqual(self.lineno + 1, reported_lineno)

        self.overrideAttr(symbol_versioning, 'warn', test_caller)
        # Grab the current lineno
        self.lineno = sys._getframe().f_lineno
        self.requireFeature(a_feature)
Example #24
0
    def test_reconcile_fixes_invalid_revhistory(self):
        if not isinstance(self.branch_format, BzrBranch):
            raise TestNotApplicable("test only applies to bzr formats")
        # Different formats have different ways of handling invalid revision
        # histories, so the setup portion is customized
        tree = self.make_branch_and_tree("test")
        r1 = tree.commit("one")
        r2 = tree.commit("two")
        r3 = tree.commit("three")
        r4 = tree.commit("four")
        # create an alternate branch
        tree.set_parent_ids([r1])
        tree.branch.set_last_revision_info(1, r1)
        r2b = tree.commit("two-b")

        # now go back and merge the commit
        tree.set_parent_ids([r4, r2b])
        tree.branch.set_last_revision_info(4, r4)

        r5 = tree.commit("five")
        # Now, try to set an invalid history
        try:
            self.applyDeprecated(deprecated_in((2, 4, 0)), tree.branch.set_revision_history, [r1, r2b, r5])
            if tree.branch.last_revision_info() != (3, r5):
                # RemoteBranch silently corrects an impossible revision
                # history given to set_revision_history.  It can be tricked
                # with set_last_revision_info though.
                tree.branch.set_last_revision_info(3, r5)
        except errors.NotLefthandHistory:
            # Branch5 allows set_revision_history to be wrong
            # Branch6 raises NotLefthandHistory, but we can force bogus stuff
            # with set_last_revision_info
            tree.branch.set_last_revision_info(3, r5)

        self.assertEqual((3, r5), tree.branch.last_revision_info())
        reconciler = tree.branch.reconcile()
        self.assertEqual((5, r5), tree.branch.last_revision_info())
        self.assertIs(True, reconciler.fixed_history)
Example #25
0
    def test_missing_revisions(self):
        t1 = self.make_branch_and_tree('b1')
        rev1 = t1.commit('one')
        t2 = t1.bzrdir.sprout('b2').open_workingtree()
        rev2 = t1.commit('two')
        rev3 = t1.commit('three')

        self.assertEqual([rev2, rev3],
                         self.applyDeprecated(deprecated_in(
                             (1, 6, 0)), t2.branch.missing_revisions,
                                              t1.branch))

        self.assertEqual([],
                         self.applyDeprecated(deprecated_in((1, 6, 0)),
                                              t2.branch.missing_revisions,
                                              t1.branch,
                                              stop_revision=1))
        self.assertEqual([rev2],
                         self.applyDeprecated(deprecated_in((1, 6, 0)),
                                              t2.branch.missing_revisions,
                                              t1.branch,
                                              stop_revision=2))
        self.assertEqual([rev2, rev3],
                         self.applyDeprecated(deprecated_in((1, 6, 0)),
                                              t2.branch.missing_revisions,
                                              t1.branch,
                                              stop_revision=3))

        self.assertRaises(errors.NoSuchRevision,
                          self.applyDeprecated,
                          deprecated_in((1, 6, 0)),
                          t2.branch.missing_revisions,
                          t1.branch,
                          stop_revision=4)

        rev4 = t2.commit('four')
        self.assertRaises(errors.DivergedBranches, self.applyDeprecated,
                          deprecated_in((1, 6, 0)),
                          t2.branch.missing_revisions, t1.branch)
Example #26
0
        return osutils.size_sha_file(f)
    finally:
        f.close()


# The registry of filter stacks indexed by name.
filter_stacks_registry = registry.Registry()


# Cache of preferences -> stack
# TODO: make this per branch (say) rather than global
_stack_cache = {}


# XXX: This function doesn't have any tests. JRV 2012-03-29
@deprecated_function(deprecated_in((2, 6, 0)))
def register_filter_stack_map(name, stack_map_lookup):
    """Register the filter stacks to use for various preference values.

    :param name: the preference/filter-stack name
    :param stack_map_lookup: a callable where
      the parameter is the preference value to match and
      the result is the matching stack of filters to use,
      or None if none.
    """
    filter_stacks_registry.register(name, stack_map_lookup)


# XXX: This function doesn't have any tests. JRV 2012-03-29
@deprecated_function(deprecated_in((2, 6, 0)))
def lazy_register_filter_stack_map(name, module_name, member_name):
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""Symbol versioning tests."""

import warnings

from bzrlib import symbol_versioning
from bzrlib.symbol_versioning import (
    deprecated_function,
    deprecated_in,
    deprecated_method,
    )
from bzrlib.tests import TestCase


@deprecated_function(deprecated_in((0, 7, 0)))
def sample_deprecated_function():
    """Deprecated function docstring."""
    return 1


a_deprecated_list = symbol_versioning.deprecated_list(deprecated_in((0, 9, 0)),
    'a_deprecated_list', ['one'], extra="Don't use me")


a_deprecated_dict = symbol_versioning.DeprecatedDict(
    deprecated_in((0, 14, 0)),
    'a_deprecated_dict',
    dict(a=42),
    advice='Pull the other one!',
    )
Example #28
0
 def test_home_unicode_deprecated(self):
     s = win32utils.get_home_location()
     u = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
         win32utils.get_home_location_unicode)
     self.assertEqual(s, u)
     self.assertIsInstance(s, unicode)
Example #29
0
            if GetComputerNameEx is not None and GetComputerNameEx(
                _WIN32_ComputerNameDnsHostname, buf, ctypes.byref(n)
            ):
                return extract_buffer(buf)

            # Try GetComputerName in case GetComputerNameEx wasn't found
            # It returns the NETBIOS name, which isn't as good, but still ok.
            # The first GetComputerNameEx might have changed 'n', so reset it
            n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH + 1)
            GetComputerName = getattr(kernel32, "GetComputerName" + suffix, None)
            if GetComputerName is not None and GetComputerName(buf, ctypes.byref(n)):
                return extract_buffer(buf)
    return get_environ_unicode("COMPUTERNAME")


@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 5, 0)))
def _ensure_unicode(s):
    if s and type(s) != unicode:
        from bzrlib import osutils

        s = s.decode(osutils.get_user_encoding())
    return s


get_appdata_location_unicode = symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 5, 0)))(
    get_appdata_location
)

get_home_location_unicode = symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 5, 0)))(
    get_home_location
)
Example #30
0
        feature = NamedFeature()
        self.assertEqual('NamedFeature', str(feature))


class TestUnavailableFeature(tests.TestCase):
    def test_access_feature(self):
        feature = features.Feature()
        exception = tests.UnavailableFeature(feature)
        self.assertIs(feature, exception.args[0])


# Although this was deprecated a long time ago, please keep it here because
# it's really just a test fixture for test-feature deprecation.
simple_thunk_feature = features._CompatabilityThunkFeature(
    symbol_versioning.deprecated_in((2, 1, 0)),
    'bzrlib.tests.test_features',
    'simple_thunk_feature',
    'UnicodeFilenameFeature',
    replacement_module='bzrlib.tests.features')


class Test_CompatibilityFeature(tests.TestCase):
    def test_does_thunk(self):
        res = self.callDeprecated([
            'bzrlib.tests.test_features.simple_thunk_feature '
            'was deprecated in version 2.1.0. '
            'Use bzrlib.tests.features.UnicodeFilenameFeature instead.'
        ], simple_thunk_feature.available)
        self.assertEqual(features.UnicodeFilenameFeature.available(), res)
Example #31
0
        if patterns:
            self.acceptable_keys = []
            for pattern in patterns:
                result = self.context.keylist(pattern)
                found_key = False
                for key in result:
                    found_key = True
                    self.acceptable_keys.append(key.subkeys[0].fpr)
                    trace.mutter("Added acceptable key: " + key.subkeys[0].fpr)
                if not found_key:
                    trace.note(gettext(
                            "No GnuPG key results for pattern: {0}"
                                ).format(pattern))

    @deprecated_method(deprecated_in((2, 6, 0)))
    def do_verifications(self, revisions, repository,
                            process_events_callback=None):
        """do verifications on a set of revisions

        :param revisions: list of revision ids to verify
        :param repository: repository object
        :param process_events_callback: method to call for GUI frontends that
            want to keep their UI refreshed

        :return: count dictionary of results of each type,
                 result list for each revision,
                 boolean True if all results are verified successfully
        """
        return bulk_verify_signatures(repository, revisions, self,
            process_events_callback)
Example #32
0
                                    'in inventory for revision {%s}' %
                                    (file_id, rev_id))
            seen_ids[file_id] = True
        for file_id in inv:
            ie = inv[file_id]
            ie.check(self, rev_id, inv, tree)
        seen_names = {}
        for path, ie in inv.iter_entries():
            if path in seen_names:
                raise BzrCheckError('duplicated path %s '
                                    'in inventory for revision {%s}' %
                                    (path, rev_id))
            seen_names[path] = True


@deprecated_function(deprecated_in((1, 6, 0)))
def check(branch, verbose):
    """Run consistency checks on a branch.
    
    Results are reported through logging.
    
    Deprecated in 1.6.  Please use check_branch instead.

    :raise BzrCheckError: if there's a consistency error.
    """
    check_branch(branch, verbose)


def check_branch(branch, verbose):
    """Run consistency checks on a branch.
Example #33
0
 def test_read_write(self):
     self.assertRaises(NoSuchFile,
         self.applyDeprecated,
         deprecated_in((1, 5, 0)),
         self.lockable.get, 'foo')
     self.assertRaises(NoSuchFile,
         self.applyDeprecated,
         deprecated_in((1, 5, 0)),
         self.lockable.get_utf8, 'foo')
     self.lockable.lock_write()
     try:
         unicode_string = u'bar\u1234'
         self.assertEqual(4, len(unicode_string))
         byte_string = unicode_string.encode('utf-8')
         self.assertEqual(6, len(byte_string))
         self.assertRaises(UnicodeEncodeError,
             self.applyDeprecated,
             deprecated_in((1, 6, 0)),
             self.lockable.put, 'foo',
             StringIO(unicode_string))
         self.applyDeprecated(
             deprecated_in((1, 6, 0)),
             self.lockable.put,
             'foo', StringIO(byte_string))
         byte_stream = self.applyDeprecated(
             deprecated_in((1, 5, 0)),
             self.lockable.get,
             'foo')
         self.assertEqual(byte_string, byte_stream.read())
         unicode_stream = self.applyDeprecated(
             deprecated_in((1, 5, 0)),
             self.lockable.get_utf8,
             'foo')
         self.assertEqual(unicode_string,
             unicode_stream.read())
         self.assertRaises(BzrBadParameterNotString,
             self.applyDeprecated,
             deprecated_in((1, 6, 0)),
             self.lockable.put_utf8,
             'bar',
             StringIO(unicode_string))
         self.applyDeprecated(
             deprecated_in((1, 6, 0)),
             self.lockable.put_utf8,
             'bar',
             unicode_string)
         unicode_stream = self.applyDeprecated(
             deprecated_in((1, 5, 0)),
             self.lockable.get_utf8,
             'bar')
         self.assertEqual(unicode_string,
             unicode_stream.read())
         byte_stream = self.applyDeprecated(
             deprecated_in((1, 5, 0)),
             self.lockable.get,
             'bar')
         self.assertEqual(byte_string, byte_stream.read())
         self.applyDeprecated(
             deprecated_in((1, 6, 0)),
             self.lockable.put_bytes,
             'raw', 'raw\xffbytes')
         byte_stream = self.applyDeprecated(
             deprecated_in((1, 5, 0)),
             self.lockable.get,
             'raw')
         self.assertEqual('raw\xffbytes', byte_stream.read())
     finally:
         self.lockable.unlock()
Example #34
0
 def test_read_write(self):
     self.assertRaises(NoSuchFile, self.applyDeprecated,
                       deprecated_in((1, 5, 0)), self.lockable.get, 'foo')
     self.assertRaises(NoSuchFile, self.applyDeprecated,
                       deprecated_in((1, 5, 0)), self.lockable.get_utf8,
                       'foo')
     self.lockable.lock_write()
     try:
         unicode_string = u'bar\u1234'
         self.assertEqual(4, len(unicode_string))
         byte_string = unicode_string.encode('utf-8')
         self.assertEqual(6, len(byte_string))
         self.assertRaises(UnicodeEncodeError, self.applyDeprecated,
                           deprecated_in((1, 6, 0)), self.lockable.put,
                           'foo', StringIO(unicode_string))
         self.applyDeprecated(deprecated_in((1, 6, 0)), self.lockable.put,
                              'foo', StringIO(byte_string))
         byte_stream = self.applyDeprecated(deprecated_in((1, 5, 0)),
                                            self.lockable.get, 'foo')
         self.assertEqual(byte_string, byte_stream.read())
         unicode_stream = self.applyDeprecated(deprecated_in(
             (1, 5, 0)), self.lockable.get_utf8, 'foo')
         self.assertEqual(unicode_string, unicode_stream.read())
         self.assertRaises(BzrBadParameterNotString, self.applyDeprecated,
                           deprecated_in((1, 6, 0)), self.lockable.put_utf8,
                           'bar', StringIO(unicode_string))
         self.applyDeprecated(deprecated_in((1, 6, 0)),
                              self.lockable.put_utf8, 'bar', unicode_string)
         unicode_stream = self.applyDeprecated(deprecated_in(
             (1, 5, 0)), self.lockable.get_utf8, 'bar')
         self.assertEqual(unicode_string, unicode_stream.read())
         byte_stream = self.applyDeprecated(deprecated_in((1, 5, 0)),
                                            self.lockable.get, 'bar')
         self.assertEqual(byte_string, byte_stream.read())
         self.applyDeprecated(deprecated_in(
             (1, 6, 0)), self.lockable.put_bytes, 'raw', 'raw\xffbytes')
         byte_stream = self.applyDeprecated(deprecated_in((1, 5, 0)),
                                            self.lockable.get, 'raw')
         self.assertEqual('raw\xffbytes', byte_stream.read())
     finally:
         self.lockable.unlock()
Example #35
0
        return osutils.size_sha_file(f)
    finally:
        f.close()


# The registry of filter stacks indexed by name.
filter_stacks_registry = registry.Registry()


# Cache of preferences -> stack
# TODO: make this per branch (say) rather than global
_stack_cache = {}


# XXX: This function doesn't have any tests. JRV 2012-03-29
@deprecated_function(deprecated_in((2, 6, 0)))
def register_filter_stack_map(name, stack_map_lookup):
    """Register the filter stacks to use for various preference values.

    :param name: the preference/filter-stack name
    :param stack_map_lookup: a callable where
      the parameter is the preference value to match and
      the result is the matching stack of filters to use,
      or None if none.
    """
    filter_stacks_registry.register(name, stack_map_lookup)


# XXX: This function doesn't have any tests. JRV 2012-03-29
@deprecated_function(deprecated_in((2, 6, 0)))
def lazy_register_filter_stack_map(name, module_name, member_name):
Example #36
0
 def __init__(self, *args, **kwargs):
     symbol_versioning.warn(symbol_versioning.deprecated_in(
         (2, 3, 0)) % 'bzrlib.tuned_gzip.GzipFile',
                            DeprecationWarning,
                            stacklevel=2)
     gzip.GzipFile.__init__(self, *args, **kwargs)
Example #37
0
class LRUCache(object):
    """A class which manages a cache of entries, removing unused ones."""
    def __init__(self, max_cache=100, after_cleanup_count=None):
        self._cache = {}
        # The "HEAD" of the lru linked list
        self._most_recently_used = None
        # The "TAIL" of the lru linked list
        self._least_recently_used = None
        self._update_max_cache(max_cache, after_cleanup_count)

    def __contains__(self, key):
        return key in self._cache

    def __getitem__(self, key):
        cache = self._cache
        node = cache[key]
        # Inlined from _record_access to decrease the overhead of __getitem__
        # We also have more knowledge about structure if __getitem__ is
        # succeeding, then we know that self._most_recently_used must not be
        # None, etc.
        mru = self._most_recently_used
        if node is mru:
            # Nothing to do, this node is already at the head of the queue
            return node.value
        # Remove this node from the old location
        node_prev = node.prev
        next_key = node.next_key
        # benchmarking shows that the lookup of _null_key in globals is faster
        # than the attribute lookup for (node is self._least_recently_used)
        if next_key is _null_key:
            # 'node' is the _least_recently_used, because it doesn't have a
            # 'next' item. So move the current lru to the previous node.
            self._least_recently_used = node_prev
        else:
            node_next = cache[next_key]
            node_next.prev = node_prev
        node_prev.next_key = next_key
        # Insert this node at the front of the list
        node.next_key = mru.key
        mru.prev = node
        self._most_recently_used = node
        node.prev = None
        return node.value

    def __len__(self):
        return len(self._cache)

    @symbol_versioning.deprecated_method(
        symbol_versioning.deprecated_in((2, 5, 0)))
    def add(self, key, value, cleanup=None):
        if cleanup is not None:
            raise ValueError("Per-node cleanup functions no longer supported")
        return self.__setitem__(key, value)

    def __setitem__(self, key, value):
        """Add a new value to the cache"""
        if key is _null_key:
            raise ValueError('cannot use _null_key as a key')
        if key in self._cache:
            node = self._cache[key]
            node.value = value
            self._record_access(node)
        else:
            node = _LRUNode(key, value)
            self._cache[key] = node
            self._record_access(node)

        if len(self._cache) > self._max_cache:
            # Trigger the cleanup
            self.cleanup()

    def cache_size(self):
        """Get the number of entries we will cache."""
        return self._max_cache

    def get(self, key, default=None):
        node = self._cache.get(key, None)
        if node is None:
            return default
        self._record_access(node)
        return node.value

    def keys(self):
        """Get the list of keys currently cached.

        Note that values returned here may not be available by the time you
        request them later. This is simply meant as a peak into the current
        state.

        :return: An unordered list of keys that are currently cached.
        """
        return self._cache.keys()

    def as_dict(self):
        """Get a new dict with the same key:value pairs as the cache"""
        return dict((k, n.value) for k, n in self._cache.iteritems())

    items = symbol_versioning.deprecated_method(
        symbol_versioning.deprecated_in((2, 5, 0)))(as_dict)

    def cleanup(self):
        """Clear the cache until it shrinks to the requested size.

        This does not completely wipe the cache, just makes sure it is under
        the after_cleanup_count.
        """
        # Make sure the cache is shrunk to the correct size
        while len(self._cache) > self._after_cleanup_count:
            self._remove_lru()

    def _record_access(self, node):
        """Record that key was accessed."""
        # Move 'node' to the front of the queue
        if self._most_recently_used is None:
            self._most_recently_used = node
            self._least_recently_used = node
            return
        elif node is self._most_recently_used:
            # Nothing to do, this node is already at the head of the queue
            return
        # We've taken care of the tail pointer, remove the node, and insert it
        # at the front
        # REMOVE
        if node is self._least_recently_used:
            self._least_recently_used = node.prev
        if node.prev is not None:
            node.prev.next_key = node.next_key
        if node.next_key is not _null_key:
            node_next = self._cache[node.next_key]
            node_next.prev = node.prev
        # INSERT
        node.next_key = self._most_recently_used.key
        self._most_recently_used.prev = node
        self._most_recently_used = node
        node.prev = None

    def _remove_node(self, node):
        if node is self._least_recently_used:
            self._least_recently_used = node.prev
        self._cache.pop(node.key)
        # If we have removed all entries, remove the head pointer as well
        if self._least_recently_used is None:
            self._most_recently_used = None
        if node.prev is not None:
            node.prev.next_key = node.next_key
        if node.next_key is not _null_key:
            node_next = self._cache[node.next_key]
            node_next.prev = node.prev
        # And remove this node's pointers
        node.prev = None
        node.next_key = _null_key

    def _remove_lru(self):
        """Remove one entry from the lru, and handle consequences.

        If there are no more references to the lru, then this entry should be
        removed from the cache.
        """
        self._remove_node(self._least_recently_used)

    def clear(self):
        """Clear out all of the cache."""
        # Clean up in LRU order
        while self._cache:
            self._remove_lru()

    def resize(self, max_cache, after_cleanup_count=None):
        """Change the number of entries that will be cached."""
        self._update_max_cache(max_cache,
                               after_cleanup_count=after_cleanup_count)

    def _update_max_cache(self, max_cache, after_cleanup_count=None):
        self._max_cache = max_cache
        if after_cleanup_count is None:
            self._after_cleanup_count = self._max_cache * 8 / 10
        else:
            self._after_cleanup_count = min(after_cleanup_count,
                                            self._max_cache)
        self.cleanup()
Example #38
0
                return extract_buffer(buf)

            # Try GetComputerName in case GetComputerNameEx wasn't found
            # It returns the NETBIOS name, which isn't as good, but still ok.
            # The first GetComputerNameEx might have changed 'n', so reset it
            n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH + 1)
            GetComputerName = getattr(kernel32, 'GetComputerName' + suffix,
                                      None)
            if (GetComputerName is not None
                    and GetComputerName(buf, ctypes.byref(n))):
                return extract_buffer(buf)
    return get_environ_unicode('COMPUTERNAME')


@symbol_versioning.deprecated_function(
    symbol_versioning.deprecated_in((2, 5, 0)))
def _ensure_unicode(s):
    if s and type(s) != unicode:
        from bzrlib import osutils
        s = s.decode(osutils.get_user_encoding())
    return s


get_appdata_location_unicode = symbol_versioning.deprecated_function(
    symbol_versioning.deprecated_in((2, 5, 0)))(get_appdata_location)

get_home_location_unicode = symbol_versioning.deprecated_function(
    symbol_versioning.deprecated_in((2, 5, 0)))(get_home_location)

get_user_name_unicode = symbol_versioning.deprecated_function(
    symbol_versioning.deprecated_in((2, 5, 0)))(get_user_name)
Example #39
0
        feature = NamedFeature()
        self.assertEqual('NamedFeature', str(feature))


class TestUnavailableFeature(tests.TestCase):

    def test_access_feature(self):
        feature = features.Feature()
        exception = tests.UnavailableFeature(feature)
        self.assertIs(feature, exception.args[0])


# Although this was deprecated a long time ago, please keep it here because
# it's really just a test fixture for test-feature deprecation.
simple_thunk_feature = features._CompatabilityThunkFeature(
    symbol_versioning.deprecated_in((2, 1, 0)),
    'bzrlib.tests.test_features',
    'simple_thunk_feature',
    'UnicodeFilenameFeature',
    replacement_module='bzrlib.tests.features')


class Test_CompatibilityFeature(tests.TestCase):

    def test_does_thunk(self):
        res = self.callDeprecated(
            ['bzrlib.tests.test_features.simple_thunk_feature '
             'was deprecated in version 2.1.0. '
             'Use bzrlib.tests.features.UnicodeFilenameFeature instead.'],
            simple_thunk_feature.available)
        self.assertEqual(features.UnicodeFilenameFeature.available(), res)
Example #40
0
            patterns = key_patterns.split(",")

            self.acceptable_keys = []
            for pattern in patterns:
                result = self.context.keylist(pattern)
                found_key = False
                for key in result:
                    found_key = True
                    self.acceptable_keys.append(key.subkeys[0].fpr)
                    trace.mutter("Added acceptable key: " + key.subkeys[0].fpr)
                if not found_key:
                    trace.note(gettext(
                            "No GnuPG key results for pattern: {0}"
                                ).format(pattern))

    @deprecated_method(deprecated_in((2, 6, 0)))
    def do_verifications(self, revisions, repository,
                            process_events_callback=None):
        """do verifications on a set of revisions

        :param revisions: list of revision ids to verify
        :param repository: repository object
        :param process_events_callback: method to call for GUI frontends that
            want to keep their UI refreshed

        :return: count dictionary of results of each type,
                 result list for each revision,
                 boolean True if all results are verified successfully
        """
        return bulk_verify_signatures(repository, revisions, self,
            process_events_callback)
Example #41
0
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
"""Symbol versioning tests."""

import warnings

from bzrlib import symbol_versioning
from bzrlib.symbol_versioning import (
    deprecated_function,
    deprecated_in,
    deprecated_method,
)
from bzrlib.tests import TestCase


@deprecated_function(deprecated_in((0, 7, 0)))
def sample_deprecated_function():
    """Deprecated function docstring."""
    return 1


a_deprecated_list = symbol_versioning.deprecated_list(deprecated_in((0, 9, 0)),
                                                      'a_deprecated_list',
                                                      ['one'],
                                                      extra="Don't use me")

a_deprecated_dict = symbol_versioning.DeprecatedDict(
    deprecated_in((0, 14, 0)),
    'a_deprecated_dict',
    dict(a=42),
    advice='Pull the other one!',
Example #42
0
 def test_cleanup_function_deprecated(self):
     """Test that per-node cleanup functions are no longer allowed"""
     cache = lru_cache.LRUCache()
     self.assertRaises(ValueError, self.applyDeprecated,
         symbol_versioning.deprecated_in((2, 5, 0)),
         cache.add, "key", 1, cleanup=lambda: None)
Example #43
0
 def test_home_unicode_deprecated(self):
     s = win32utils.get_home_location()
     u = self.applyDeprecated(symbol_versioning.deprecated_in((2, 5, 0)),
         win32utils.get_home_location_unicode)
     self.assertEqual(s, u)
     self.assertIsInstance(s, unicode)
Example #44
0
 def __init__(self, *args, **kwargs):
     symbol_versioning.warn(
         symbol_versioning.deprecated_in((2, 3, 0)) % "bzrlib.tuned_gzip.GzipFile", DeprecationWarning, stacklevel=2
     )
     gzip.GzipFile.__init__(self, *args, **kwargs)
Example #45
0
class TestDeprecationWarnings(TestCase):
    def capture_warning(self, message, category, stacklevel=None):
        self._warnings.append((message, category, stacklevel))

    def setUp(self):
        super(TestDeprecationWarnings, self).setUp()
        self._warnings = []

    @deprecated_method(deprecated_in((0, 7, 0)))
    def deprecated_method(self):
        """Deprecated method docstring.

        This might explain stuff.
        """
        return 1

    @staticmethod
    @deprecated_function(deprecated_in((0, 7, 0)))
    def deprecated_static():
        """Deprecated static."""
        return 1

    def test_deprecated_static(self):
        # XXX: The results are not quite right because the class name is not
        # shown - however it is enough to give people a good indication of
        # where the problem is.
        expected_warning = ("bzrlib.tests.test_symbol_versioning."
                            "deprecated_static "
                            "was deprecated in version 0.7.0.",
                            DeprecationWarning, 2)
        expected_docstring = (
            'Deprecated static.\n'
            '\n'
            'This function was deprecated in version 0.7.0.\n')
        self.check_deprecated_callable(expected_warning, expected_docstring,
                                       "deprecated_static",
                                       "bzrlib.tests.test_symbol_versioning",
                                       self.deprecated_static)

    def test_deprecated_method(self):
        expected_warning = ("bzrlib.tests.test_symbol_versioning."
                            "TestDeprecationWarnings.deprecated_method "
                            "was deprecated in version 0.7.0.",
                            DeprecationWarning, 2)
        expected_docstring = (
            'Deprecated method docstring.\n'
            '\n'
            '        This might explain stuff.\n'
            '        \n'
            '        This method was deprecated in version 0.7.0.\n'
            '        ')
        self.check_deprecated_callable(expected_warning, expected_docstring,
                                       "deprecated_method",
                                       "bzrlib.tests.test_symbol_versioning",
                                       self.deprecated_method)

    def test_deprecated_function(self):
        expected_warning = (
            "bzrlib.tests.test_symbol_versioning.sample_deprecated_function "
            "was deprecated in version 0.7.0.", DeprecationWarning, 2)
        expected_docstring = (
            'Deprecated function docstring.\n'
            '\n'
            'This function was deprecated in version 0.7.0.\n')
        self.check_deprecated_callable(expected_warning, expected_docstring,
                                       "sample_deprecated_function",
                                       "bzrlib.tests.test_symbol_versioning",
                                       sample_deprecated_function)

    def test_deprecated_list(self):
        expected_warning = (
            "Modifying a_deprecated_list was deprecated in version 0.9.0."
            " Don't use me", DeprecationWarning, 3)
        old_warning_method = symbol_versioning.warn
        try:
            symbol_versioning.set_warning_method(self.capture_warning)
            self.assertEqual(['one'], a_deprecated_list)
            self.assertEqual([], self._warnings)

            a_deprecated_list.append('foo')
            self.assertEqual([expected_warning], self._warnings)
            self.assertEqual(['one', 'foo'], a_deprecated_list)

            a_deprecated_list.extend(['bar', 'baz'])
            self.assertEqual([expected_warning] * 2, self._warnings)
            self.assertEqual(['one', 'foo', 'bar', 'baz'], a_deprecated_list)

            a_deprecated_list.insert(1, 'xxx')
            self.assertEqual([expected_warning] * 3, self._warnings)
            self.assertEqual(['one', 'xxx', 'foo', 'bar', 'baz'],
                             a_deprecated_list)

            a_deprecated_list.remove('foo')
            self.assertEqual([expected_warning] * 4, self._warnings)
            self.assertEqual(['one', 'xxx', 'bar', 'baz'], a_deprecated_list)

            val = a_deprecated_list.pop()
            self.assertEqual([expected_warning] * 5, self._warnings)
            self.assertEqual('baz', val)
            self.assertEqual(['one', 'xxx', 'bar'], a_deprecated_list)

            val = a_deprecated_list.pop(1)
            self.assertEqual([expected_warning] * 6, self._warnings)
            self.assertEqual('xxx', val)
            self.assertEqual(['one', 'bar'], a_deprecated_list)
        finally:
            symbol_versioning.set_warning_method(old_warning_method)

    def test_deprecated_dict(self):
        expected_warning = (
            "access to a_deprecated_dict was deprecated in version 0.14.0."
            " Pull the other one!", DeprecationWarning, 2)
        old_warning_method = symbol_versioning.warn
        try:
            symbol_versioning.set_warning_method(self.capture_warning)
            self.assertEqual(len(a_deprecated_dict), 1)
            self.assertEqual([expected_warning], self._warnings)

            a_deprecated_dict['b'] = 42
            self.assertEqual(a_deprecated_dict['b'], 42)
            self.assertTrue('b' in a_deprecated_dict)
            del a_deprecated_dict['b']
            self.assertFalse('b' in a_deprecated_dict)
            self.assertEqual([expected_warning] * 6, self._warnings)
        finally:
            symbol_versioning.set_warning_method(old_warning_method)

    def check_deprecated_callable(self, expected_warning, expected_docstring,
                                  expected_name, expected_module,
                                  deprecated_callable):
        if __doc__ is None:
            # With -OO the docstring should just be the deprecated version
            expected_docstring = expected_docstring.split('\n')[-2].lstrip()
        old_warning_method = symbol_versioning.warn
        try:
            symbol_versioning.set_warning_method(self.capture_warning)
            self.assertEqual(1, deprecated_callable())
            self.assertEqual([expected_warning], self._warnings)
            deprecated_callable()
            self.assertEqual([expected_warning, expected_warning],
                             self._warnings)
            self.assertEqualDiff(expected_docstring,
                                 deprecated_callable.__doc__)
            self.assertEqualDiff(expected_name, deprecated_callable.__name__)
            self.assertEqualDiff(expected_module,
                                 deprecated_callable.__module__)
            self.assertTrue(deprecated_callable.is_deprecated)
        finally:
            symbol_versioning.set_warning_method(old_warning_method)

    def test_deprecated_passed(self):
        self.assertEqual(True, symbol_versioning.deprecated_passed(None))
        self.assertEqual(True, symbol_versioning.deprecated_passed(True))
        self.assertEqual(True, symbol_versioning.deprecated_passed(False))
        self.assertEqual(
            False,
            symbol_versioning.deprecated_passed(
                symbol_versioning.DEPRECATED_PARAMETER))

    def test_deprecation_string(self):
        """We can get a deprecation string for a method or function."""
        self.assertEqual(
            'bzrlib.tests.test_symbol_versioning.'
            'TestDeprecationWarnings.test_deprecation_string was deprecated in '
            'version 0.11.0.',
            symbol_versioning.deprecation_string(self.test_deprecation_string,
                                                 deprecated_in((0, 11, 0))))
        self.assertEqual(
            'bzrlib.symbol_versioning.deprecated_function was '
            'deprecated in version 0.11.0.',
            symbol_versioning.deprecation_string(
                symbol_versioning.deprecated_function, deprecated_in(
                    (0, 11, 0))))
Example #46
0
class InventoryEntry(object):
    """Description of a versioned file.

    An InventoryEntry has the following fields, which are also
    present in the XML inventory-entry element:

    file_id

    name
        (within the parent directory)

    parent_id
        file_id of the parent directory, or ROOT_ID

    revision
        the revision_id in which this variation of this file was 
        introduced.

    executable
        Indicates that this file should be executable on systems
        that support it.

    text_sha1
        sha-1 of the text of the file
        
    text_size
        size in bytes of the text of the file
        
    (reading a version 4 tree created a text_id field.)

    >>> i = Inventory()
    >>> i.path2id('')
    'TREE_ROOT'
    >>> i.add(InventoryDirectory('123', 'src', ROOT_ID))
    InventoryDirectory('123', 'src', parent_id='TREE_ROOT', revision=None)
    >>> i.add(InventoryFile('2323', 'hello.c', parent_id='123'))
    InventoryFile('2323', 'hello.c', parent_id='123', sha1=None, len=None)
    >>> shouldbe = {0: '', 1: 'src', 2: 'src/hello.c'}
    >>> for ix, j in enumerate(i.iter_entries()):
    ...   print (j[0] == shouldbe[ix], j[1])
    ... 
    (True, InventoryDirectory('TREE_ROOT', u'', parent_id=None, revision=None))
    (True, InventoryDirectory('123', 'src', parent_id='TREE_ROOT', revision=None))
    (True, InventoryFile('2323', 'hello.c', parent_id='123', sha1=None, len=None))
    >>> i.add(InventoryFile('2324', 'bye.c', '123'))
    InventoryFile('2324', 'bye.c', parent_id='123', sha1=None, len=None)
    >>> i.add(InventoryDirectory('2325', 'wibble', '123'))
    InventoryDirectory('2325', 'wibble', parent_id='123', revision=None)
    >>> i.path2id('src/wibble')
    '2325'
    >>> '2325' in i
    True
    >>> i.add(InventoryFile('2326', 'wibble.c', '2325'))
    InventoryFile('2326', 'wibble.c', parent_id='2325', sha1=None, len=None)
    >>> i['2326']
    InventoryFile('2326', 'wibble.c', parent_id='2325', sha1=None, len=None)
    >>> for path, entry in i.iter_entries():
    ...     print path
    ... 
    <BLANKLINE>
    src
    src/bye.c
    src/hello.c
    src/wibble
    src/wibble/wibble.c
    >>> i.id2path('2326')
    'src/wibble/wibble.c'
    """

    # Constants returned by describe_change()
    #
    # TODO: These should probably move to some kind of FileChangeDescription
    # class; that's like what's inside a TreeDelta but we want to be able to
    # generate them just for one file at a time.
    RENAMED = 'renamed'
    MODIFIED_AND_RENAMED = 'modified and renamed'

    __slots__ = []

    def detect_changes(self, old_entry):
        """Return a (text_modified, meta_modified) from this to old_entry.
        
        _read_tree_state must have been called on self and old_entry prior to 
        calling detect_changes.
        """
        return False, False

    def _diff(self,
              text_diff,
              from_label,
              tree,
              to_label,
              to_entry,
              to_tree,
              output_to,
              reverse=False):
        """Perform a diff between two entries of the same kind."""

    def parent_candidates(self, previous_inventories):
        """Find possible per-file graph parents.

        This is currently defined by:
         - Select the last changed revision in the parent inventory.
         - Do deal with a short lived bug in bzr 0.8's development two entries
           that have the same last changed but different 'x' bit settings are
           changed in-place.
        """
        # revision:ie mapping for each ie found in previous_inventories.
        candidates = {}
        # identify candidate head revision ids.
        for inv in previous_inventories:
            if self.file_id in inv:
                ie = inv[self.file_id]
                if ie.revision in candidates:
                    # same revision value in two different inventories:
                    # correct possible inconsistencies:
                    #     * there was a bug in revision updates with 'x' bit
                    #       support.
                    try:
                        if candidates[ie.revision].executable != ie.executable:
                            candidates[ie.revision].executable = False
                            ie.executable = False
                    except AttributeError:
                        pass
                else:
                    # add this revision as a candidate.
                    candidates[ie.revision] = ie
        return candidates

    @deprecated_method(deprecated_in((1, 6, 0)))
    def get_tar_item(self, root, dp, now, tree):
        """Get a tarfile item and a file stream for its content."""
        item = tarfile.TarInfo(osutils.pathjoin(root, dp).encode('utf8'))
        # TODO: would be cool to actually set it to the timestamp of the
        # revision it was last changed
        item.mtime = now
        fileobj = self._put_in_tar(item, tree)
        return item, fileobj

    def has_text(self):
        """Return true if the object this entry represents has textual data.

        Note that textual data includes binary content.

        Also note that all entries get weave files created for them.
        This attribute is primarily used when upgrading from old trees that
        did not have the weave index for all inventory entries.
        """
        return False

    def __init__(self, file_id, name, parent_id, text_id=None):
        """Create an InventoryEntry
        
        The filename must be a single component, relative to the
        parent directory; it cannot be a whole path or relative name.

        >>> e = InventoryFile('123', 'hello.c', ROOT_ID)
        >>> e.name
        'hello.c'
        >>> e.file_id
        '123'
        >>> e = InventoryFile('123', 'src/hello.c', ROOT_ID)
        Traceback (most recent call last):
        InvalidEntryName: Invalid entry name: src/hello.c
        """
        if '/' in name or '\\' in name:
            raise errors.InvalidEntryName(name=name)
        self.executable = False
        self.revision = None
        self.text_sha1 = None
        self.text_size = None
        self.file_id = file_id
        self.name = name
        self.text_id = text_id
        self.parent_id = parent_id
        self.symlink_target = None
        self.reference_revision = None

    def kind_character(self):
        """Return a short kind indicator useful for appending to names."""
        raise BzrError('unknown kind %r' % self.kind)

    known_kinds = ('file', 'directory', 'symlink')

    def _put_in_tar(self, item, tree):
        """populate item for stashing in a tar, and return the content stream.

        If no content is available, return None.
        """
        raise BzrError("don't know how to export {%s} of kind %r" %
                       (self.file_id, self.kind))

    @deprecated_method(deprecated_in((1, 6, 0)))
    def put_on_disk(self, dest, dp, tree):
        """Create a representation of self on disk in the prefix dest.
        
        This is a template method - implement _put_on_disk in subclasses.
        """
        fullpath = osutils.pathjoin(dest, dp)
        self._put_on_disk(fullpath, tree)
        # mutter("  export {%s} kind %s to %s", self.file_id,
        #         self.kind, fullpath)

    def _put_on_disk(self, fullpath, tree):
        """Put this entry onto disk at fullpath, from tree tree."""
        raise BzrError("don't know how to export {%s} of kind %r" %
                       (self.file_id, self.kind))

    def sorted_children(self):
        return sorted(self.children.items())

    @staticmethod
    def versionable_kind(kind):
        return (kind in ('file', 'directory', 'symlink', 'tree-reference'))

    def check(self, checker, rev_id, inv, tree):
        """Check this inventory entry is intact.

        This is a template method, override _check for kind specific
        tests.

        :param checker: Check object providing context for the checks; 
             can be used to find out what parts of the repository have already
             been checked.
        :param rev_id: Revision id from which this InventoryEntry was loaded.
             Not necessarily the last-changed revision for this file.
        :param inv: Inventory from which the entry was loaded.
        :param tree: RevisionTree for this entry.
        """
        if self.parent_id is not None:
            if not inv.has_id(self.parent_id):
                raise BzrCheckError(
                    'missing parent {%s} in inventory for revision {%s}' %
                    (self.parent_id, rev_id))
        self._check(checker, rev_id, tree)

    def _check(self, checker, rev_id, tree):
        """Check this inventory entry for kind specific errors."""
        raise BzrCheckError('unknown entry kind %r in revision {%s}' %
                            (self.kind, rev_id))

    def copy(self):
        """Clone this inventory entry."""
        raise NotImplementedError

    @staticmethod
    def describe_change(old_entry, new_entry):
        """Describe the change between old_entry and this.
        
        This smells of being an InterInventoryEntry situation, but as its
        the first one, we're making it a static method for now.

        An entry with a different parent, or different name is considered 
        to be renamed. Reparenting is an internal detail.
        Note that renaming the parent does not trigger a rename for the
        child entry itself.
        """
        # TODO: Perhaps return an object rather than just a string
        if old_entry is new_entry:
            # also the case of both being None
            return 'unchanged'
        elif old_entry is None:
            return 'added'
        elif new_entry is None:
            return 'removed'
        if old_entry.kind != new_entry.kind:
            return 'modified'
        text_modified, meta_modified = new_entry.detect_changes(old_entry)
        if text_modified or meta_modified:
            modified = True
        else:
            modified = False
        # TODO 20060511 (mbp, rbc) factor out 'detect_rename' here.
        if old_entry.parent_id != new_entry.parent_id:
            renamed = True
        elif old_entry.name != new_entry.name:
            renamed = True
        else:
            renamed = False
        if renamed and not modified:
            return InventoryEntry.RENAMED
        if modified and not renamed:
            return 'modified'
        if modified and renamed:
            return InventoryEntry.MODIFIED_AND_RENAMED
        return 'unchanged'

    def __repr__(self):
        return ("%s(%r, %r, parent_id=%r, revision=%r)" %
                (self.__class__.__name__, self.file_id, self.name,
                 self.parent_id, self.revision))

    def __eq__(self, other):
        if not isinstance(other, InventoryEntry):
            return NotImplemented

        return ((self.file_id == other.file_id) and (self.name == other.name)
                and (other.symlink_target == self.symlink_target)
                and (self.text_sha1 == other.text_sha1)
                and (self.text_size == other.text_size)
                and (self.text_id == other.text_id)
                and (self.parent_id == other.parent_id)
                and (self.kind == other.kind)
                and (self.revision == other.revision)
                and (self.executable == other.executable)
                and (self.reference_revision == other.reference_revision))

    def __ne__(self, other):
        return not (self == other)

    def __hash__(self):
        raise ValueError('not hashable')

    def _unchanged(self, previous_ie):
        """Has this entry changed relative to previous_ie.

        This method should be overridden in child classes.
        """
        compatible = True
        # different inv parent
        if previous_ie.parent_id != self.parent_id:
            compatible = False
        # renamed
        elif previous_ie.name != self.name:
            compatible = False
        elif previous_ie.kind != self.kind:
            compatible = False
        return compatible

    def _read_tree_state(self, path, work_tree):
        """Populate fields in the inventory entry from the given tree.
        
        Note that this should be modified to be a noop on virtual trees
        as all entries created there are prepopulated.
        """
        # TODO: Rather than running this manually, we should check the
        # working sha1 and other expensive properties when they're
        # first requested, or preload them if they're already known
        pass  # nothing to do by default

    def _forget_tree_state(self):
        pass
Example #47
0
                return extract_buffer(buf)

            # Try GetComputerName in case GetComputerNameEx wasn't found
            # It returns the NETBIOS name, which isn't as good, but still ok.
            # The first GetComputerNameEx might have changed 'n', so reset it
            n = ctypes.c_int(MAX_COMPUTERNAME_LENGTH+1)
            GetComputerName = getattr(kernel32, 'GetComputerName'+suffix,
                                      None)
            if (GetComputerName is not None
                and GetComputerName(buf, ctypes.byref(n))):
                return extract_buffer(buf)
    return get_environ_unicode('COMPUTERNAME')


@symbol_versioning.deprecated_function(
    symbol_versioning.deprecated_in((2, 5, 0)))
def _ensure_unicode(s):
    if s and type(s) != unicode:
        from bzrlib import osutils
        s = s.decode(osutils.get_user_encoding())
    return s


get_appdata_location_unicode = symbol_versioning.deprecated_function(
    symbol_versioning.deprecated_in((2, 5, 0)))(get_appdata_location)

get_home_location_unicode = symbol_versioning.deprecated_function(
    symbol_versioning.deprecated_in((2, 5, 0)))(get_home_location)

get_user_name_unicode = symbol_versioning.deprecated_function(
    symbol_versioning.deprecated_in((2, 5, 0)))(get_user_name)