예제 #1
0
    def test_send_pack_new_ref(self):
        self.rin.write(
            '0064310ca9477129b8586fa2afc779c1f57cf64bba6c '
            'refs/heads/master\x00 report-status delete-refs ofs-delta\n'
            '0000000eunpack ok\n'
            '0019ok refs/heads/blah12\n'
            '0000')
        self.rin.seek(0)

        tree = Tree()
        commit = Commit()
        commit.tree = tree
        commit.parents = []
        commit.author = commit.committer = 'test user'
        commit.commit_time = commit.author_time = 1174773719
        commit.commit_timezone = commit.author_timezone = 0
        commit.encoding = 'UTF-8'
        commit.message = 'test message'

        def determine_wants(refs):
            return {
                'refs/heads/blah12': commit.id,
                'refs/heads/master': '310ca9477129b8586fa2afc779c1f57cf64bba6c'
            }

        def generate_pack_contents(have, want):
            return [
                (commit, None),
                (tree, ''),
            ]

        f = BytesIO()
        pack = write_pack_objects(f, generate_pack_contents(None, None))
        self.client.send_pack('/', determine_wants, generate_pack_contents)
        self.assertIn(self.rout.getvalue(), [
            '007f0000000000000000000000000000000000000000 %s '
            'refs/heads/blah12\x00report-status ofs-delta0000%s' %
            (commit.id, f.getvalue()),
            '007f0000000000000000000000000000000000000000 %s '
            'refs/heads/blah12\x00ofs-delta report-status0000%s' %
            (commit.id, f.getvalue())
        ])
예제 #2
0
 def test_import_tree_with_file_exe(self):
     blob = Blob.from_string(b"bar")
     tree = Tree()
     tree.add(b"foo", 0o100755, blob.id)
     objects = {blob.id: blob, tree.id: tree}
     ret, child_modes = import_git_tree(
         self._texts, self._mapping, b"", b"", (None, tree.id), None, None,
         b"somerevid", [], objects.__getitem__, (None, stat.S_IFDIR),
         DummyStoreUpdater(), self._mapping.generate_file_id)
     self.assertEqual(child_modes, {})
     self.assertEqual(2, len(ret))
     self.assertEqual(None, ret[0][0])
     self.assertEqual("", ret[0][1])
     self.assertEqual(None, ret[1][0])
     self.assertEqual("foo", ret[1][1])
     ie = ret[0][3]
     self.assertEqual("directory", ie.kind)
     ie = ret[1][3]
     self.assertEqual("file", ie.kind)
     self.assertEqual(True, ie.executable)
예제 #3
0
 def test_import_tree_empty_root(self):
     tree = Tree()
     ret, child_modes = import_git_tree(self._texts, self._mapping, b"", b"",
                                        (None, tree.id), None,
                                        None, b"somerevid", [], {
                                            tree.id: tree}.__getitem__,
                                        (None, stat.S_IFDIR), DummyStoreUpdater(),
                                        self._mapping.generate_file_id)
     self.assertEqual(child_modes, {})
     self.assertEqual(
         set([(b"TREE_ROOT", b'somerevid')]), self._texts.keys())
     self.assertEqual(1, len(ret))
     self.assertEqual(None, ret[0][0])
     self.assertEqual("", ret[0][1])
     ie = ret[0][3]
     self.assertEqual(False, ie.executable)
     self.assertEqual("directory", ie.kind)
     self.assertEqual({}, ie.children)
     self.assertEqual(b"somerevid", ie.revision)
     self.assertEqual(None, ie.text_sha1)
예제 #4
0
파일: backend.py 프로젝트: wil/vacuous
 def _collect(self, tree, path, cache=None):
     result = [(None, None, tree)]
     bits = filter(None, path.split(os.path.sep))
     repo = self.repo
     for i, bit in enumerate(bits):
         found = False
         for mode, name, hexsha in tree.entries():
             if name == bit:
                 found = True
                 if cache and hexsha in cache:
                     tree = cache[hexsha]
                 else:
                     tree = repo[hexsha]
                 result.append((mode, name, tree))
                 break
         if not found:
             result += [(self.directory_mode, bit, Tree())
                        for bit in bits[i:]]
             break
     return result
