本文整理汇总了Python中git.IndexFile类的典型用法代码示例。如果您正苦于以下问题:Python IndexFile类的具体用法?Python IndexFile怎么用?Python IndexFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IndexFile类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_index_merge_tree
def test_index_merge_tree(self, rw_repo):
# A bit out of place, but we need a different repo for this:
self.assertNotEqual(self.rorepo, rw_repo)
self.assertEqual(len(set((self.rorepo, self.rorepo, rw_repo, rw_repo))), 2)
# SINGLE TREE MERGE
# current index is at the (virtual) cur_commit
next_commit = "4c39f9da792792d4e73fc3a5effde66576ae128c"
parent_commit = rw_repo.head.commit.parents[0]
manifest_key = IndexFile.entry_key('MANIFEST.in', 0)
manifest_entry = rw_repo.index.entries[manifest_key]
rw_repo.index.merge_tree(next_commit)
# only one change should be recorded
assert manifest_entry.binsha != rw_repo.index.entries[manifest_key].binsha
rw_repo.index.reset(rw_repo.head)
self.assertEqual(rw_repo.index.entries[manifest_key].binsha, manifest_entry.binsha)
# FAKE MERGE
#############
# Add a change with a NULL sha that should conflict with next_commit. We
# pretend there was a change, but we do not even bother adding a proper
# sha for it ( which makes things faster of course )
manifest_fake_entry = BaseIndexEntry((manifest_entry[0], b"\0" * 20, 0, manifest_entry[3]))
# try write flag
self._assert_entries(rw_repo.index.add([manifest_fake_entry], write=False))
# add actually resolves the null-hex-sha for us as a feature, but we can
# edit the index manually
assert rw_repo.index.entries[manifest_key].binsha != Object.NULL_BIN_SHA
# must operate on the same index for this ! Its a bit problematic as
# it might confuse people
index = rw_repo.index
index.entries[manifest_key] = IndexEntry.from_base(manifest_fake_entry)
index.write()
self.assertEqual(rw_repo.index.entries[manifest_key].hexsha, Diff.NULL_HEX_SHA)
# write an unchanged index ( just for the fun of it )
rw_repo.index.write()
# a three way merge would result in a conflict and fails as the command will
# not overwrite any entries in our index and hence leave them unmerged. This is
# mainly a protection feature as the current index is not yet in a tree
self.failUnlessRaises(GitCommandError, index.merge_tree, next_commit, base=parent_commit)
# the only way to get the merged entries is to safe the current index away into a tree,
# which is like a temporary commit for us. This fails as well as the NULL sha deos not
# have a corresponding object
# NOTE: missing_ok is not a kwarg anymore, missing_ok is always true
# self.failUnlessRaises(GitCommandError, index.write_tree)
# if missing objects are okay, this would work though ( they are always okay now )
# As we can't read back the tree with NULL_SHA, we rather set it to something else
index.entries[manifest_key] = IndexEntry(manifest_entry[:1] + (hex_to_bin('f' * 40),) + manifest_entry[2:])
tree = index.write_tree()
# now make a proper three way merge with unmerged entries
unmerged_tree = IndexFile.from_tree(rw_repo, parent_commit, tree, next_commit)
unmerged_blobs = unmerged_tree.unmerged_blobs()
self.assertEqual(len(unmerged_blobs), 1)
self.assertEqual(list(unmerged_blobs.keys())[0], manifest_key[0])
示例2: test_index_file_base
def test_index_file_base(self):
# read from file
index = IndexFile(self.rorepo, fixture_path("index"))
assert index.entries
assert index.version > 0
# test entry
entry = next(iter(index.entries.values()))
for attr in ("path", "ctime", "mtime", "dev", "inode", "mode", "uid",
"gid", "size", "binsha", "hexsha", "stage"):
getattr(entry, attr)
# END for each method
# test update
entries = index.entries
assert isinstance(index.update(), IndexFile)
assert entries is not index.entries
# test stage
index_merge = IndexFile(self.rorepo, fixture_path("index_merge"))
self.assertEqual(len(index_merge.entries), 106)
assert len(list(e for e in index_merge.entries.values() if e.stage != 0))
# write the data - it must match the original
tmpfile = tempfile.mktemp()
index_merge.write(tmpfile)
with open(tmpfile, 'rb') as fp:
self.assertEqual(fp.read(), fixture("index_merge"))
os.remove(tmpfile)
示例3: test_index_file_from_tree
def test_index_file_from_tree(self, rw_repo):
if sys.version_info < (2, 7):
## Skipped, not `assertRaisesRegexp` in py2.6
return
common_ancestor_sha = "5117c9c8a4d3af19a9958677e45cda9269de1541"
cur_sha = "4b43ca7ff72d5f535134241e7c797ddc9c7a3573"
other_sha = "39f85c4358b7346fee22169da9cad93901ea9eb9"
# simple index from tree
base_index = IndexFile.from_tree(rw_repo, common_ancestor_sha)
assert base_index.entries
self._cmp_tree_index(common_ancestor_sha, base_index)
# merge two trees - its like a fast-forward
two_way_index = IndexFile.from_tree(rw_repo, common_ancestor_sha, cur_sha)
assert two_way_index.entries
self._cmp_tree_index(cur_sha, two_way_index)
# merge three trees - here we have a merge conflict
three_way_index = IndexFile.from_tree(rw_repo, common_ancestor_sha, cur_sha, other_sha)
assert len(list(e for e in three_way_index.entries.values() if e.stage != 0))
# ITERATE BLOBS
merge_required = lambda t: t[0] != 0
merge_blobs = list(three_way_index.iter_blobs(merge_required))
assert merge_blobs
assert merge_blobs[0][0] in (1, 2, 3)
assert isinstance(merge_blobs[0][1], Blob)
# test BlobFilter
prefix = 'lib/git'
for stage, blob in base_index.iter_blobs(BlobFilter([prefix])): # @UnusedVariable
assert blob.path.startswith(prefix)
# writing a tree should fail with an unmerged index
self.failUnlessRaises(UnmergedEntriesError, three_way_index.write_tree)
# removed unmerged entries
unmerged_blob_map = three_way_index.unmerged_blobs()
assert unmerged_blob_map
# pick the first blob at the first stage we find and use it as resolved version
three_way_index.resolve_blobs(l[0][1] for l in unmerged_blob_map.values())
tree = three_way_index.write_tree()
assert isinstance(tree, Tree)
num_blobs = 0
for blob in tree.traverse(predicate=lambda item, d: item.type == "blob"):
assert (blob.path, 0) in three_way_index.entries
num_blobs += 1
# END for each blob
self.assertEqual(num_blobs, len(three_way_index.entries))
示例4: test__to_relative_path_at_root
def test__to_relative_path_at_root(self):
root = osp.abspath(os.sep)
class Mocked(object):
bare = False
git_dir = root
working_tree_dir = root
repo = Mocked()
path = os.path.join(root, 'file')
index = IndexFile(repo)
rel = index._to_relative_path(path)
self.assertEqual(rel, os.path.relpath(path, root))
示例5: test_index_new
def test_index_new(self):
B = self.rorepo.tree("6d9b1f4f9fa8c9f030e3207e7deacc5d5f8bba4e")
H = self.rorepo.tree("25dca42bac17d511b7e2ebdd9d1d679e7626db5f")
M = self.rorepo.tree("e746f96bcc29238b79118123028ca170adc4ff0f")
for args in ((B,), (B, H), (B, H, M)):
index = IndexFile.new(self.rorepo, *args)
assert isinstance(index, IndexFile)
示例6: time_warp
def time_warp(self, c_o):
"""
History rewriting occurs here. We read everything from the original
commit, reformat the python, and checkin, mirroring the original
commit history.
:param c_o: Commit object representing "before"
:return: None
"""
log.info('warping: {} | {} | {:f} MB | {}s'.format(
time_convert(c_o.authored_date, c_o.author_tz_offset),
c_o.summary,
resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1000,
time.clock()))
items = self.handle_commit(c_o)
parent_commits = tuple(self.converted[v] for v in c_o.parents)
# for the singular case of init / root / the genesis
if len(parent_commits) == 0:
parent_commits = {c_o}
self.repo.head.reference = c_o
self.repo.head.reset(index=True, working_tree=True)
idx = IndexFile(self.repo)
idx.add(items)
idx.write_tree()
com_msg = [c_o.message]
com_msg.extend('\n'.join(self.convert_errors))
self.convert_errors = [] # todo: rearchitect - too easy to forget
com_msg.append(
'\n[gitreformat yapf-ify (github/ghtdak) on {}]'.format(
time.strftime('%c')))
com_msg.append('\n[from commit: {}]'.format(c_o.hexsha))
c_n = idx.commit(
''.join(com_msg),
parent_commits=parent_commits,
author=c_o.author,
author_date=time_convert(c_o.authored_date,
c_o.author_tz_offset),
committer=c_o.committer,
commit_date=time_convert(c_o.committed_date,
c_o.committer_tz_offset))
self.repo.head.reference = c_n
self.repo.head.reset(index=True, working_tree=True)
self.verify_paths(c_o.tree, c_n.tree)
self.converted[c_o] = c_n
return c_n
示例7: test_references_and_objects
#.........这里部分代码省略.........
past = repo.commit('HEAD~5')
assert repo.tree(past) == repo.tree(past.hexsha)
assert repo.tree('v0.8.1').type == 'tree' # yes, you can provide any refspec - works everywhere
# ![21-test_references_and_objects]
# [22-test_references_and_objects]
assert len(tree) < len(list(tree.traverse()))
# ![22-test_references_and_objects]
# [23-test_references_and_objects]
index = repo.index
# The index contains all blobs in a flat list
assert len(list(index.iter_blobs())) == len([o for o in repo.head.commit.tree.traverse() if o.type == 'blob'])
# Access blob objects
for (path, stage), entry in index.entries.items():
pass
new_file_path = os.path.join(repo.working_tree_dir, 'new-file-name')
open(new_file_path, 'w').close()
index.add([new_file_path]) # add a new file to the index
index.remove(['LICENSE']) # remove an existing one
assert os.path.isfile(os.path.join(repo.working_tree_dir, 'LICENSE')) # working tree is untouched
assert index.commit("my commit message").type == 'commit' # commit changed index
repo.active_branch.commit = repo.commit('HEAD~1') # forget last commit
from git import Actor
author = Actor("An author", "[email protected]")
committer = Actor("A committer", "[email protected]")
# commit by commit message and author and committer
index.commit("my commit message", author=author, committer=committer)
# ![23-test_references_and_objects]
# [24-test_references_and_objects]
from git import IndexFile
# loads a tree into a temporary index, which exists just in memory
IndexFile.from_tree(repo, 'HEAD~1')
# merge two trees three-way into memory
merge_index = IndexFile.from_tree(repo, 'HEAD~10', 'HEAD', repo.merge_base('HEAD~10', 'HEAD'))
# and persist it
merge_index.write(os.path.join(rw_dir, 'merged_index'))
# ![24-test_references_and_objects]
# [25-test_references_and_objects]
empty_repo = git.Repo.init(os.path.join(rw_dir, 'empty'))
origin = empty_repo.create_remote('origin', repo.remotes.origin.url)
assert origin.exists()
assert origin == empty_repo.remotes.origin == empty_repo.remotes['origin']
origin.fetch() # assure we actually have data. fetch() returns useful information
# Setup a local tracking branch of a remote branch
empty_repo.create_head('master', origin.refs.master).set_tracking_branch(origin.refs.master)
origin.rename('new_origin') # rename remotes
# push and pull behaves similarly to `git push|pull`
origin.pull()
origin.push()
# assert not empty_repo.delete_remote(origin).exists() # create and delete remotes
# ![25-test_references_and_objects]
# [26-test_references_and_objects]
assert origin.url == repo.remotes.origin.url
cw = origin.config_writer
cw.set("pushurl", "other_url")
cw.release()
# Please note that in python 2, writing origin.config_writer.set(...) is totally safe.
# In py3 __del__ calls can be delayed, thus not writing changes in time.
# ![26-test_references_and_objects]
示例8: test_index_file_diffing
def test_index_file_diffing(self, rw_repo):
# default Index instance points to our index
index = IndexFile(rw_repo)
assert index.path is not None
assert len(index.entries)
# write the file back
index.write()
# could sha it, or check stats
# test diff
# resetting the head will leave the index in a different state, and the
# diff will yield a few changes
cur_head_commit = rw_repo.head.reference.commit
rw_repo.head.reset('HEAD~6', index=True, working_tree=False)
# diff against same index is 0
diff = index.diff()
self.assertEqual(len(diff), 0)
# against HEAD as string, must be the same as it matches index
diff = index.diff('HEAD')
self.assertEqual(len(diff), 0)
# against previous head, there must be a difference
diff = index.diff(cur_head_commit)
assert len(diff)
# we reverse the result
adiff = index.diff(str(cur_head_commit), R=True)
odiff = index.diff(cur_head_commit, R=False) # now its not reversed anymore
assert adiff != odiff
self.assertEqual(odiff, diff) # both unreversed diffs against HEAD
# against working copy - its still at cur_commit
wdiff = index.diff(None)
assert wdiff != adiff
assert wdiff != odiff
# against something unusual
self.failUnlessRaises(ValueError, index.diff, int)
# adjust the index to match an old revision
cur_branch = rw_repo.active_branch
cur_commit = cur_branch.commit
rev_head_parent = 'HEAD~1'
assert index.reset(rev_head_parent) is index
self.assertEqual(cur_branch, rw_repo.active_branch)
self.assertEqual(cur_commit, rw_repo.head.commit)
# there must be differences towards the working tree which is in the 'future'
assert index.diff(None)
# reset the working copy as well to current head,to pull 'back' as well
new_data = b"will be reverted"
file_path = osp.join(rw_repo.working_tree_dir, "CHANGES")
with open(file_path, "wb") as fp:
fp.write(new_data)
index.reset(rev_head_parent, working_tree=True)
assert not index.diff(None)
self.assertEqual(cur_branch, rw_repo.active_branch)
self.assertEqual(cur_commit, rw_repo.head.commit)
with open(file_path, 'rb') as fp:
assert fp.read() != new_data
# test full checkout
test_file = osp.join(rw_repo.working_tree_dir, "CHANGES")
with open(test_file, 'ab') as fd:
fd.write(b"some data")
rval = index.checkout(None, force=True, fprogress=self._fprogress)
assert 'CHANGES' in list(rval)
self._assert_fprogress([None])
assert osp.isfile(test_file)
os.remove(test_file)
rval = index.checkout(None, force=False, fprogress=self._fprogress)
assert 'CHANGES' in list(rval)
self._assert_fprogress([None])
assert osp.isfile(test_file)
# individual file
os.remove(test_file)
rval = index.checkout(test_file, fprogress=self._fprogress)
self.assertEqual(list(rval)[0], 'CHANGES')
self._assert_fprogress([test_file])
assert osp.exists(test_file)
# checking out non-existing file throws
self.failUnlessRaises(CheckoutError, index.checkout, "doesnt_exist_ever.txt.that")
self.failUnlessRaises(CheckoutError, index.checkout, paths=["doesnt/exist"])
# checkout file with modifications
append_data = b"hello"
with open(test_file, "ab") as fp:
fp.write(append_data)
try:
index.checkout(test_file)
except CheckoutError as e:
#.........这里部分代码省略.........