-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.py
More file actions
83 lines (74 loc) · 2.74 KB
/
git.py
File metadata and controls
83 lines (74 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import pygit2
import time
from config import *
class Git:
repo = None
###Initializing
def git_init(self):
try:
self.repo = pygit2.Repository(base_path)
except Exception,data:
print 'First Time, Init Repository NOW'
self.repo = pygit2.init_repository(base_path, bare=True)
if self.repo.is_empty:
self.git_do_first_commit()
###Commiting
def git_do_commit_with_workdir_modify(self, file_name, message):
index = self.repo.index
index.add(file_name)
index.write()
tree_oid = index.write_tree()
self.git_do_commit_with_tree_oid(tree_oid, message)
def git_do_commit_with_tree_oid(self, tree_oid, message):
author = pygit2.Signature('zjw', '[email protected]', int(time.time()), 480);
self.repo.create_commit('HEAD', author, author, message, tree_oid, [] if self.repo.is_empty else [self.repo.head.target])
def git_do_commit_with_content(self, file_name, message, content):
blob_oid = self.repo.create_blob(content)
try:
head_commit_tree = self.repo[self.repo.head.target].tree
tree_builder = self.repo.TreeBuilder(head_commit_tree)
except:#first commit, head_commit_tree does not exist
tree_builder = self.repo.TreeBuilder()
tree_builder.insert(file_name, blob_oid, pygit2.GIT_FILEMODE_BLOB)
tree_oid = tree_builder.write()
self.git_do_commit_with_tree_oid(tree_oid, message)
def git_do_first_commit(self):
self.git_do_commit_with_content('README', 'Initialize Commit','Initialize Commit')
###GET BLOB DATA
def git_blob_data_from_head_commit(self, file_name):
commit = self.repo[self.repo.head.target];
return self.git_blob_data_from_commit(commit, file_name)
def git_blob_data_from_comimit_oid(self, commit_oid, file_name):
commit = self.repo[commit_oid]
return self.git_blob_data_from_commit(commit, file_name)
def git_blob_data_from_commit(self, commit, file_name):
if file_name in commit.tree :
tree_entry = commit.tree[file_name]
else:
return ''
blob = self.repo[tree_entry.oid]
return blob.data;
def git_file_history(self, file_name):
commits = []
last_oid = None
for commit in self.repo.walk(self.repo.head.target, pygit2.GIT_SORT_TOPOLOGICAL | pygit2.GIT_SORT_REVERSE):
if file_name in commit.tree:
file_oid = commit.tree[file_name].oid
has_changed = (last_oid != file_oid)
if not has_changed:
continue
else:
last_oid = file_oid
else:
continue
commits.insert(0,commit)
return commits
def git_file_list(self):
commit = self.repo.revparse_single('HEAD')
tree = commit.tree
file_names = []
for tree_entry in tree:
file_names.append(tree_entry.name)
return file_names
git = Git()
git.git_init()