예제 #5
0
    def test_no_decode_encode(self):
        repo_dir = tempfile.mkdtemp()
        repo_dir_bytes = os.fsencode(repo_dir)
        self.addCleanup(shutil.rmtree, repo_dir)
        with Repo.init(repo_dir) as repo:

            # Populate repo
            file = Blob.from_string(b'foo')

            tree = Tree()
            latin1_name = u'À'.encode('latin1')
            latin1_path = os.path.join(repo_dir_bytes, latin1_name)
            utf8_name = u'À'.encode('utf8')
            utf8_path = os.path.join(repo_dir_bytes, utf8_name)
            tree[latin1_name] = (stat.S_IFREG | 0o644, file.id)
            tree[utf8_name] = (stat.S_IFREG | 0o644, file.id)

            repo.object_store.add_objects([(o, None) for o in [file, tree]])

            try:
                build_index_from_tree(repo.path, repo.index_path(),
                                      repo.object_store, tree.id)
            except OSError as e:
                if e.errno == 92 and sys.platform == 'darwin':
                    # Our filename isn't supported by the platform :(
                    self.skipTest('can not write filename %r' % e.filename)
                else:
                    raise
            except UnicodeDecodeError:
                # This happens e.g. with python3.6 on Windows.
                # It implicitly decodes using utf8, which doesn't work.
                self.skipTest('can not implicitly convert as utf8')

            # Verify index entries
            index = repo.open_index()
            self.assertIn(latin1_name, index)
            self.assertIn(utf8_name, index)

            self.assertTrue(os.path.exists(latin1_path))

            self.assertTrue(os.path.exists(utf8_path))
예제 #6
0
    def setUp(self):
        super(GraftsInMemoryRepoTests, self).setUp()
        r = self._repo = MemoryRepo()

        self._shas = []

        tree = Tree()

        commit_kwargs = {
            'committer': 'Test Committer <*****@*****.**>',
            'author': 'Test Author <*****@*****.**>',
            'commit_timestamp': 12395,
            'commit_timezone': 0,
            'author_timestamp': 12395,
            'author_timezone': 0,
            'tree': tree.id
        }

        self._shas.append(r.do_commit('empty commit', **commit_kwargs))
        self._shas.append(r.do_commit('empty commit', **commit_kwargs))
        self._shas.append(r.do_commit('empty commit', **commit_kwargs))
예제 #7
0
파일: backends.py 프로젝트: monocleman1/dd
 def checkout(self, commit=None, branch=None, retry=True):
     if commit is not None and isinstance(commit, string_types):
         commit = self.repo._repo.get_object(commit)
     if not commit:
         branches = OrderedDict(
             (('refs/heads/%s' % branch
               or 'master', 1), ('refs/heads/master', 1)))
         for ref in branches:
             try:
                 _commit_id = self.repo._repo.refs[ref]
             except KeyError:
                 pass
             else:
                 try:
                     commit = self.repo._repo.get_object(_commit_id)
                 except ObjectMissing:
                     if ref != 'refs/heads/master':
                         del self.repo._repo.refs[ref]
                     else:
                         six.reraise(*sys.exc_info())
                 else:
                     break
     if commit is not None and isinstance(commit, string_types):
         commit = self.repo._repo.get_object(commit)
     self._commit = commit
     if commit is None:
         tree = Tree()
     else:
         try:
             tree = self.repo._repo.get_object(commit.tree)
         except ObjectMissing:
             if retry and branch is not None:
                 if branch != 'master':
                     del self.repo._repo.refs['refs/heads/%s' % branch]
                     return self.checkout(branch='master', retry=False)
                 else:
                     six.reraise(*sys.exc_info())
     self._tree = tree
     self._working_tree = tree.copy()
     self._blobs = {}
