Parent: [43aef6] (diff)

Child: [449671] (diff)

Download this file

hg.py    294 lines (251 with data), 9.2 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
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import os
os.environ['HGRCPATH'] = '' # disable loading .hgrc
import stat
import errno
import logging
import subprocess
import cPickle as pickle
import email as EM
from datetime import datetime
from cStringIO import StringIO
from itertools import islice
import pymongo
from pylons import c
from mercurial import ui, hg
from webob import exc
from ming.orm.mapped_class import MappedClass
from ming.orm.property import FieldProperty
from ming.utils import LazyProperty
from pyforge import model as M
from pyforge.lib import helpers as h
log = logging.getLogger(__name__)
def on_import():
HgRepository.CommitClass = HgCommit
HgCommit.TreeClass = HgTree
HgTree.BlobClass = HgBlob
class HgRepository(M.Repository):
class __mongometa__:
name='hg-repository'
def index(self):
result = super(HgRepository, self).index()
result.update(
type_s='HgRepository')
return result
def _setup_paths(self):
if not self.fs_path.endswith('/'): self.fs_path += '/'
try:
os.makedirs(self.fs_path)
except OSError, e: # pragma no cover
if e.errno != errno.EEXIST:
raise
def _setup_special_files(self):
magic_file = os.path.join(self.full_fs_path, '.SOURCEFORGE-REPOSITORY')
with open(magic_file, 'w') as f:
f.write('hg')
os.chmod(magic_file, stat.S_IRUSR|stat.S_IRGRP|stat.S_IROTH)
# TO DO: set up equivalent of receive-hook here
def init(self):
self._setup_paths()
# We may eventually require --template=...
log.info('hg init %s', self.full_fs_path)
result = subprocess.call(['hg', 'init', self.name],
cwd=self.fs_path)
self._setup_special_files()
self.status = 'ready'
def init_as_clone(self, source_path):
self._setup_paths()
log.info('hg clone %s %s%s' % (source_path, self.fs_path, self.name))
result = subprocess.call(['hg', 'clone', '--noupdate', source_path, self.name],
cwd=self.fs_path)
# How do we want to handle merge-requests? Will it be in repo?
self._setup_special_files()
self.status = 'ready'
@LazyProperty
def _impl(self):
return hg.repository(ui.ui(), os.path.join(self.fs_path, self.name))
def __iter__(self):
return self.log()
def commit(self, hash):
return self.CommitClass.from_repo_object(self._impl[hash], self)
def _log(self, ci, **kwargs):
def _iter(root):
seen = set()
frontier = [root]
while frontier:
ci = frontier.pop(0)
if ci in seen: continue
yield ci
seen.add(ci)
frontier += ci.parents()
frontier.sort(key=lambda ci: sum(ci.date()))
commits = _iter(ci)
offset = kwargs.pop('offset', 0)
limit = kwargs.pop('limit', None)
if limit is None:
commits = islice(commits, offset, None)
else:
commits = islice(commits, offset, offset+limit)
return [ self.CommitClass.from_repo_object(entry, self)
for entry in commits ]
def log(self, branch=None, tag='tip', offset=0, limit=10):
if branch is not None:
ci = self._impl.branchmap()[branch][0]
elif tag is not None:
ci = self._impl.tags()[tag]
else:
ci = self._impl.changelog.tip()
ci = self._impl[ci]
return self._log(ci, offset=offset, limit=limit)
def __getattr__(self, name):
assert type(self._impl) != type(self)
return getattr(self._impl, name)
def __getitem__(self, name):
return HgCommit.from_repo_object(self._impl[name], self)
def repo_tags(self):
'''Override Artifact.tags'''
return self._impl.tags()
class HgCommit(M.Commit):
type_s='HgCommit'
_impl = None
@classmethod
def from_repo_object(cls, ctx ,repo):
result = cls(id=ctx.hex(), repo=repo)
result.__dict__['_impl'] = ctx
result.user = dict(
name=EM.utils.parseaddr(ctx.user())[0],
email=EM.utils.parseaddr(ctx.user())[1])
result.user_url = None
result.revision=ctx.rev()
result.datetime=datetime.fromtimestamp(sum(ctx.date()))
return result
def url(self):
return self._repo.url() + 'ci/' + self._id + '/'
def __getattr__(self, name):
assert type(self._impl) != type(self)
return getattr(self._impl, name)
def shorthand_id(self):
return '[%s]' % self._id[:6]
@LazyProperty
def parents(self):
return tuple(HgCommit.from_repo_object(p, self._repo)
for p in self._impl.parents())
@LazyProperty
def children(self):
return tuple(HgCommit.from_repo_object(p, self._repo)
for p in self._impl.children())
def tree(self):
return self.TreeClass(self._repo, self)
def diffs(self):
differ = h.diff_text_genshi
for fn in self.changeset()[3]:
fc = self._impl[fn]
if fc.parents():
a = fc.parents()[0].path()
a_text = fc.parents()[0].data()
else:
a = '<<null>>'
a_text = ''
yield (
a, fc.path(), ''.join(differ(a_text, fc.data())))
else:
pass
def diff_summarize(self):
if len(self.parents) == 1:
parent = self.parents[0]
for filename in self._impl.files():
if filename in parent._impl:
if filename in self._impl:
yield 'change', filename
else:
yield 'remove', filename
else:
yield 'add', filename
elif len(self.parents) == 0:
for filename in self._impl.files():
yield 'add', filename
def context(self):
return dict(
prev=self.parents,
next=self.children)
class HgTree(M.Tree):
def __init__(self, repo, commit, parent=None, name=None):
super(HgTree, self).__init__(repo, commit, parent, name)
if self._parent:
self._tree = self._parent._tree[name]
self._manifest = self._parent._manifest
else:
self._tree = {}
self._manifest = commit._manifest
for k,v in self._manifest.iteritems():
dirname, filename = os.path.split(k)
tree = self._tree
for dirpart in dirname.split('/'):
tree = tree.setdefault(dirpart, {})
tree[filename] = v
def ls(self):
for name, dirent in sorted(self._tree.iteritems()):
name = name
date = None
href = name
last_author = '-'
commit = None
if isinstance(dirent, dict):
href = href + '/'
kind='dir'
else:
kind='file'
fc = self._repo._impl.filectx(
self.path() + name,
fileid=dirent)
date = datetime.fromtimestamp(sum(fc.date()))
last_author = fc.user()
commit = HgCommit.from_repo_object(fc.changectx(), self._repo)
yield dict(
dirent=dirent,
name=name,
date=date,
href=href,
kind=kind,
last_author=last_author,
commit=commit,
)
def is_blob(self, name):
try:
dirent = self._tree[name]
return not isinstance(dirent, dict)
except:
log.exception('Error checking blob-ness of %s', name)
return False
class HgBlob(M.Blob):
def __init__(self, repo, commit, tree, filename):
super(HgBlob, self).__init__(
repo, commit, tree, filename)
self._blob = self._repo._impl.filectx(
self.path(), fileid=tree._tree[filename])
def __iter__(self):
fp = StringIO(self.text)
return iter(fp)
@LazyProperty
def text(self):
return self._blob.data()
@classmethod
def from_repo_object(cls, fc, repo):
ci = HgCommit.from_repo_object(fc.changectx(), repo)
dirname, filename = os.path.split(fc.path())
tree = ci.tree()
try:
return tree.get_blob(filename, dirname[1:].split('/'))
except KeyError:
return None
def context(self):
prev=[ HgBlob.from_repo_object(fc, self._repo)
for fc in self._blob.parents() ]
next=[ HgBlob.from_repo_object(fc, self._repo)
for fc in self._blob.children() ]
prev = [ b for b in prev if b is not None ]
next = [ b for b in next if b is not None ]
return dict(prev=prev, next=next)
def __getattr__(self, name):
return getattr(self._blob, name)
on_import()
MappedClass.compile_all()