Commit | Line | Data |
---|---|---|
cbe4567e KH |
1 | import os, os.path, re |
2 | from stgit import exception, run, utils | |
3 | ||
4 | class RepositoryException(exception.StgException): | |
5 | pass | |
6 | ||
7 | class DetachedHeadException(RepositoryException): | |
8 | def __init__(self): | |
9 | RepositoryException.__init__(self, 'Not on any branch') | |
10 | ||
11 | class Repr(object): | |
12 | def __repr__(self): | |
13 | return str(self) | |
14 | ||
15 | class NoValue(object): | |
16 | pass | |
17 | ||
18 | def make_defaults(defaults): | |
19 | def d(val, attr): | |
20 | if val != NoValue: | |
21 | return val | |
22 | elif defaults != NoValue: | |
23 | return getattr(defaults, attr) | |
24 | else: | |
25 | return None | |
26 | return d | |
27 | ||
28 | class Person(Repr): | |
29 | """Immutable.""" | |
30 | def __init__(self, name = NoValue, email = NoValue, | |
31 | date = NoValue, defaults = NoValue): | |
32 | d = make_defaults(defaults) | |
33 | self.__name = d(name, 'name') | |
34 | self.__email = d(email, 'email') | |
35 | self.__date = d(date, 'date') | |
36 | name = property(lambda self: self.__name) | |
37 | email = property(lambda self: self.__email) | |
38 | date = property(lambda self: self.__date) | |
39 | def set_name(self, name): | |
40 | return type(self)(name = name, defaults = self) | |
41 | def set_email(self, email): | |
42 | return type(self)(email = email, defaults = self) | |
43 | def set_date(self, date): | |
44 | return type(self)(date = date, defaults = self) | |
45 | def __str__(self): | |
46 | return '%s <%s> %s' % (self.name, self.email, self.date) | |
47 | @classmethod | |
48 | def parse(cls, s): | |
49 | m = re.match(r'^([^<]*)<([^>]*)>\s+(\d+\s+[+-]\d{4})$', s) | |
50 | assert m | |
51 | name = m.group(1).strip() | |
52 | email = m.group(2) | |
53 | date = m.group(3) | |
54 | return cls(name, email, date) | |
55 | ||
56 | class Tree(Repr): | |
57 | """Immutable.""" | |
58 | def __init__(self, sha1): | |
59 | self.__sha1 = sha1 | |
60 | sha1 = property(lambda self: self.__sha1) | |
61 | def __str__(self): | |
62 | return 'Tree<%s>' % self.sha1 | |
63 | ||
64 | class Commitdata(Repr): | |
65 | """Immutable.""" | |
66 | def __init__(self, tree = NoValue, parents = NoValue, author = NoValue, | |
67 | committer = NoValue, message = NoValue, defaults = NoValue): | |
68 | d = make_defaults(defaults) | |
69 | self.__tree = d(tree, 'tree') | |
70 | self.__parents = d(parents, 'parents') | |
71 | self.__author = d(author, 'author') | |
72 | self.__committer = d(committer, 'committer') | |
73 | self.__message = d(message, 'message') | |
74 | tree = property(lambda self: self.__tree) | |
75 | parents = property(lambda self: self.__parents) | |
76 | @property | |
77 | def parent(self): | |
78 | assert len(self.__parents) == 1 | |
79 | return self.__parents[0] | |
80 | author = property(lambda self: self.__author) | |
81 | committer = property(lambda self: self.__committer) | |
82 | message = property(lambda self: self.__message) | |
83 | def set_tree(self, tree): | |
84 | return type(self)(tree = tree, defaults = self) | |
85 | def set_parents(self, parents): | |
86 | return type(self)(parents = parents, defaults = self) | |
87 | def add_parent(self, parent): | |
88 | return type(self)(parents = list(self.parents or []) + [parent], | |
89 | defaults = self) | |
90 | def set_parent(self, parent): | |
91 | return self.set_parents([parent]) | |
92 | def set_author(self, author): | |
93 | return type(self)(author = author, defaults = self) | |
94 | def set_committer(self, committer): | |
95 | return type(self)(committer = committer, defaults = self) | |
96 | def set_message(self, message): | |
97 | return type(self)(message = message, defaults = self) | |
98 | def __str__(self): | |
99 | if self.tree == None: | |
100 | tree = None | |
101 | else: | |
102 | tree = self.tree.sha1 | |
103 | if self.parents == None: | |
104 | parents = None | |
105 | else: | |
106 | parents = [p.sha1 for p in self.parents] | |
107 | return ('Commitdata<tree: %s, parents: %s, author: %s,' | |
108 | ' committer: %s, message: "%s">' | |
109 | ) % (tree, parents, self.author, self.committer, self.message) | |
110 | @classmethod | |
111 | def parse(cls, repository, s): | |
112 | cd = cls() | |
113 | lines = list(s.splitlines(True)) | |
114 | for i in xrange(len(lines)): | |
115 | line = lines[i].strip() | |
116 | if not line: | |
117 | return cd.set_message(''.join(lines[i+1:])) | |
118 | key, value = line.split(None, 1) | |
119 | if key == 'tree': | |
120 | cd = cd.set_tree(repository.get_tree(value)) | |
121 | elif key == 'parent': | |
122 | cd = cd.add_parent(repository.get_commit(value)) | |
123 | elif key == 'author': | |
124 | cd = cd.set_author(Person.parse(value)) | |
125 | elif key == 'committer': | |
126 | cd = cd.set_committer(Person.parse(value)) | |
127 | else: | |
128 | assert False | |
129 | assert False | |
130 | ||
131 | class Commit(Repr): | |
132 | """Immutable.""" | |
133 | def __init__(self, repository, sha1): | |
134 | self.__sha1 = sha1 | |
135 | self.__repository = repository | |
136 | self.__data = None | |
137 | sha1 = property(lambda self: self.__sha1) | |
138 | @property | |
139 | def data(self): | |
140 | if self.__data == None: | |
141 | self.__data = Commitdata.parse( | |
142 | self.__repository, | |
143 | self.__repository.cat_object(self.sha1)) | |
144 | return self.__data | |
145 | def __str__(self): | |
146 | return 'Commit<sha1: %s, data: %s>' % (self.sha1, self.__data) | |
147 | ||
148 | class Refs(object): | |
149 | def __init__(self, repository): | |
150 | self.__repository = repository | |
151 | self.__refs = None | |
152 | def __cache_refs(self): | |
153 | self.__refs = {} | |
154 | for line in self.__repository.run(['git', 'show-ref']).output_lines(): | |
155 | m = re.match(r'^([0-9a-f]{40})\s+(\S+)$', line) | |
156 | sha1, ref = m.groups() | |
157 | self.__refs[ref] = sha1 | |
158 | def get(self, ref): | |
159 | """Throws KeyError if ref doesn't exist.""" | |
160 | if self.__refs == None: | |
161 | self.__cache_refs() | |
162 | return self.__repository.get_commit(self.__refs[ref]) | |
163 | def set(self, ref, commit, msg): | |
164 | if self.__refs == None: | |
165 | self.__cache_refs() | |
166 | old_sha1 = self.__refs.get(ref, '0'*40) | |
167 | new_sha1 = commit.sha1 | |
168 | if old_sha1 != new_sha1: | |
169 | self.__repository.run(['git', 'update-ref', '-m', msg, | |
170 | ref, new_sha1, old_sha1]).no_output() | |
171 | self.__refs[ref] = new_sha1 | |
172 | def delete(self, ref): | |
173 | if self.__refs == None: | |
174 | self.__cache_refs() | |
175 | self.__repository.run(['git', 'update-ref', | |
176 | '-d', ref, self.__refs[ref]]).no_output() | |
177 | del self.__refs[ref] | |
178 | ||
179 | class ObjectCache(object): | |
180 | """Cache for Python objects, for making sure that we create only one | |
181 | Python object per git object.""" | |
182 | def __init__(self, create): | |
183 | self.__objects = {} | |
184 | self.__create = create | |
185 | def __getitem__(self, name): | |
186 | if not name in self.__objects: | |
187 | self.__objects[name] = self.__create(name) | |
188 | return self.__objects[name] | |
189 | def __contains__(self, name): | |
190 | return name in self.__objects | |
191 | def __setitem__(self, name, val): | |
192 | assert not name in self.__objects | |
193 | self.__objects[name] = val | |
194 | ||
195 | class RunWithEnv(object): | |
196 | def run(self, args, env = {}): | |
197 | return run.Run(*args).env(utils.add_dict(self.env, env)) | |
198 | ||
199 | class Repository(RunWithEnv): | |
200 | def __init__(self, directory): | |
201 | self.__git_dir = directory | |
202 | self.__refs = Refs(self) | |
203 | self.__trees = ObjectCache(lambda sha1: Tree(sha1)) | |
204 | self.__commits = ObjectCache(lambda sha1: Commit(self, sha1)) | |
205 | env = property(lambda self: { 'GIT_DIR': self.__git_dir }) | |
206 | @classmethod | |
207 | def default(cls): | |
208 | """Return the default repository.""" | |
209 | try: | |
210 | return cls(run.Run('git', 'rev-parse', '--git-dir' | |
211 | ).output_one_line()) | |
212 | except run.RunException: | |
213 | raise RepositoryException('Cannot find git repository') | |
214 | directory = property(lambda self: self.__git_dir) | |
215 | refs = property(lambda self: self.__refs) | |
216 | def cat_object(self, sha1): | |
217 | return self.run(['git', 'cat-file', '-p', sha1]).raw_output() | |
218 | def rev_parse(self, rev): | |
219 | try: | |
220 | return self.get_commit(self.run( | |
221 | ['git', 'rev-parse', '%s^{commit}' % rev] | |
222 | ).output_one_line()) | |
223 | except run.RunException: | |
224 | raise RepositoryException('%s: No such revision' % rev) | |
225 | def get_tree(self, sha1): | |
226 | return self.__trees[sha1] | |
227 | def get_commit(self, sha1): | |
228 | return self.__commits[sha1] | |
229 | def commit(self, commitdata): | |
230 | c = ['git', 'commit-tree', commitdata.tree.sha1] | |
231 | for p in commitdata.parents: | |
232 | c.append('-p') | |
233 | c.append(p.sha1) | |
234 | env = {} | |
235 | for p, v1 in ((commitdata.author, 'AUTHOR'), | |
236 | (commitdata.committer, 'COMMITTER')): | |
237 | if p != None: | |
238 | for attr, v2 in (('name', 'NAME'), ('email', 'EMAIL'), | |
239 | ('date', 'DATE')): | |
240 | if getattr(p, attr) != None: | |
241 | env['GIT_%s_%s' % (v1, v2)] = getattr(p, attr) | |
242 | sha1 = self.run(c, env = env).raw_input(commitdata.message | |
243 | ).output_one_line() | |
244 | return self.get_commit(sha1) | |
245 | @property | |
246 | def head(self): | |
247 | try: | |
248 | return self.run(['git', 'symbolic-ref', '-q', 'HEAD'] | |
249 | ).output_one_line() | |
250 | except run.RunException: | |
251 | raise DetachedHeadException() | |
252 | def set_head(self, ref, msg): | |
253 | self.run(['git', 'symbolic-ref', '-m', msg, 'HEAD', ref]).no_output() |