예제 #8
0
    def test_send_pack_new_ref(self):
        self.rin.write(
            b'0064310ca9477129b8586fa2afc779c1f57cf64bba6c '
            b'refs/heads/master\x00 report-status delete-refs ofs-delta\n'
            b'0000000eunpack ok\n'
            b'0019ok refs/heads/blah12\n'
            b'0000')
        self.rin.seek(0)

        tree = Tree()
        commit = Commit()
        commit.tree = tree
        commit.parents = []
        commit.author = commit.committer = b'test user'
        commit.commit_time = commit.author_time = 1174773719
        commit.commit_timezone = commit.author_timezone = 0
        commit.encoding = b'UTF-8'
        commit.message = b'test message'

        def update_refs(refs):
            return {
                b'refs/heads/blah12': commit.id,
                b'refs/heads/master':
                b'310ca9477129b8586fa2afc779c1f57cf64bba6c'
            }

        def generate_pack_data(have, want, ofs_delta=False):
            return pack_objects_to_data([
                (commit, None),
                (tree, b''),
            ])

        f = BytesIO()
        write_pack_data(f, *generate_pack_data(None, None))
        self.client.send_pack(b'/', update_refs, generate_pack_data)
        self.assertEqual(
            self.rout.getvalue(),
            b'008b0000000000000000000000000000000000000000 ' + commit.id +
            b' refs/heads/blah12\x00delete-refs ofs-delta report-status0000' +
            f.getvalue())
예제 #9
0
    def set(self, path, obj, mode):
        path_items = path.encode(self.encoding).split(b'/')
        sub_tree = self.tree
        old_trees = [sub_tree]
        for name in path_items[:-1]:
            try:
                _, sub_tree_sha = sub_tree[name]
            except KeyError:
                sub_tree = Tree()
            else:
                sub_tree = self.lookup_obj(sub_tree_sha)
            old_trees.append(sub_tree)

        new_objs = []
        for old_tree, name in reversed(tuple(zip(old_trees, path_items))):
            new_tree = old_tree.copy()
            if obj is None or obj.id == b'4b825dc642cb6eb9a060e54bf8d69288fbee4904':
                if name not in new_tree:
                    raise KeyError(name)
                del new_tree[name]
                # print(f'del old: {old_tree} new: {new_tree} name: {name}')
            else:
                obj_id = obj.id
                new_objs.append(obj)
                new_tree[name] = (mode, obj_id)
                # print(f'set old: {old_tree} new: {new_tree} name: {name} obj_id: {obj_id}')

            obj = new_tree
            mode = stat.S_IFDIR

        new_objs.append(obj)
        self.tree = obj

        # print(f'old: {old_trees} new: {new_objs}')
        for old_tree in old_trees:
            if old_tree:
                with suppress(KeyError):
                    del self.changed_objects[old_tree.id]
        for obj in new_objs:
            self.changed_objects[obj.id] = obj
예제 #10
0
    def test_no_decode_encode(self):
        repo_dir = tempfile.mkdtemp()
        repo_dir_bytes = repo_dir.encode(sys.getfilesystemencoding())
        self.addCleanup(shutil.rmtree, repo_dir)
        with Repo.init(repo_dir) as repo:

            # Populate repo
            file = Blob.from_string(b'foo')

            tree = Tree()
            latin1_name = u'À'.encode('latin1')
            latin1_path = os.path.join(repo_dir_bytes, latin1_name)
            utf8_name = u'À'.encode('utf8')
            utf8_path = os.path.join(repo_dir_bytes, utf8_name)
            tree[latin1_name] = (stat.S_IFREG | 0o644, file.id)
            tree[utf8_name] = (stat.S_IFREG | 0o644, file.id)

            repo.object_store.add_objects(
                [(o, None) for o in [file, tree]])

            try:
                os.path.exists(latin1_path)
            except UnicodeDecodeError:
                # This happens e.g. with python3.6 on Windows.
                # It implicitly decodes using utf8, which doesn't work.
                self.skipTest('can not implicitly convert as utf8')

            build_index_from_tree(
                repo.path, repo.index_path(),
                repo.object_store, tree.id)

            # Verify index entries
            index = repo.open_index()
            self.assertIn(latin1_name, index)
            self.assertIn(utf8_name, index)

            self.assertTrue(os.path.exists(latin1_path))

            self.assertTrue(os.path.exists(utf8_path))
예제 #11
0
 def checkout(self, commit=None, branch=None, retry=True):
     if self._tree != self._working_tree:
         raise IOError('Can only switch from a clean repository')
     if commit is not None and isinstance(commit, string_types):
         commit = self.repo._repo.get_object(commit)
     if not commit:
         for ref in {'refs/heads/%s' % branch, 'refs/heads/master'}:
             try:
                 _commit_id = self.repo._repo.refs[ref]
             except KeyError:
                 pass
             else:
                 try:
                     commit = self.repo._repo.get_object(_commit_id)
                 except ObjectMissing:
                     if ref != 'refs/heads/master':
                         del self.repo._repo.refs[ref]
                     else:
                         six.reraise(*sys.exc_info())
                 else:
                     break
     if commit is not None and isinstance(commit, string_types):
         commit = self.repo._repo.get_object(commit)
     self._commit = commit
     if commit is None:
         tree = Tree()
     else:
         try:
             tree = self.repo._repo.get_object(commit.tree)
         except ObjectMissing:
             if retry and branch is not None:
                 if branch != 'master':
                     del self.repo._repo.refs['refs/heads/%s' % branch]
                     return self.checkout(branch='master', retry=False)
                 else:
                     six.reraise(*sys.exc_info())
     self._tree = tree
     self._working_tree = tree.copy()
     self._blobs = {}
예제 #12
0
    def _diff_between(self,
                      old_commit_sha,
                      new_commit_sha,
                      diff_function=None,
                      filter_binary=True):
        """Internal method for getting a diff between two commits
            Please use .diff method unless you have very specific needs
        """

        # If commit is first commit (new_commit_sha == old_commit_sha)
        # then compare to an empty tree
        if new_commit_sha == old_commit_sha:
            old_tree = Tree()
        else:
            old_tree = self._commit_tree(old_commit_sha)

        new_tree = self._commit_tree(new_commit_sha)

        return diff_function(self.repo.object_store,
                             old_tree,
                             new_tree,
                             filter_binary=filter_binary)
예제 #13
0
    def test_norewrite(self):
        repo_dir = tempfile.mkdtemp()
        self.addCleanup(shutil.rmtree, repo_dir)
        with Repo.init(repo_dir) as repo:
            # Populate repo
            filea = Blob.from_string(b'file a')
            filea_path = os.path.join(repo_dir, 'a')
            tree = Tree()
            tree[b'a'] = (stat.S_IFREG | 0o644, filea.id)

            repo.object_store.add_objects([(o, None)
                for o in [filea, tree]])

            # First Write
            build_index_from_tree(repo.path, repo.index_path(),
                                  repo.object_store, tree.id)
            # Use sync as metadata can be cached on some FS
            os.sync()
            mtime = os.stat(filea_path).st_mtime

            # Test Rewrite
            build_index_from_tree(repo.path, repo.index_path(),
                                  repo.object_store, tree.id)
            os.sync()
            self.assertEqual(mtime, os.stat(filea_path).st_mtime)

            # Modify content
            with open(filea_path, 'wb') as fh:
                fh.write(b'test a')
            os.sync()
            mtime = os.stat(filea_path).st_mtime

            # Test rewrite
            build_index_from_tree(repo.path, repo.index_path(),
                                  repo.object_store, tree.id)
            os.sync()
            with open(filea_path, 'rb') as fh:
                self.assertEqual(b'file a', fh.read())
예제 #14
0
    def test_send_pack_no_sideband64k_with_update_ref_error(self):
        # No side-bank-64k reported by server shouldn't try to parse
        # side band data
        pkts = [
            '55dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7 capabilities^{}'
            '\x00 report-status delete-refs ofs-delta\n', '', "unpack ok",
            "ng refs/foo/bar pre-receive hook declined", ''
        ]
        for pkt in pkts:
            if pkt == '':
                self.rin.write("0000")
            else:
                self.rin.write("%04x%s" % (len(pkt) + 4, pkt))
        self.rin.seek(0)

        tree = Tree()
        commit = Commit()
        commit.tree = tree
        commit.parents = []
        commit.author = commit.committer = 'test user'
        commit.commit_time = commit.author_time = 1174773719
        commit.commit_timezone = commit.author_timezone = 0
        commit.encoding = 'UTF-8'
        commit.message = 'test message'

        def determine_wants(refs):
            return {
                'refs/foo/bar': commit.id,
            }

        def generate_pack_contents(have, want):
            return [
                (commit, None),
                (tree, ''),
            ]

        self.assertRaises(UpdateRefsError, self.client.send_pack, "blah",
                          determine_wants, generate_pack_contents)
예제 #15
0
    def test_send_pack_no_sideband64k_with_update_ref_error(self):
        # No side-bank-64k reported by server shouldn't try to parse
        # side band data
        pkts = [
            b'55dcc6bf963f922e1ed5c4bbaaefcfacef57b1d7 capabilities^{}'
            b'\x00 report-status delete-refs ofs-delta\n', b'', b"unpack ok",
            b"ng refs/foo/bar pre-receive hook declined", b''
        ]
        for pkt in pkts:
            if pkt == b'':
                self.rin.write(b"0000")
            else:
                self.rin.write(("%04x" % (len(pkt) + 4)).encode('ascii') + pkt)
        self.rin.seek(0)

        tree = Tree()
        commit = Commit()
        commit.tree = tree
        commit.parents = []
        commit.author = commit.committer = b'test user'
        commit.commit_time = commit.author_time = 1174773719
        commit.commit_timezone = commit.author_timezone = 0
        commit.encoding = b'UTF-8'
        commit.message = b'test message'

        def update_refs(refs):
            return {
                b'refs/foo/bar': commit.id,
            }

        def generate_pack_data(have, want, ofs_delta=False):
            return pack_objects_to_data([
                (commit, None),
                (tree, ''),
            ])

        self.assertRaises(UpdateRefsError, self.client.send_pack, "blah",
                          update_refs, generate_pack_data)
예제 #16
0
def step_impl_given(context):
    context.test_git_repo_dir = tempfile.mkdtemp('paasta_tools_deployments_json_itest')
    context.test_git_repo = Repo.init(context.test_git_repo_dir)
    print 'Temp repo in %s' % context.test_git_repo_dir

    blob = Blob.from_string("My file content\n")
    tree = Tree()
    tree.add("spam", 0100644, blob.id)

    commit = Commit()
    commit.author = commit.committer = "itest author"
    commit.commit_time = commit.author_time = int(time())
    commit.commit_timezone = commit.author_timezone = parse_timezone('-0200')[0]
    commit.message = "Initial commit"
    commit.tree = tree.id

    object_store = context.test_git_repo.object_store
    object_store.add_object(blob)
    object_store.add_object(tree)
    object_store.add_object(commit)

    context.test_git_repo.refs['refs/heads/paasta-test_cluster.test_instance'] = commit.id
    context.expected_commit = commit.id
예제 #17
0
 def test_import_tree_with_file(self):
     blob = Blob.from_string(b"bar1")
     tree = Tree()
     tree.add(b"foo", stat.S_IFREG | 0o644, blob.id)
     objects = {blob.id: blob, tree.id: tree}
     ret, child_modes = import_git_tree(
         self._texts, self._mapping, b"bla", b"bla", (None, tree.id), None,
         None, b"somerevid", [], objects.__getitem__, (None, stat.S_IFDIR),
         DummyStoreUpdater(), self._mapping.generate_file_id)
     self.assertEqual(child_modes, {})
     self.assertEqual(2, len(ret))
     self.assertEqual(None, ret[0][0])
     self.assertEqual("bla", ret[0][1])
     self.assertEqual(None, ret[1][0])
     self.assertEqual("bla/foo", ret[1][1])
     ie = ret[0][3]
     self.assertEqual("directory", ie.kind)
     ie = ret[1][3]
     self.assertEqual("file", ie.kind)
     self.assertEqual(b"git:bla/foo", ie.file_id)
     self.assertEqual(b"somerevid", ie.revision)
     self.assertEqual(osutils.sha_strings([b"bar1"]), ie.text_sha1)
     self.assertEqual(False, ie.executable)
예제 #18
0
def render_tree(tree, path):
    new_tree = Tree()

    for entry in tree.items():
        item = repo[entry.sha]
        if isinstance(item, Tree):
            new_tree.add(entry.path, entry.mode,
                         render_tree(item, path + (entry.path, )))
        elif isinstance(item, Blob):
            if entry.path.startswith(".") or (
                    "." not in entry.path) or entry.path.endswith(".py"):
                continue
            if not entry.path.endswith(".rst"):
                new_tree.add(entry.path, entry.mode, entry.sha)
            else:
                name = "index.html" if entry.path == 'README.rst' else (
                    entry.path[:-4] + ".html")
                new_tree.add(
                    name, entry.mode,
                    render_rst(item, os.path.join(*(path + (name, )))))

    store.add_object(new_tree)
    return new_tree.id
예제 #19
0
 def test_simple_bytesio(self):
     f = BytesIO()
     c = Commit()
     c.committer = c.author = b"Jelmer <*****@*****.**>"
     c.commit_time = c.author_time = 1271350201
     c.commit_timezone = c.author_timezone = 0
     c.message = b"This is the first line\nAnd this is the second line.\n"
     c.tree = Tree().id
     write_commit_patch(f, c, b"CONTENTS", (1, 1), version="custom")
     f.seek(0)
     lines = f.readlines()
     self.assertTrue(lines[0].startswith(
         b"From 0b0d34d1b5b596c928adc9a727a4b9e03d025298"))
     self.assertEqual(lines[1], b"From: Jelmer <*****@*****.**>\n")
     self.assertTrue(lines[2].startswith(b"Date: "))
     self.assertEqual([
         b"Subject: [PATCH 1/1] This is the first line\n",
         b"And this is the second line.\n", b"\n", b"\n", b"---\n"
     ], lines[3:8])
     self.assertEqual([b"CONTENTS-- \n", b"custom\n"], lines[-2:])
     if len(lines) >= 12:
         # diffstat may not be present
         self.assertEqual(lines[8], b" 0 files changed\n")
예제 #20
0
 def test_directory_converted_to_submodule(self):
     base_inv = Inventory()
     base_inv.add_path("foo", "directory")
     base_inv.add_path("foo/bar", "file")
     othertree = Blob.from_string(b"someotherthing")
     blob = Blob.from_string(b"bar")
     tree = Tree()
     tree.add(b"bar", 0o160000, blob.id)
     objects = {tree.id: tree}
     ret, child_modes = import_git_submodule(
         self._texts, self._mapping, b"foo", b"foo",
         (tree.id, othertree.id), base_inv, base_inv.root.file_id,
         b"somerevid", [],
         objects.__getitem__, (stat.S_IFDIR | 0o755, S_IFGITLINK),
         DummyStoreUpdater(), self._mapping.generate_file_id)
     self.assertEqual(child_modes, {})
     self.assertEqual(2, len(ret))
     self.assertEqual(ret[0],
                      ("foo/bar", None, base_inv.path2id("foo/bar"), None))
     self.assertEqual(ret[1][:3],
                      ("foo", "foo", self._mapping.generate_file_id("foo")))
     ie = ret[1][3]
     self.assertEqual(ie.kind, "tree-reference")
예제 #21
0
    def _update_file(self, name, subdir, filename, data, commit_msg):
        # first, create a new blob for the data
        blob = Blob.from_string(data.encode('utf-8'))

        # fetch the old tree object, add new page
        try:
            subdir_tree = _walk_git_repo_tree(self.repo, self.current_tree,
                                              subdir)
        except KeyError:
            # we need to create the subdir_tree as well, since it does not exist
            # yet
            subdir_tree = Tree()
        subdir_tree.add(_git_default_file_mode, filename, blob.id)

        # create new root tree
        tree = self.current_tree
        tree.add(stat.S_IFDIR, subdir, subdir_tree.id)

        # create commit
        commit = Commit()
        commit.parents = [self.current_commit.id]
        commit.tree = tree.id
        commit.author = commit.committer = self.wiki_user
        commit.commit_time = commit.author_time = int(time.time())
        commit.commit_timezone = commit.author_timezone = parse_timezone(
            time.timezone)[0]
        commit.encoding = 'UTF-8'
        commit.message = commit_msg.encode('utf-8')

        # store all objects
        self.repo.object_store.add_object(blob)
        self.repo.object_store.add_object(subdir_tree)
        self.repo.object_store.add_object(tree)
        self.repo.object_store.add_object(commit)

        # update the branch
        self.repo.refs[self.head] = commit.id
예제 #22
0
    def write(self, data):
        commit = Commit()

        # commit metadata
        author = b"tinydb"
        commit.author = commit.committer = author
        commit.commit_time = commit.author_time = int(time.time())
        tz = time.timezone if (time.localtime().tm_isdst) else time.altzone
        commit.commit_timezone = commit.author_timezone = tz
        commit.encoding = b'UTF-8'
        commit.message = (
            'Updated by tinydb-git {}'.format(__version__).encode('utf8'))

        # prepare blob
        blob = Blob.from_string(self._serialize(data))

        try:
            parent_commit = self.repo[self._refname]
        except KeyError:
            # branch does not exist, start with an empty tree
            tree = Tree()
        else:
            commit.parents = [parent_commit.id]
            tree = self.repo[parent_commit.tree]

        # no subdirs in filename, add directly to tree
        tree.add(self.filename, 0o100644, blob.id)

        commit.tree = tree.id

        # add objects
        self.repo.object_store.add_object(blob)
        self.repo.object_store.add_object(tree)
        self.repo.object_store.add_object(commit)

        # update refs
        self.repo.refs[self._refname] = commit.id
예제 #23
0
    def _put(self, key, data):
        commit = self._create_top_commit()
        commit.message = ('Updated key {}'.format(self.subdir + '/' +
                                                  key)).encode('utf8')

        blob = Blob.from_string(data)

        try:
            parent_commit = self.repo[self._refname]
        except KeyError:
            # branch does not exist, start with an empty tree
            tree = Tree()
        else:
            commit.parents = [parent_commit.id]
            tree = self.repo[parent_commit.tree]

        objects_to_add = [blob]

        # no subdirs in filename, add directly to tree
        components = [key.encode('ascii')]
        if self.subdir:
            components = self._subdir_components + components
        res = _on_tree(self.repo, tree, components, blob)
        objects_to_add.extend(res)

        commit.tree = res[-1].id
        objects_to_add.append(commit)

        # add objects
        for obj in objects_to_add:
            self.repo.object_store.add_object(obj)

        # update refs
        self.repo.refs[self._refname] = commit.id

        return key
예제 #24
0
    def test_git_dir(self):
        if os.name != 'posix':
            self.skipTest("test depends on POSIX shell")

        repo_dir = tempfile.mkdtemp()
        repo = Repo.init(repo_dir)
        self.addCleanup(shutil.rmtree, repo_dir)

        # Populate repo
        filea = Blob.from_string(b'file a')
        filee = Blob.from_string(b'd')

        tree = Tree()
        tree[b'.git/a'] = (stat.S_IFREG | 0o644, filea.id)
        tree[b'c/e'] = (stat.S_IFREG | 0o644, filee.id)

        repo.object_store.add_objects([(o, None)
                                       for o in [filea, filee, tree]])

        build_index_from_tree(repo.path, repo.index_path(), repo.object_store,
                              tree.id)

        # Verify index entries
        index = repo.open_index()
        self.assertEqual(len(index), 1)

        # filea
        apath = os.path.join(repo.path, '.git', 'a')
        self.assertFalse(os.path.exists(apath))

        # filee
        epath = os.path.join(repo.path, 'c', 'e')
        self.assertTrue(os.path.exists(epath))
        self.assertReasonableIndexEntry(index[b'c/e'], stat.S_IFREG | 0o644, 1,
                                        filee.id)
        self.assertFileContents(epath, b'd')
예제 #25
0
 def checkout(self, commit=None, branch=None):
     if self._tree != self._working_tree:
         raise IOError('Can only switch from a clean repository')
     if commit is not None and isinstance(commit, string_types):
         commit = self.repo._repo.get_object(commit)
     if not commit:
         for ref in {'refs/heads/%s' % branch, 'refs/heads/master'}:
             try:
                 _commit_id = self.repo._repo.refs[ref]
             except KeyError:
                 pass
             else:
                 commit = self.repo._repo.get_object(_commit_id)
                 break
     if commit is not None and isinstance(commit, string_types):
         commit = self.repo._repo.get_object(commit)
     self._commit = commit
     if commit is None:
         tree = Tree()
     else:
         tree = self.repo._repo.get_object(commit.tree)
     self._tree = tree
     self._working_tree = tree.copy()
     self._blobs = {}
def step_impl_given(context):
    context.test_git_repo_dir = tempfile.mkdtemp("paasta_tools_deployments_json_itest")
    context.test_git_repo = Repo.init(context.test_git_repo_dir)
    paasta_print("Temp repo in %s" % context.test_git_repo_dir)

    blob = Blob.from_string(b"My file content\n")
    tree = Tree()
    tree.add(b"spam", 0o0100644, blob.id)

    commit = Commit()
    commit.author = commit.committer = b"itest author"
    commit.commit_time = commit.author_time = int(time())
    commit.commit_timezone = commit.author_timezone = parse_timezone(b"-0200")[0]
    commit.message = b"Initial commit"
    commit.tree = tree.id

    object_store = context.test_git_repo.object_store
    object_store.add_object(blob)
    object_store.add_object(tree)
    object_store.add_object(commit)

    context.test_git_repo.refs[b"refs/heads/master"] = commit.id
    context.expected_commit_as_bytes = commit.id
    context.expected_commit = context.expected_commit_as_bytes.decode()
예제 #27
0
def make_release_tree(store, sha):
    tree = Tree()
    tree.add(sha, 040000, make_preview(store))

    names = [
        ("code","zip"),
        ("exercise","zip"),
        ("src","zip"),
        ("screen","pdf"),
        ("print","pdf")]

    files = [("%s.%s.%s"%(a,sha,b), "build/%s.%s"%(a,b)) for a,b in names]
    add_files(store, tree, files)

    date = formatdate(commit.author_time, commit.author_timezone)

    with open("index.html", "rb") as f:
        html = f.read().format(date=date, sha=sha)

    blob = Blob.from_string(html)
    store.add_object(blob)
    tree.add("index.html", 0100644, blob.id)
    store.add_object(tree)
    return tree.id
예제 #28
0
 def test_get_ctag(self):
     gc = self.create_store()
     self.assertEqual(Tree().id.decode('ascii'), gc.get_ctag())
     self.add_blob(gc, 'foo.ics', EXAMPLE_VCALENDAR1)
     self.assertEqual(gc._get_current_tree().id.decode('ascii'),
                      gc.get_ctag())
예제 #29
0
파일: git.py 프로젝트: raony/gitdb
 def current_tree(self):
     return self.__get_object__(
         self.current_commit.tree) if self.current_commit else Tree()
예제 #30
0
파일: git.py 프로젝트: raony/gitdb
 def __create_tree__(self, parent_list, child):
     tree = Tree()
     parent_list[-1].add(child.encode(ENCODING), 0o040000, tree.id)
     parent_list.append(tree)
     return parent_list