##// END OF EJS Templates
localrepo: move the changegroup method in changegroup module...
Pierre-Yves David -
r20931:de60ca3a default
parent child Browse files
Show More
@@ -1,512 +1,516
1 1 # changegroup.py - Mercurial changegroup manipulation functions
2 2 #
3 3 # Copyright 2006 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from i18n import _
9 9 from node import nullrev, nullid, hex
10 10 import mdiff, util, dagutil
11 11 import struct, os, bz2, zlib, tempfile
12 12 import discovery
13 13
14 14 _BUNDLE10_DELTA_HEADER = "20s20s20s20s"
15 15
16 16 def readexactly(stream, n):
17 17 '''read n bytes from stream.read and abort if less was available'''
18 18 s = stream.read(n)
19 19 if len(s) < n:
20 20 raise util.Abort(_("stream ended unexpectedly"
21 21 " (got %d bytes, expected %d)")
22 22 % (len(s), n))
23 23 return s
24 24
25 25 def getchunk(stream):
26 26 """return the next chunk from stream as a string"""
27 27 d = readexactly(stream, 4)
28 28 l = struct.unpack(">l", d)[0]
29 29 if l <= 4:
30 30 if l:
31 31 raise util.Abort(_("invalid chunk length %d") % l)
32 32 return ""
33 33 return readexactly(stream, l - 4)
34 34
35 35 def chunkheader(length):
36 36 """return a changegroup chunk header (string)"""
37 37 return struct.pack(">l", length + 4)
38 38
39 39 def closechunk():
40 40 """return a changegroup chunk header (string) for a zero-length chunk"""
41 41 return struct.pack(">l", 0)
42 42
43 43 class nocompress(object):
44 44 def compress(self, x):
45 45 return x
46 46 def flush(self):
47 47 return ""
48 48
49 49 bundletypes = {
50 50 "": ("", nocompress), # only when using unbundle on ssh and old http servers
51 51 # since the unification ssh accepts a header but there
52 52 # is no capability signaling it.
53 53 "HG10UN": ("HG10UN", nocompress),
54 54 "HG10BZ": ("HG10", lambda: bz2.BZ2Compressor()),
55 55 "HG10GZ": ("HG10GZ", lambda: zlib.compressobj()),
56 56 }
57 57
58 58 # hgweb uses this list to communicate its preferred type
59 59 bundlepriority = ['HG10GZ', 'HG10BZ', 'HG10UN']
60 60
61 61 def writebundle(cg, filename, bundletype):
62 62 """Write a bundle file and return its filename.
63 63
64 64 Existing files will not be overwritten.
65 65 If no filename is specified, a temporary file is created.
66 66 bz2 compression can be turned off.
67 67 The bundle file will be deleted in case of errors.
68 68 """
69 69
70 70 fh = None
71 71 cleanup = None
72 72 try:
73 73 if filename:
74 74 fh = open(filename, "wb")
75 75 else:
76 76 fd, filename = tempfile.mkstemp(prefix="hg-bundle-", suffix=".hg")
77 77 fh = os.fdopen(fd, "wb")
78 78 cleanup = filename
79 79
80 80 header, compressor = bundletypes[bundletype]
81 81 fh.write(header)
82 82 z = compressor()
83 83
84 84 # parse the changegroup data, otherwise we will block
85 85 # in case of sshrepo because we don't know the end of the stream
86 86
87 87 # an empty chunkgroup is the end of the changegroup
88 88 # a changegroup has at least 2 chunkgroups (changelog and manifest).
89 89 # after that, an empty chunkgroup is the end of the changegroup
90 90 empty = False
91 91 count = 0
92 92 while not empty or count <= 2:
93 93 empty = True
94 94 count += 1
95 95 while True:
96 96 chunk = getchunk(cg)
97 97 if not chunk:
98 98 break
99 99 empty = False
100 100 fh.write(z.compress(chunkheader(len(chunk))))
101 101 pos = 0
102 102 while pos < len(chunk):
103 103 next = pos + 2**20
104 104 fh.write(z.compress(chunk[pos:next]))
105 105 pos = next
106 106 fh.write(z.compress(closechunk()))
107 107 fh.write(z.flush())
108 108 cleanup = None
109 109 return filename
110 110 finally:
111 111 if fh is not None:
112 112 fh.close()
113 113 if cleanup is not None:
114 114 os.unlink(cleanup)
115 115
116 116 def decompressor(fh, alg):
117 117 if alg == 'UN':
118 118 return fh
119 119 elif alg == 'GZ':
120 120 def generator(f):
121 121 zd = zlib.decompressobj()
122 122 for chunk in util.filechunkiter(f):
123 123 yield zd.decompress(chunk)
124 124 elif alg == 'BZ':
125 125 def generator(f):
126 126 zd = bz2.BZ2Decompressor()
127 127 zd.decompress("BZ")
128 128 for chunk in util.filechunkiter(f, 4096):
129 129 yield zd.decompress(chunk)
130 130 else:
131 131 raise util.Abort("unknown bundle compression '%s'" % alg)
132 132 return util.chunkbuffer(generator(fh))
133 133
134 134 class unbundle10(object):
135 135 deltaheader = _BUNDLE10_DELTA_HEADER
136 136 deltaheadersize = struct.calcsize(deltaheader)
137 137 def __init__(self, fh, alg):
138 138 self._stream = decompressor(fh, alg)
139 139 self._type = alg
140 140 self.callback = None
141 141 def compressed(self):
142 142 return self._type != 'UN'
143 143 def read(self, l):
144 144 return self._stream.read(l)
145 145 def seek(self, pos):
146 146 return self._stream.seek(pos)
147 147 def tell(self):
148 148 return self._stream.tell()
149 149 def close(self):
150 150 return self._stream.close()
151 151
152 152 def chunklength(self):
153 153 d = readexactly(self._stream, 4)
154 154 l = struct.unpack(">l", d)[0]
155 155 if l <= 4:
156 156 if l:
157 157 raise util.Abort(_("invalid chunk length %d") % l)
158 158 return 0
159 159 if self.callback:
160 160 self.callback()
161 161 return l - 4
162 162
163 163 def changelogheader(self):
164 164 """v10 does not have a changelog header chunk"""
165 165 return {}
166 166
167 167 def manifestheader(self):
168 168 """v10 does not have a manifest header chunk"""
169 169 return {}
170 170
171 171 def filelogheader(self):
172 172 """return the header of the filelogs chunk, v10 only has the filename"""
173 173 l = self.chunklength()
174 174 if not l:
175 175 return {}
176 176 fname = readexactly(self._stream, l)
177 177 return {'filename': fname}
178 178
179 179 def _deltaheader(self, headertuple, prevnode):
180 180 node, p1, p2, cs = headertuple
181 181 if prevnode is None:
182 182 deltabase = p1
183 183 else:
184 184 deltabase = prevnode
185 185 return node, p1, p2, deltabase, cs
186 186
187 187 def deltachunk(self, prevnode):
188 188 l = self.chunklength()
189 189 if not l:
190 190 return {}
191 191 headerdata = readexactly(self._stream, self.deltaheadersize)
192 192 header = struct.unpack(self.deltaheader, headerdata)
193 193 delta = readexactly(self._stream, l - self.deltaheadersize)
194 194 node, p1, p2, deltabase, cs = self._deltaheader(header, prevnode)
195 195 return {'node': node, 'p1': p1, 'p2': p2, 'cs': cs,
196 196 'deltabase': deltabase, 'delta': delta}
197 197
198 198 class headerlessfixup(object):
199 199 def __init__(self, fh, h):
200 200 self._h = h
201 201 self._fh = fh
202 202 def read(self, n):
203 203 if self._h:
204 204 d, self._h = self._h[:n], self._h[n:]
205 205 if len(d) < n:
206 206 d += readexactly(self._fh, n - len(d))
207 207 return d
208 208 return readexactly(self._fh, n)
209 209
210 210 def readbundle(fh, fname):
211 211 header = readexactly(fh, 6)
212 212
213 213 if not fname:
214 214 fname = "stream"
215 215 if not header.startswith('HG') and header.startswith('\0'):
216 216 fh = headerlessfixup(fh, header)
217 217 header = "HG10UN"
218 218
219 219 magic, version, alg = header[0:2], header[2:4], header[4:6]
220 220
221 221 if magic != 'HG':
222 222 raise util.Abort(_('%s: not a Mercurial bundle') % fname)
223 223 if version != '10':
224 224 raise util.Abort(_('%s: unknown bundle version %s') % (fname, version))
225 225 return unbundle10(fh, alg)
226 226
227 227 class bundle10(object):
228 228 deltaheader = _BUNDLE10_DELTA_HEADER
229 229 def __init__(self, repo, bundlecaps=None):
230 230 """Given a source repo, construct a bundler.
231 231
232 232 bundlecaps is optional and can be used to specify the set of
233 233 capabilities which can be used to build the bundle.
234 234 """
235 235 # Set of capabilities we can use to build the bundle.
236 236 if bundlecaps is None:
237 237 bundlecaps = set()
238 238 self._bundlecaps = bundlecaps
239 239 self._changelog = repo.changelog
240 240 self._manifest = repo.manifest
241 241 reorder = repo.ui.config('bundle', 'reorder', 'auto')
242 242 if reorder == 'auto':
243 243 reorder = None
244 244 else:
245 245 reorder = util.parsebool(reorder)
246 246 self._repo = repo
247 247 self._reorder = reorder
248 248 self._progress = repo.ui.progress
249 249 def close(self):
250 250 return closechunk()
251 251
252 252 def fileheader(self, fname):
253 253 return chunkheader(len(fname)) + fname
254 254
255 255 def group(self, nodelist, revlog, lookup, units=None, reorder=None):
256 256 """Calculate a delta group, yielding a sequence of changegroup chunks
257 257 (strings).
258 258
259 259 Given a list of changeset revs, return a set of deltas and
260 260 metadata corresponding to nodes. The first delta is
261 261 first parent(nodelist[0]) -> nodelist[0], the receiver is
262 262 guaranteed to have this parent as it has all history before
263 263 these changesets. In the case firstparent is nullrev the
264 264 changegroup starts with a full revision.
265 265
266 266 If units is not None, progress detail will be generated, units specifies
267 267 the type of revlog that is touched (changelog, manifest, etc.).
268 268 """
269 269 # if we don't have any revisions touched by these changesets, bail
270 270 if len(nodelist) == 0:
271 271 yield self.close()
272 272 return
273 273
274 274 # for generaldelta revlogs, we linearize the revs; this will both be
275 275 # much quicker and generate a much smaller bundle
276 276 if (revlog._generaldelta and reorder is not False) or reorder:
277 277 dag = dagutil.revlogdag(revlog)
278 278 revs = set(revlog.rev(n) for n in nodelist)
279 279 revs = dag.linearize(revs)
280 280 else:
281 281 revs = sorted([revlog.rev(n) for n in nodelist])
282 282
283 283 # add the parent of the first rev
284 284 p = revlog.parentrevs(revs[0])[0]
285 285 revs.insert(0, p)
286 286
287 287 # build deltas
288 288 total = len(revs) - 1
289 289 msgbundling = _('bundling')
290 290 for r in xrange(len(revs) - 1):
291 291 if units is not None:
292 292 self._progress(msgbundling, r + 1, unit=units, total=total)
293 293 prev, curr = revs[r], revs[r + 1]
294 294 linknode = lookup(revlog.node(curr))
295 295 for c in self.revchunk(revlog, curr, prev, linknode):
296 296 yield c
297 297
298 298 yield self.close()
299 299
300 300 # filter any nodes that claim to be part of the known set
301 301 def prune(self, revlog, missing, commonrevs, source):
302 302 rr, rl = revlog.rev, revlog.linkrev
303 303 return [n for n in missing if rl(rr(n)) not in commonrevs]
304 304
305 305 def generate(self, commonrevs, clnodes, fastpathlinkrev, source):
306 306 '''yield a sequence of changegroup chunks (strings)'''
307 307 repo = self._repo
308 308 cl = self._changelog
309 309 mf = self._manifest
310 310 reorder = self._reorder
311 311 progress = self._progress
312 312
313 313 # for progress output
314 314 msgbundling = _('bundling')
315 315
316 316 mfs = {} # needed manifests
317 317 fnodes = {} # needed file nodes
318 318 changedfiles = set()
319 319
320 320 # Callback for the changelog, used to collect changed files and manifest
321 321 # nodes.
322 322 # Returns the linkrev node (identity in the changelog case).
323 323 def lookupcl(x):
324 324 c = cl.read(x)
325 325 changedfiles.update(c[3])
326 326 # record the first changeset introducing this manifest version
327 327 mfs.setdefault(c[0], x)
328 328 return x
329 329
330 330 # Callback for the manifest, used to collect linkrevs for filelog
331 331 # revisions.
332 332 # Returns the linkrev node (collected in lookupcl).
333 333 def lookupmf(x):
334 334 clnode = mfs[x]
335 335 if not fastpathlinkrev:
336 336 mdata = mf.readfast(x)
337 337 for f, n in mdata.iteritems():
338 338 if f in changedfiles:
339 339 # record the first changeset introducing this filelog
340 340 # version
341 341 fnodes[f].setdefault(n, clnode)
342 342 return clnode
343 343
344 344 for chunk in self.group(clnodes, cl, lookupcl, units=_('changesets'),
345 345 reorder=reorder):
346 346 yield chunk
347 347 progress(msgbundling, None)
348 348
349 349 for f in changedfiles:
350 350 fnodes[f] = {}
351 351 mfnodes = self.prune(mf, mfs, commonrevs, source)
352 352 for chunk in self.group(mfnodes, mf, lookupmf, units=_('manifests'),
353 353 reorder=reorder):
354 354 yield chunk
355 355 progress(msgbundling, None)
356 356
357 357 mfs.clear()
358 358 needed = set(cl.rev(x) for x in clnodes)
359 359
360 360 def linknodes(filerevlog, fname):
361 361 if fastpathlinkrev:
362 362 ln, llr = filerevlog.node, filerevlog.linkrev
363 363 def genfilenodes():
364 364 for r in filerevlog:
365 365 linkrev = llr(r)
366 366 if linkrev in needed:
367 367 yield filerevlog.node(r), cl.node(linkrev)
368 368 fnodes[fname] = dict(genfilenodes())
369 369 return fnodes.get(fname, {})
370 370
371 371 for chunk in self.generatefiles(changedfiles, linknodes, commonrevs,
372 372 source):
373 373 yield chunk
374 374
375 375 yield self.close()
376 376 progress(msgbundling, None)
377 377
378 378 if clnodes:
379 379 repo.hook('outgoing', node=hex(clnodes[0]), source=source)
380 380
381 381 def generatefiles(self, changedfiles, linknodes, commonrevs, source):
382 382 repo = self._repo
383 383 progress = self._progress
384 384 reorder = self._reorder
385 385 msgbundling = _('bundling')
386 386
387 387 total = len(changedfiles)
388 388 # for progress output
389 389 msgfiles = _('files')
390 390 for i, fname in enumerate(sorted(changedfiles)):
391 391 filerevlog = repo.file(fname)
392 392 if not filerevlog:
393 393 raise util.Abort(_("empty or missing revlog for %s") % fname)
394 394
395 395 linkrevnodes = linknodes(filerevlog, fname)
396 396 # Lookup for filenodes, we collected the linkrev nodes above in the
397 397 # fastpath case and with lookupmf in the slowpath case.
398 398 def lookupfilelog(x):
399 399 return linkrevnodes[x]
400 400
401 401 filenodes = self.prune(filerevlog, linkrevnodes, commonrevs, source)
402 402 if filenodes:
403 403 progress(msgbundling, i + 1, item=fname, unit=msgfiles,
404 404 total=total)
405 405 yield self.fileheader(fname)
406 406 for chunk in self.group(filenodes, filerevlog, lookupfilelog,
407 407 reorder=reorder):
408 408 yield chunk
409 409
410 410 def revchunk(self, revlog, rev, prev, linknode):
411 411 node = revlog.node(rev)
412 412 p1, p2 = revlog.parentrevs(rev)
413 413 base = prev
414 414
415 415 prefix = ''
416 416 if base == nullrev:
417 417 delta = revlog.revision(node)
418 418 prefix = mdiff.trivialdiffheader(len(delta))
419 419 else:
420 420 delta = revlog.revdiff(base, rev)
421 421 p1n, p2n = revlog.parents(node)
422 422 basenode = revlog.node(base)
423 423 meta = self.builddeltaheader(node, p1n, p2n, basenode, linknode)
424 424 meta += prefix
425 425 l = len(meta) + len(delta)
426 426 yield chunkheader(l)
427 427 yield meta
428 428 yield delta
429 429 def builddeltaheader(self, node, p1n, p2n, basenode, linknode):
430 430 # do nothing with basenode, it is implicitly the previous one in HG10
431 431 return struct.pack(self.deltaheader, node, p1n, p2n, linknode)
432 432
433 433 def _changegroupinfo(repo, nodes, source):
434 434 if repo.ui.verbose or source == 'bundle':
435 435 repo.ui.status(_("%d changesets found\n") % len(nodes))
436 436 if repo.ui.debugflag:
437 437 repo.ui.debug("list of changesets:\n")
438 438 for node in nodes:
439 439 repo.ui.debug("%s\n" % hex(node))
440 440
441 441 def getsubset(repo, outgoing, bundler, source, fastpath=False):
442 442 repo = repo.unfiltered()
443 443 commonrevs = outgoing.common
444 444 csets = outgoing.missing
445 445 heads = outgoing.missingheads
446 446 # We go through the fast path if we get told to, or if all (unfiltered
447 447 # heads have been requested (since we then know there all linkrevs will
448 448 # be pulled by the client).
449 449 heads.sort()
450 450 fastpathlinkrev = fastpath or (
451 451 repo.filtername is None and heads == sorted(repo.heads()))
452 452
453 453 repo.hook('preoutgoing', throw=True, source=source)
454 454 _changegroupinfo(repo, csets, source)
455 455 gengroup = bundler.generate(commonrevs, csets, fastpathlinkrev, source)
456 456 return unbundle10(util.chunkbuffer(gengroup), 'UN')
457 457
458 458 def changegroupsubset(repo, roots, heads, source):
459 459 """Compute a changegroup consisting of all the nodes that are
460 460 descendants of any of the roots and ancestors of any of the heads.
461 461 Return a chunkbuffer object whose read() method will return
462 462 successive changegroup chunks.
463 463
464 464 It is fairly complex as determining which filenodes and which
465 465 manifest nodes need to be included for the changeset to be complete
466 466 is non-trivial.
467 467
468 468 Another wrinkle is doing the reverse, figuring out which changeset in
469 469 the changegroup a particular filenode or manifestnode belongs to.
470 470 """
471 471 cl = repo.changelog
472 472 if not roots:
473 473 roots = [nullid]
474 474 # TODO: remove call to nodesbetween.
475 475 csets, roots, heads = cl.nodesbetween(roots, heads)
476 476 discbases = []
477 477 for n in roots:
478 478 discbases.extend([p for p in cl.parents(n) if p != nullid])
479 479 outgoing = discovery.outgoing(cl, discbases, heads)
480 480 bundler = bundle10(repo)
481 481 return getsubset(repo, outgoing, bundler, source)
482 482
483 483 def getlocalbundle(repo, source, outgoing, bundlecaps=None):
484 484 """Like getbundle, but taking a discovery.outgoing as an argument.
485 485
486 486 This is only implemented for local repos and reuses potentially
487 487 precomputed sets in outgoing."""
488 488 if not outgoing.missing:
489 489 return None
490 490 bundler = bundle10(repo, bundlecaps)
491 491 return getsubset(repo, outgoing, bundler, source)
492 492
493 493 def getbundle(repo, source, heads=None, common=None, bundlecaps=None):
494 494 """Like changegroupsubset, but returns the set difference between the
495 495 ancestors of heads and the ancestors common.
496 496
497 497 If heads is None, use the local heads. If common is None, use [nullid].
498 498
499 499 The nodes in common might not all be known locally due to the way the
500 500 current discovery protocol works.
501 501 """
502 502 cl = repo.changelog
503 503 if common:
504 504 hasnode = cl.hasnode
505 505 common = [n for n in common if hasnode(n)]
506 506 else:
507 507 common = [nullid]
508 508 if not heads:
509 509 heads = cl.heads()
510 510 outgoing = discovery.outgoing(cl, common, heads)
511 511 return getlocalbundle(repo, source, outgoing, bundlecaps=bundlecaps)
512 512
513 def changegroup(repo, basenodes, source):
514 # to avoid a race we use changegroupsubset() (issue1320)
515 return changegroupsubset(repo, basenodes, repo.heads(), source)
516
@@ -1,2096 +1,2091
1 1 # localrepo.py - read/write repository class for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7 from node import hex, nullid, short
8 8 from i18n import _
9 9 import peer, changegroup, subrepo, pushkey, obsolete, repoview
10 10 import changelog, dirstate, filelog, manifest, context, bookmarks, phases
11 11 import lock as lockmod
12 12 import transaction, store, encoding, exchange
13 13 import scmutil, util, extensions, hook, error, revset
14 14 import match as matchmod
15 15 import merge as mergemod
16 16 import tags as tagsmod
17 17 from lock import release
18 18 import weakref, errno, os, time, inspect
19 19 import branchmap, pathutil
20 20 propertycache = util.propertycache
21 21 filecache = scmutil.filecache
22 22
23 23 class repofilecache(filecache):
24 24 """All filecache usage on repo are done for logic that should be unfiltered
25 25 """
26 26
27 27 def __get__(self, repo, type=None):
28 28 return super(repofilecache, self).__get__(repo.unfiltered(), type)
29 29 def __set__(self, repo, value):
30 30 return super(repofilecache, self).__set__(repo.unfiltered(), value)
31 31 def __delete__(self, repo):
32 32 return super(repofilecache, self).__delete__(repo.unfiltered())
33 33
34 34 class storecache(repofilecache):
35 35 """filecache for files in the store"""
36 36 def join(self, obj, fname):
37 37 return obj.sjoin(fname)
38 38
39 39 class unfilteredpropertycache(propertycache):
40 40 """propertycache that apply to unfiltered repo only"""
41 41
42 42 def __get__(self, repo, type=None):
43 43 unfi = repo.unfiltered()
44 44 if unfi is repo:
45 45 return super(unfilteredpropertycache, self).__get__(unfi)
46 46 return getattr(unfi, self.name)
47 47
48 48 class filteredpropertycache(propertycache):
49 49 """propertycache that must take filtering in account"""
50 50
51 51 def cachevalue(self, obj, value):
52 52 object.__setattr__(obj, self.name, value)
53 53
54 54
55 55 def hasunfilteredcache(repo, name):
56 56 """check if a repo has an unfilteredpropertycache value for <name>"""
57 57 return name in vars(repo.unfiltered())
58 58
59 59 def unfilteredmethod(orig):
60 60 """decorate method that always need to be run on unfiltered version"""
61 61 def wrapper(repo, *args, **kwargs):
62 62 return orig(repo.unfiltered(), *args, **kwargs)
63 63 return wrapper
64 64
65 65 moderncaps = set(('lookup', 'branchmap', 'pushkey', 'known', 'getbundle'))
66 66 legacycaps = moderncaps.union(set(['changegroupsubset']))
67 67
68 68 class localpeer(peer.peerrepository):
69 69 '''peer for a local repo; reflects only the most recent API'''
70 70
71 71 def __init__(self, repo, caps=moderncaps):
72 72 peer.peerrepository.__init__(self)
73 73 self._repo = repo.filtered('served')
74 74 self.ui = repo.ui
75 75 self._caps = repo._restrictcapabilities(caps)
76 76 self.requirements = repo.requirements
77 77 self.supportedformats = repo.supportedformats
78 78
79 79 def close(self):
80 80 self._repo.close()
81 81
82 82 def _capabilities(self):
83 83 return self._caps
84 84
85 85 def local(self):
86 86 return self._repo
87 87
88 88 def canpush(self):
89 89 return True
90 90
91 91 def url(self):
92 92 return self._repo.url()
93 93
94 94 def lookup(self, key):
95 95 return self._repo.lookup(key)
96 96
97 97 def branchmap(self):
98 98 return self._repo.branchmap()
99 99
100 100 def heads(self):
101 101 return self._repo.heads()
102 102
103 103 def known(self, nodes):
104 104 return self._repo.known(nodes)
105 105
106 106 def getbundle(self, source, heads=None, common=None, bundlecaps=None):
107 107 return changegroup.getbundle(self._repo, source, heads=heads,
108 108 common=common, bundlecaps=None)
109 109
110 110 # TODO We might want to move the next two calls into legacypeer and add
111 111 # unbundle instead.
112 112
113 113 def lock(self):
114 114 return self._repo.lock()
115 115
116 116 def addchangegroup(self, cg, source, url):
117 117 return self._repo.addchangegroup(cg, source, url)
118 118
119 119 def pushkey(self, namespace, key, old, new):
120 120 return self._repo.pushkey(namespace, key, old, new)
121 121
122 122 def listkeys(self, namespace):
123 123 return self._repo.listkeys(namespace)
124 124
125 125 def debugwireargs(self, one, two, three=None, four=None, five=None):
126 126 '''used to test argument passing over the wire'''
127 127 return "%s %s %s %s %s" % (one, two, three, four, five)
128 128
129 129 class locallegacypeer(localpeer):
130 130 '''peer extension which implements legacy methods too; used for tests with
131 131 restricted capabilities'''
132 132
133 133 def __init__(self, repo):
134 134 localpeer.__init__(self, repo, caps=legacycaps)
135 135
136 136 def branches(self, nodes):
137 137 return self._repo.branches(nodes)
138 138
139 139 def between(self, pairs):
140 140 return self._repo.between(pairs)
141 141
142 142 def changegroup(self, basenodes, source):
143 return self._repo.changegroup(basenodes, source)
143 return changegroup.changegroup(self._repo, basenodes, source)
144 144
145 145 def changegroupsubset(self, bases, heads, source):
146 146 return changegroup.changegroupsubset(self._repo, bases, heads, source)
147 147
148 148 class localrepository(object):
149 149
150 150 supportedformats = set(('revlogv1', 'generaldelta'))
151 151 _basesupported = supportedformats | set(('store', 'fncache', 'shared',
152 152 'dotencode'))
153 153 openerreqs = set(('revlogv1', 'generaldelta'))
154 154 requirements = ['revlogv1']
155 155 filtername = None
156 156
157 157 # a list of (ui, featureset) functions.
158 158 # only functions defined in module of enabled extensions are invoked
159 159 featuresetupfuncs = set()
160 160
161 161 def _baserequirements(self, create):
162 162 return self.requirements[:]
163 163
164 164 def __init__(self, baseui, path=None, create=False):
165 165 self.wvfs = scmutil.vfs(path, expandpath=True, realpath=True)
166 166 self.wopener = self.wvfs
167 167 self.root = self.wvfs.base
168 168 self.path = self.wvfs.join(".hg")
169 169 self.origroot = path
170 170 self.auditor = pathutil.pathauditor(self.root, self._checknested)
171 171 self.vfs = scmutil.vfs(self.path)
172 172 self.opener = self.vfs
173 173 self.baseui = baseui
174 174 self.ui = baseui.copy()
175 175 self.ui.copy = baseui.copy # prevent copying repo configuration
176 176 # A list of callback to shape the phase if no data were found.
177 177 # Callback are in the form: func(repo, roots) --> processed root.
178 178 # This list it to be filled by extension during repo setup
179 179 self._phasedefaults = []
180 180 try:
181 181 self.ui.readconfig(self.join("hgrc"), self.root)
182 182 extensions.loadall(self.ui)
183 183 except IOError:
184 184 pass
185 185
186 186 if self.featuresetupfuncs:
187 187 self.supported = set(self._basesupported) # use private copy
188 188 extmods = set(m.__name__ for n, m
189 189 in extensions.extensions(self.ui))
190 190 for setupfunc in self.featuresetupfuncs:
191 191 if setupfunc.__module__ in extmods:
192 192 setupfunc(self.ui, self.supported)
193 193 else:
194 194 self.supported = self._basesupported
195 195
196 196 if not self.vfs.isdir():
197 197 if create:
198 198 if not self.wvfs.exists():
199 199 self.wvfs.makedirs()
200 200 self.vfs.makedir(notindexed=True)
201 201 requirements = self._baserequirements(create)
202 202 if self.ui.configbool('format', 'usestore', True):
203 203 self.vfs.mkdir("store")
204 204 requirements.append("store")
205 205 if self.ui.configbool('format', 'usefncache', True):
206 206 requirements.append("fncache")
207 207 if self.ui.configbool('format', 'dotencode', True):
208 208 requirements.append('dotencode')
209 209 # create an invalid changelog
210 210 self.vfs.append(
211 211 "00changelog.i",
212 212 '\0\0\0\2' # represents revlogv2
213 213 ' dummy changelog to prevent using the old repo layout'
214 214 )
215 215 if self.ui.configbool('format', 'generaldelta', False):
216 216 requirements.append("generaldelta")
217 217 requirements = set(requirements)
218 218 else:
219 219 raise error.RepoError(_("repository %s not found") % path)
220 220 elif create:
221 221 raise error.RepoError(_("repository %s already exists") % path)
222 222 else:
223 223 try:
224 224 requirements = scmutil.readrequires(self.vfs, self.supported)
225 225 except IOError, inst:
226 226 if inst.errno != errno.ENOENT:
227 227 raise
228 228 requirements = set()
229 229
230 230 self.sharedpath = self.path
231 231 try:
232 232 vfs = scmutil.vfs(self.vfs.read("sharedpath").rstrip('\n'),
233 233 realpath=True)
234 234 s = vfs.base
235 235 if not vfs.exists():
236 236 raise error.RepoError(
237 237 _('.hg/sharedpath points to nonexistent directory %s') % s)
238 238 self.sharedpath = s
239 239 except IOError, inst:
240 240 if inst.errno != errno.ENOENT:
241 241 raise
242 242
243 243 self.store = store.store(requirements, self.sharedpath, scmutil.vfs)
244 244 self.spath = self.store.path
245 245 self.svfs = self.store.vfs
246 246 self.sopener = self.svfs
247 247 self.sjoin = self.store.join
248 248 self.vfs.createmode = self.store.createmode
249 249 self._applyrequirements(requirements)
250 250 if create:
251 251 self._writerequirements()
252 252
253 253
254 254 self._branchcaches = {}
255 255 self.filterpats = {}
256 256 self._datafilters = {}
257 257 self._transref = self._lockref = self._wlockref = None
258 258
259 259 # A cache for various files under .hg/ that tracks file changes,
260 260 # (used by the filecache decorator)
261 261 #
262 262 # Maps a property name to its util.filecacheentry
263 263 self._filecache = {}
264 264
265 265 # hold sets of revision to be filtered
266 266 # should be cleared when something might have changed the filter value:
267 267 # - new changesets,
268 268 # - phase change,
269 269 # - new obsolescence marker,
270 270 # - working directory parent change,
271 271 # - bookmark changes
272 272 self.filteredrevcache = {}
273 273
274 274 def close(self):
275 275 pass
276 276
277 277 def _restrictcapabilities(self, caps):
278 278 return caps
279 279
280 280 def _applyrequirements(self, requirements):
281 281 self.requirements = requirements
282 282 self.sopener.options = dict((r, 1) for r in requirements
283 283 if r in self.openerreqs)
284 284 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
285 285 if chunkcachesize is not None:
286 286 self.sopener.options['chunkcachesize'] = chunkcachesize
287 287
288 288 def _writerequirements(self):
289 289 reqfile = self.opener("requires", "w")
290 290 for r in sorted(self.requirements):
291 291 reqfile.write("%s\n" % r)
292 292 reqfile.close()
293 293
294 294 def _checknested(self, path):
295 295 """Determine if path is a legal nested repository."""
296 296 if not path.startswith(self.root):
297 297 return False
298 298 subpath = path[len(self.root) + 1:]
299 299 normsubpath = util.pconvert(subpath)
300 300
301 301 # XXX: Checking against the current working copy is wrong in
302 302 # the sense that it can reject things like
303 303 #
304 304 # $ hg cat -r 10 sub/x.txt
305 305 #
306 306 # if sub/ is no longer a subrepository in the working copy
307 307 # parent revision.
308 308 #
309 309 # However, it can of course also allow things that would have
310 310 # been rejected before, such as the above cat command if sub/
311 311 # is a subrepository now, but was a normal directory before.
312 312 # The old path auditor would have rejected by mistake since it
313 313 # panics when it sees sub/.hg/.
314 314 #
315 315 # All in all, checking against the working copy seems sensible
316 316 # since we want to prevent access to nested repositories on
317 317 # the filesystem *now*.
318 318 ctx = self[None]
319 319 parts = util.splitpath(subpath)
320 320 while parts:
321 321 prefix = '/'.join(parts)
322 322 if prefix in ctx.substate:
323 323 if prefix == normsubpath:
324 324 return True
325 325 else:
326 326 sub = ctx.sub(prefix)
327 327 return sub.checknested(subpath[len(prefix) + 1:])
328 328 else:
329 329 parts.pop()
330 330 return False
331 331
332 332 def peer(self):
333 333 return localpeer(self) # not cached to avoid reference cycle
334 334
335 335 def unfiltered(self):
336 336 """Return unfiltered version of the repository
337 337
338 338 Intended to be overwritten by filtered repo."""
339 339 return self
340 340
341 341 def filtered(self, name):
342 342 """Return a filtered version of a repository"""
343 343 # build a new class with the mixin and the current class
344 344 # (possibly subclass of the repo)
345 345 class proxycls(repoview.repoview, self.unfiltered().__class__):
346 346 pass
347 347 return proxycls(self, name)
348 348
349 349 @repofilecache('bookmarks')
350 350 def _bookmarks(self):
351 351 return bookmarks.bmstore(self)
352 352
353 353 @repofilecache('bookmarks.current')
354 354 def _bookmarkcurrent(self):
355 355 return bookmarks.readcurrent(self)
356 356
357 357 def bookmarkheads(self, bookmark):
358 358 name = bookmark.split('@', 1)[0]
359 359 heads = []
360 360 for mark, n in self._bookmarks.iteritems():
361 361 if mark.split('@', 1)[0] == name:
362 362 heads.append(n)
363 363 return heads
364 364
365 365 @storecache('phaseroots')
366 366 def _phasecache(self):
367 367 return phases.phasecache(self, self._phasedefaults)
368 368
369 369 @storecache('obsstore')
370 370 def obsstore(self):
371 371 store = obsolete.obsstore(self.sopener)
372 372 if store and not obsolete._enabled:
373 373 # message is rare enough to not be translated
374 374 msg = 'obsolete feature not enabled but %i markers found!\n'
375 375 self.ui.warn(msg % len(list(store)))
376 376 return store
377 377
378 378 @storecache('00changelog.i')
379 379 def changelog(self):
380 380 c = changelog.changelog(self.sopener)
381 381 if 'HG_PENDING' in os.environ:
382 382 p = os.environ['HG_PENDING']
383 383 if p.startswith(self.root):
384 384 c.readpending('00changelog.i.a')
385 385 return c
386 386
387 387 @storecache('00manifest.i')
388 388 def manifest(self):
389 389 return manifest.manifest(self.sopener)
390 390
391 391 @repofilecache('dirstate')
392 392 def dirstate(self):
393 393 warned = [0]
394 394 def validate(node):
395 395 try:
396 396 self.changelog.rev(node)
397 397 return node
398 398 except error.LookupError:
399 399 if not warned[0]:
400 400 warned[0] = True
401 401 self.ui.warn(_("warning: ignoring unknown"
402 402 " working parent %s!\n") % short(node))
403 403 return nullid
404 404
405 405 return dirstate.dirstate(self.opener, self.ui, self.root, validate)
406 406
407 407 def __getitem__(self, changeid):
408 408 if changeid is None:
409 409 return context.workingctx(self)
410 410 return context.changectx(self, changeid)
411 411
412 412 def __contains__(self, changeid):
413 413 try:
414 414 return bool(self.lookup(changeid))
415 415 except error.RepoLookupError:
416 416 return False
417 417
418 418 def __nonzero__(self):
419 419 return True
420 420
421 421 def __len__(self):
422 422 return len(self.changelog)
423 423
424 424 def __iter__(self):
425 425 return iter(self.changelog)
426 426
427 427 def revs(self, expr, *args):
428 428 '''Return a list of revisions matching the given revset'''
429 429 expr = revset.formatspec(expr, *args)
430 430 m = revset.match(None, expr)
431 431 return m(self, revset.spanset(self))
432 432
433 433 def set(self, expr, *args):
434 434 '''
435 435 Yield a context for each matching revision, after doing arg
436 436 replacement via revset.formatspec
437 437 '''
438 438 for r in self.revs(expr, *args):
439 439 yield self[r]
440 440
441 441 def url(self):
442 442 return 'file:' + self.root
443 443
444 444 def hook(self, name, throw=False, **args):
445 445 return hook.hook(self.ui, self, name, throw, **args)
446 446
447 447 @unfilteredmethod
448 448 def _tag(self, names, node, message, local, user, date, extra={}):
449 449 if isinstance(names, str):
450 450 names = (names,)
451 451
452 452 branches = self.branchmap()
453 453 for name in names:
454 454 self.hook('pretag', throw=True, node=hex(node), tag=name,
455 455 local=local)
456 456 if name in branches:
457 457 self.ui.warn(_("warning: tag %s conflicts with existing"
458 458 " branch name\n") % name)
459 459
460 460 def writetags(fp, names, munge, prevtags):
461 461 fp.seek(0, 2)
462 462 if prevtags and prevtags[-1] != '\n':
463 463 fp.write('\n')
464 464 for name in names:
465 465 m = munge and munge(name) or name
466 466 if (self._tagscache.tagtypes and
467 467 name in self._tagscache.tagtypes):
468 468 old = self.tags().get(name, nullid)
469 469 fp.write('%s %s\n' % (hex(old), m))
470 470 fp.write('%s %s\n' % (hex(node), m))
471 471 fp.close()
472 472
473 473 prevtags = ''
474 474 if local:
475 475 try:
476 476 fp = self.opener('localtags', 'r+')
477 477 except IOError:
478 478 fp = self.opener('localtags', 'a')
479 479 else:
480 480 prevtags = fp.read()
481 481
482 482 # local tags are stored in the current charset
483 483 writetags(fp, names, None, prevtags)
484 484 for name in names:
485 485 self.hook('tag', node=hex(node), tag=name, local=local)
486 486 return
487 487
488 488 try:
489 489 fp = self.wfile('.hgtags', 'rb+')
490 490 except IOError, e:
491 491 if e.errno != errno.ENOENT:
492 492 raise
493 493 fp = self.wfile('.hgtags', 'ab')
494 494 else:
495 495 prevtags = fp.read()
496 496
497 497 # committed tags are stored in UTF-8
498 498 writetags(fp, names, encoding.fromlocal, prevtags)
499 499
500 500 fp.close()
501 501
502 502 self.invalidatecaches()
503 503
504 504 if '.hgtags' not in self.dirstate:
505 505 self[None].add(['.hgtags'])
506 506
507 507 m = matchmod.exact(self.root, '', ['.hgtags'])
508 508 tagnode = self.commit(message, user, date, extra=extra, match=m)
509 509
510 510 for name in names:
511 511 self.hook('tag', node=hex(node), tag=name, local=local)
512 512
513 513 return tagnode
514 514
515 515 def tag(self, names, node, message, local, user, date):
516 516 '''tag a revision with one or more symbolic names.
517 517
518 518 names is a list of strings or, when adding a single tag, names may be a
519 519 string.
520 520
521 521 if local is True, the tags are stored in a per-repository file.
522 522 otherwise, they are stored in the .hgtags file, and a new
523 523 changeset is committed with the change.
524 524
525 525 keyword arguments:
526 526
527 527 local: whether to store tags in non-version-controlled file
528 528 (default False)
529 529
530 530 message: commit message to use if committing
531 531
532 532 user: name of user to use if committing
533 533
534 534 date: date tuple to use if committing'''
535 535
536 536 if not local:
537 537 for x in self.status()[:5]:
538 538 if '.hgtags' in x:
539 539 raise util.Abort(_('working copy of .hgtags is changed '
540 540 '(please commit .hgtags manually)'))
541 541
542 542 self.tags() # instantiate the cache
543 543 self._tag(names, node, message, local, user, date)
544 544
545 545 @filteredpropertycache
546 546 def _tagscache(self):
547 547 '''Returns a tagscache object that contains various tags related
548 548 caches.'''
549 549
550 550 # This simplifies its cache management by having one decorated
551 551 # function (this one) and the rest simply fetch things from it.
552 552 class tagscache(object):
553 553 def __init__(self):
554 554 # These two define the set of tags for this repository. tags
555 555 # maps tag name to node; tagtypes maps tag name to 'global' or
556 556 # 'local'. (Global tags are defined by .hgtags across all
557 557 # heads, and local tags are defined in .hg/localtags.)
558 558 # They constitute the in-memory cache of tags.
559 559 self.tags = self.tagtypes = None
560 560
561 561 self.nodetagscache = self.tagslist = None
562 562
563 563 cache = tagscache()
564 564 cache.tags, cache.tagtypes = self._findtags()
565 565
566 566 return cache
567 567
568 568 def tags(self):
569 569 '''return a mapping of tag to node'''
570 570 t = {}
571 571 if self.changelog.filteredrevs:
572 572 tags, tt = self._findtags()
573 573 else:
574 574 tags = self._tagscache.tags
575 575 for k, v in tags.iteritems():
576 576 try:
577 577 # ignore tags to unknown nodes
578 578 self.changelog.rev(v)
579 579 t[k] = v
580 580 except (error.LookupError, ValueError):
581 581 pass
582 582 return t
583 583
584 584 def _findtags(self):
585 585 '''Do the hard work of finding tags. Return a pair of dicts
586 586 (tags, tagtypes) where tags maps tag name to node, and tagtypes
587 587 maps tag name to a string like \'global\' or \'local\'.
588 588 Subclasses or extensions are free to add their own tags, but
589 589 should be aware that the returned dicts will be retained for the
590 590 duration of the localrepo object.'''
591 591
592 592 # XXX what tagtype should subclasses/extensions use? Currently
593 593 # mq and bookmarks add tags, but do not set the tagtype at all.
594 594 # Should each extension invent its own tag type? Should there
595 595 # be one tagtype for all such "virtual" tags? Or is the status
596 596 # quo fine?
597 597
598 598 alltags = {} # map tag name to (node, hist)
599 599 tagtypes = {}
600 600
601 601 tagsmod.findglobaltags(self.ui, self, alltags, tagtypes)
602 602 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
603 603
604 604 # Build the return dicts. Have to re-encode tag names because
605 605 # the tags module always uses UTF-8 (in order not to lose info
606 606 # writing to the cache), but the rest of Mercurial wants them in
607 607 # local encoding.
608 608 tags = {}
609 609 for (name, (node, hist)) in alltags.iteritems():
610 610 if node != nullid:
611 611 tags[encoding.tolocal(name)] = node
612 612 tags['tip'] = self.changelog.tip()
613 613 tagtypes = dict([(encoding.tolocal(name), value)
614 614 for (name, value) in tagtypes.iteritems()])
615 615 return (tags, tagtypes)
616 616
617 617 def tagtype(self, tagname):
618 618 '''
619 619 return the type of the given tag. result can be:
620 620
621 621 'local' : a local tag
622 622 'global' : a global tag
623 623 None : tag does not exist
624 624 '''
625 625
626 626 return self._tagscache.tagtypes.get(tagname)
627 627
628 628 def tagslist(self):
629 629 '''return a list of tags ordered by revision'''
630 630 if not self._tagscache.tagslist:
631 631 l = []
632 632 for t, n in self.tags().iteritems():
633 633 r = self.changelog.rev(n)
634 634 l.append((r, t, n))
635 635 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
636 636
637 637 return self._tagscache.tagslist
638 638
639 639 def nodetags(self, node):
640 640 '''return the tags associated with a node'''
641 641 if not self._tagscache.nodetagscache:
642 642 nodetagscache = {}
643 643 for t, n in self._tagscache.tags.iteritems():
644 644 nodetagscache.setdefault(n, []).append(t)
645 645 for tags in nodetagscache.itervalues():
646 646 tags.sort()
647 647 self._tagscache.nodetagscache = nodetagscache
648 648 return self._tagscache.nodetagscache.get(node, [])
649 649
650 650 def nodebookmarks(self, node):
651 651 marks = []
652 652 for bookmark, n in self._bookmarks.iteritems():
653 653 if n == node:
654 654 marks.append(bookmark)
655 655 return sorted(marks)
656 656
657 657 def branchmap(self):
658 658 '''returns a dictionary {branch: [branchheads]} with branchheads
659 659 ordered by increasing revision number'''
660 660 branchmap.updatecache(self)
661 661 return self._branchcaches[self.filtername]
662 662
663 663 def branchtip(self, branch):
664 664 '''return the tip node for a given branch'''
665 665 try:
666 666 return self.branchmap().branchtip(branch)
667 667 except KeyError:
668 668 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
669 669
670 670 def lookup(self, key):
671 671 return self[key].node()
672 672
673 673 def lookupbranch(self, key, remote=None):
674 674 repo = remote or self
675 675 if key in repo.branchmap():
676 676 return key
677 677
678 678 repo = (remote and remote.local()) and remote or self
679 679 return repo[key].branch()
680 680
681 681 def known(self, nodes):
682 682 nm = self.changelog.nodemap
683 683 pc = self._phasecache
684 684 result = []
685 685 for n in nodes:
686 686 r = nm.get(n)
687 687 resp = not (r is None or pc.phase(self, r) >= phases.secret)
688 688 result.append(resp)
689 689 return result
690 690
691 691 def local(self):
692 692 return self
693 693
694 694 def cancopy(self):
695 695 # so statichttprepo's override of local() works
696 696 if not self.local():
697 697 return False
698 698 if not self.ui.configbool('phases', 'publish', True):
699 699 return True
700 700 # if publishing we can't copy if there is filtered content
701 701 return not self.filtered('visible').changelog.filteredrevs
702 702
703 703 def join(self, f):
704 704 return os.path.join(self.path, f)
705 705
706 706 def wjoin(self, f):
707 707 return os.path.join(self.root, f)
708 708
709 709 def file(self, f):
710 710 if f[0] == '/':
711 711 f = f[1:]
712 712 return filelog.filelog(self.sopener, f)
713 713
714 714 def changectx(self, changeid):
715 715 return self[changeid]
716 716
717 717 def parents(self, changeid=None):
718 718 '''get list of changectxs for parents of changeid'''
719 719 return self[changeid].parents()
720 720
721 721 def setparents(self, p1, p2=nullid):
722 722 copies = self.dirstate.setparents(p1, p2)
723 723 pctx = self[p1]
724 724 if copies:
725 725 # Adjust copy records, the dirstate cannot do it, it
726 726 # requires access to parents manifests. Preserve them
727 727 # only for entries added to first parent.
728 728 for f in copies:
729 729 if f not in pctx and copies[f] in pctx:
730 730 self.dirstate.copy(copies[f], f)
731 731 if p2 == nullid:
732 732 for f, s in sorted(self.dirstate.copies().items()):
733 733 if f not in pctx and s not in pctx:
734 734 self.dirstate.copy(None, f)
735 735
736 736 def filectx(self, path, changeid=None, fileid=None):
737 737 """changeid can be a changeset revision, node, or tag.
738 738 fileid can be a file revision or node."""
739 739 return context.filectx(self, path, changeid, fileid)
740 740
741 741 def getcwd(self):
742 742 return self.dirstate.getcwd()
743 743
744 744 def pathto(self, f, cwd=None):
745 745 return self.dirstate.pathto(f, cwd)
746 746
747 747 def wfile(self, f, mode='r'):
748 748 return self.wopener(f, mode)
749 749
750 750 def _link(self, f):
751 751 return self.wvfs.islink(f)
752 752
753 753 def _loadfilter(self, filter):
754 754 if filter not in self.filterpats:
755 755 l = []
756 756 for pat, cmd in self.ui.configitems(filter):
757 757 if cmd == '!':
758 758 continue
759 759 mf = matchmod.match(self.root, '', [pat])
760 760 fn = None
761 761 params = cmd
762 762 for name, filterfn in self._datafilters.iteritems():
763 763 if cmd.startswith(name):
764 764 fn = filterfn
765 765 params = cmd[len(name):].lstrip()
766 766 break
767 767 if not fn:
768 768 fn = lambda s, c, **kwargs: util.filter(s, c)
769 769 # Wrap old filters not supporting keyword arguments
770 770 if not inspect.getargspec(fn)[2]:
771 771 oldfn = fn
772 772 fn = lambda s, c, **kwargs: oldfn(s, c)
773 773 l.append((mf, fn, params))
774 774 self.filterpats[filter] = l
775 775 return self.filterpats[filter]
776 776
777 777 def _filter(self, filterpats, filename, data):
778 778 for mf, fn, cmd in filterpats:
779 779 if mf(filename):
780 780 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
781 781 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
782 782 break
783 783
784 784 return data
785 785
786 786 @unfilteredpropertycache
787 787 def _encodefilterpats(self):
788 788 return self._loadfilter('encode')
789 789
790 790 @unfilteredpropertycache
791 791 def _decodefilterpats(self):
792 792 return self._loadfilter('decode')
793 793
794 794 def adddatafilter(self, name, filter):
795 795 self._datafilters[name] = filter
796 796
797 797 def wread(self, filename):
798 798 if self._link(filename):
799 799 data = self.wvfs.readlink(filename)
800 800 else:
801 801 data = self.wopener.read(filename)
802 802 return self._filter(self._encodefilterpats, filename, data)
803 803
804 804 def wwrite(self, filename, data, flags):
805 805 data = self._filter(self._decodefilterpats, filename, data)
806 806 if 'l' in flags:
807 807 self.wopener.symlink(data, filename)
808 808 else:
809 809 self.wopener.write(filename, data)
810 810 if 'x' in flags:
811 811 self.wvfs.setflags(filename, False, True)
812 812
813 813 def wwritedata(self, filename, data):
814 814 return self._filter(self._decodefilterpats, filename, data)
815 815
816 816 def transaction(self, desc, report=None):
817 817 tr = self._transref and self._transref() or None
818 818 if tr and tr.running():
819 819 return tr.nest()
820 820
821 821 # abort here if the journal already exists
822 822 if self.svfs.exists("journal"):
823 823 raise error.RepoError(
824 824 _("abandoned transaction found - run hg recover"))
825 825
826 826 def onclose():
827 827 self.store.write(tr)
828 828
829 829 self._writejournal(desc)
830 830 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
831 831 rp = report and report or self.ui.warn
832 832 tr = transaction.transaction(rp, self.sopener,
833 833 "journal",
834 834 aftertrans(renames),
835 835 self.store.createmode,
836 836 onclose)
837 837 self._transref = weakref.ref(tr)
838 838 return tr
839 839
840 840 def _journalfiles(self):
841 841 return ((self.svfs, 'journal'),
842 842 (self.vfs, 'journal.dirstate'),
843 843 (self.vfs, 'journal.branch'),
844 844 (self.vfs, 'journal.desc'),
845 845 (self.vfs, 'journal.bookmarks'),
846 846 (self.svfs, 'journal.phaseroots'))
847 847
848 848 def undofiles(self):
849 849 return [vfs.join(undoname(x)) for vfs, x in self._journalfiles()]
850 850
851 851 def _writejournal(self, desc):
852 852 self.opener.write("journal.dirstate",
853 853 self.opener.tryread("dirstate"))
854 854 self.opener.write("journal.branch",
855 855 encoding.fromlocal(self.dirstate.branch()))
856 856 self.opener.write("journal.desc",
857 857 "%d\n%s\n" % (len(self), desc))
858 858 self.opener.write("journal.bookmarks",
859 859 self.opener.tryread("bookmarks"))
860 860 self.sopener.write("journal.phaseroots",
861 861 self.sopener.tryread("phaseroots"))
862 862
863 863 def recover(self):
864 864 lock = self.lock()
865 865 try:
866 866 if self.svfs.exists("journal"):
867 867 self.ui.status(_("rolling back interrupted transaction\n"))
868 868 transaction.rollback(self.sopener, "journal",
869 869 self.ui.warn)
870 870 self.invalidate()
871 871 return True
872 872 else:
873 873 self.ui.warn(_("no interrupted transaction available\n"))
874 874 return False
875 875 finally:
876 876 lock.release()
877 877
878 878 def rollback(self, dryrun=False, force=False):
879 879 wlock = lock = None
880 880 try:
881 881 wlock = self.wlock()
882 882 lock = self.lock()
883 883 if self.svfs.exists("undo"):
884 884 return self._rollback(dryrun, force)
885 885 else:
886 886 self.ui.warn(_("no rollback information available\n"))
887 887 return 1
888 888 finally:
889 889 release(lock, wlock)
890 890
891 891 @unfilteredmethod # Until we get smarter cache management
892 892 def _rollback(self, dryrun, force):
893 893 ui = self.ui
894 894 try:
895 895 args = self.opener.read('undo.desc').splitlines()
896 896 (oldlen, desc, detail) = (int(args[0]), args[1], None)
897 897 if len(args) >= 3:
898 898 detail = args[2]
899 899 oldtip = oldlen - 1
900 900
901 901 if detail and ui.verbose:
902 902 msg = (_('repository tip rolled back to revision %s'
903 903 ' (undo %s: %s)\n')
904 904 % (oldtip, desc, detail))
905 905 else:
906 906 msg = (_('repository tip rolled back to revision %s'
907 907 ' (undo %s)\n')
908 908 % (oldtip, desc))
909 909 except IOError:
910 910 msg = _('rolling back unknown transaction\n')
911 911 desc = None
912 912
913 913 if not force and self['.'] != self['tip'] and desc == 'commit':
914 914 raise util.Abort(
915 915 _('rollback of last commit while not checked out '
916 916 'may lose data'), hint=_('use -f to force'))
917 917
918 918 ui.status(msg)
919 919 if dryrun:
920 920 return 0
921 921
922 922 parents = self.dirstate.parents()
923 923 self.destroying()
924 924 transaction.rollback(self.sopener, 'undo', ui.warn)
925 925 if self.vfs.exists('undo.bookmarks'):
926 926 self.vfs.rename('undo.bookmarks', 'bookmarks')
927 927 if self.svfs.exists('undo.phaseroots'):
928 928 self.svfs.rename('undo.phaseroots', 'phaseroots')
929 929 self.invalidate()
930 930
931 931 parentgone = (parents[0] not in self.changelog.nodemap or
932 932 parents[1] not in self.changelog.nodemap)
933 933 if parentgone:
934 934 self.vfs.rename('undo.dirstate', 'dirstate')
935 935 try:
936 936 branch = self.opener.read('undo.branch')
937 937 self.dirstate.setbranch(encoding.tolocal(branch))
938 938 except IOError:
939 939 ui.warn(_('named branch could not be reset: '
940 940 'current branch is still \'%s\'\n')
941 941 % self.dirstate.branch())
942 942
943 943 self.dirstate.invalidate()
944 944 parents = tuple([p.rev() for p in self.parents()])
945 945 if len(parents) > 1:
946 946 ui.status(_('working directory now based on '
947 947 'revisions %d and %d\n') % parents)
948 948 else:
949 949 ui.status(_('working directory now based on '
950 950 'revision %d\n') % parents)
951 951 # TODO: if we know which new heads may result from this rollback, pass
952 952 # them to destroy(), which will prevent the branchhead cache from being
953 953 # invalidated.
954 954 self.destroyed()
955 955 return 0
956 956
957 957 def invalidatecaches(self):
958 958
959 959 if '_tagscache' in vars(self):
960 960 # can't use delattr on proxy
961 961 del self.__dict__['_tagscache']
962 962
963 963 self.unfiltered()._branchcaches.clear()
964 964 self.invalidatevolatilesets()
965 965
966 966 def invalidatevolatilesets(self):
967 967 self.filteredrevcache.clear()
968 968 obsolete.clearobscaches(self)
969 969
970 970 def invalidatedirstate(self):
971 971 '''Invalidates the dirstate, causing the next call to dirstate
972 972 to check if it was modified since the last time it was read,
973 973 rereading it if it has.
974 974
975 975 This is different to dirstate.invalidate() that it doesn't always
976 976 rereads the dirstate. Use dirstate.invalidate() if you want to
977 977 explicitly read the dirstate again (i.e. restoring it to a previous
978 978 known good state).'''
979 979 if hasunfilteredcache(self, 'dirstate'):
980 980 for k in self.dirstate._filecache:
981 981 try:
982 982 delattr(self.dirstate, k)
983 983 except AttributeError:
984 984 pass
985 985 delattr(self.unfiltered(), 'dirstate')
986 986
987 987 def invalidate(self):
988 988 unfiltered = self.unfiltered() # all file caches are stored unfiltered
989 989 for k in self._filecache:
990 990 # dirstate is invalidated separately in invalidatedirstate()
991 991 if k == 'dirstate':
992 992 continue
993 993
994 994 try:
995 995 delattr(unfiltered, k)
996 996 except AttributeError:
997 997 pass
998 998 self.invalidatecaches()
999 999 self.store.invalidatecaches()
1000 1000
1001 1001 def invalidateall(self):
1002 1002 '''Fully invalidates both store and non-store parts, causing the
1003 1003 subsequent operation to reread any outside changes.'''
1004 1004 # extension should hook this to invalidate its caches
1005 1005 self.invalidate()
1006 1006 self.invalidatedirstate()
1007 1007
1008 1008 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc):
1009 1009 try:
1010 1010 l = lockmod.lock(vfs, lockname, 0, releasefn, desc=desc)
1011 1011 except error.LockHeld, inst:
1012 1012 if not wait:
1013 1013 raise
1014 1014 self.ui.warn(_("waiting for lock on %s held by %r\n") %
1015 1015 (desc, inst.locker))
1016 1016 # default to 600 seconds timeout
1017 1017 l = lockmod.lock(vfs, lockname,
1018 1018 int(self.ui.config("ui", "timeout", "600")),
1019 1019 releasefn, desc=desc)
1020 1020 self.ui.warn(_("got lock after %s seconds\n") % l.delay)
1021 1021 if acquirefn:
1022 1022 acquirefn()
1023 1023 return l
1024 1024
1025 1025 def _afterlock(self, callback):
1026 1026 """add a callback to the current repository lock.
1027 1027
1028 1028 The callback will be executed on lock release."""
1029 1029 l = self._lockref and self._lockref()
1030 1030 if l:
1031 1031 l.postrelease.append(callback)
1032 1032 else:
1033 1033 callback()
1034 1034
1035 1035 def lock(self, wait=True):
1036 1036 '''Lock the repository store (.hg/store) and return a weak reference
1037 1037 to the lock. Use this before modifying the store (e.g. committing or
1038 1038 stripping). If you are opening a transaction, get a lock as well.)'''
1039 1039 l = self._lockref and self._lockref()
1040 1040 if l is not None and l.held:
1041 1041 l.lock()
1042 1042 return l
1043 1043
1044 1044 def unlock():
1045 1045 if hasunfilteredcache(self, '_phasecache'):
1046 1046 self._phasecache.write()
1047 1047 for k, ce in self._filecache.items():
1048 1048 if k == 'dirstate' or k not in self.__dict__:
1049 1049 continue
1050 1050 ce.refresh()
1051 1051
1052 1052 l = self._lock(self.svfs, "lock", wait, unlock,
1053 1053 self.invalidate, _('repository %s') % self.origroot)
1054 1054 self._lockref = weakref.ref(l)
1055 1055 return l
1056 1056
1057 1057 def wlock(self, wait=True):
1058 1058 '''Lock the non-store parts of the repository (everything under
1059 1059 .hg except .hg/store) and return a weak reference to the lock.
1060 1060 Use this before modifying files in .hg.'''
1061 1061 l = self._wlockref and self._wlockref()
1062 1062 if l is not None and l.held:
1063 1063 l.lock()
1064 1064 return l
1065 1065
1066 1066 def unlock():
1067 1067 self.dirstate.write()
1068 1068 self._filecache['dirstate'].refresh()
1069 1069
1070 1070 l = self._lock(self.vfs, "wlock", wait, unlock,
1071 1071 self.invalidatedirstate, _('working directory of %s') %
1072 1072 self.origroot)
1073 1073 self._wlockref = weakref.ref(l)
1074 1074 return l
1075 1075
1076 1076 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1077 1077 """
1078 1078 commit an individual file as part of a larger transaction
1079 1079 """
1080 1080
1081 1081 fname = fctx.path()
1082 1082 text = fctx.data()
1083 1083 flog = self.file(fname)
1084 1084 fparent1 = manifest1.get(fname, nullid)
1085 1085 fparent2 = fparent2o = manifest2.get(fname, nullid)
1086 1086
1087 1087 meta = {}
1088 1088 copy = fctx.renamed()
1089 1089 if copy and copy[0] != fname:
1090 1090 # Mark the new revision of this file as a copy of another
1091 1091 # file. This copy data will effectively act as a parent
1092 1092 # of this new revision. If this is a merge, the first
1093 1093 # parent will be the nullid (meaning "look up the copy data")
1094 1094 # and the second one will be the other parent. For example:
1095 1095 #
1096 1096 # 0 --- 1 --- 3 rev1 changes file foo
1097 1097 # \ / rev2 renames foo to bar and changes it
1098 1098 # \- 2 -/ rev3 should have bar with all changes and
1099 1099 # should record that bar descends from
1100 1100 # bar in rev2 and foo in rev1
1101 1101 #
1102 1102 # this allows this merge to succeed:
1103 1103 #
1104 1104 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1105 1105 # \ / merging rev3 and rev4 should use bar@rev2
1106 1106 # \- 2 --- 4 as the merge base
1107 1107 #
1108 1108
1109 1109 cfname = copy[0]
1110 1110 crev = manifest1.get(cfname)
1111 1111 newfparent = fparent2
1112 1112
1113 1113 if manifest2: # branch merge
1114 1114 if fparent2 == nullid or crev is None: # copied on remote side
1115 1115 if cfname in manifest2:
1116 1116 crev = manifest2[cfname]
1117 1117 newfparent = fparent1
1118 1118
1119 1119 # find source in nearest ancestor if we've lost track
1120 1120 if not crev:
1121 1121 self.ui.debug(" %s: searching for copy revision for %s\n" %
1122 1122 (fname, cfname))
1123 1123 for ancestor in self[None].ancestors():
1124 1124 if cfname in ancestor:
1125 1125 crev = ancestor[cfname].filenode()
1126 1126 break
1127 1127
1128 1128 if crev:
1129 1129 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1130 1130 meta["copy"] = cfname
1131 1131 meta["copyrev"] = hex(crev)
1132 1132 fparent1, fparent2 = nullid, newfparent
1133 1133 else:
1134 1134 self.ui.warn(_("warning: can't find ancestor for '%s' "
1135 1135 "copied from '%s'!\n") % (fname, cfname))
1136 1136
1137 1137 elif fparent1 == nullid:
1138 1138 fparent1, fparent2 = fparent2, nullid
1139 1139 elif fparent2 != nullid:
1140 1140 # is one parent an ancestor of the other?
1141 1141 fparentancestor = flog.ancestor(fparent1, fparent2)
1142 1142 if fparentancestor == fparent1:
1143 1143 fparent1, fparent2 = fparent2, nullid
1144 1144 elif fparentancestor == fparent2:
1145 1145 fparent2 = nullid
1146 1146
1147 1147 # is the file changed?
1148 1148 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1149 1149 changelist.append(fname)
1150 1150 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1151 1151
1152 1152 # are just the flags changed during merge?
1153 1153 if fparent1 != fparent2o and manifest1.flags(fname) != fctx.flags():
1154 1154 changelist.append(fname)
1155 1155
1156 1156 return fparent1
1157 1157
1158 1158 @unfilteredmethod
1159 1159 def commit(self, text="", user=None, date=None, match=None, force=False,
1160 1160 editor=False, extra={}):
1161 1161 """Add a new revision to current repository.
1162 1162
1163 1163 Revision information is gathered from the working directory,
1164 1164 match can be used to filter the committed files. If editor is
1165 1165 supplied, it is called to get a commit message.
1166 1166 """
1167 1167
1168 1168 def fail(f, msg):
1169 1169 raise util.Abort('%s: %s' % (f, msg))
1170 1170
1171 1171 if not match:
1172 1172 match = matchmod.always(self.root, '')
1173 1173
1174 1174 if not force:
1175 1175 vdirs = []
1176 1176 match.explicitdir = vdirs.append
1177 1177 match.bad = fail
1178 1178
1179 1179 wlock = self.wlock()
1180 1180 try:
1181 1181 wctx = self[None]
1182 1182 merge = len(wctx.parents()) > 1
1183 1183
1184 1184 if (not force and merge and match and
1185 1185 (match.files() or match.anypats())):
1186 1186 raise util.Abort(_('cannot partially commit a merge '
1187 1187 '(do not specify files or patterns)'))
1188 1188
1189 1189 changes = self.status(match=match, clean=force)
1190 1190 if force:
1191 1191 changes[0].extend(changes[6]) # mq may commit unchanged files
1192 1192
1193 1193 # check subrepos
1194 1194 subs = []
1195 1195 commitsubs = set()
1196 1196 newstate = wctx.substate.copy()
1197 1197 # only manage subrepos and .hgsubstate if .hgsub is present
1198 1198 if '.hgsub' in wctx:
1199 1199 # we'll decide whether to track this ourselves, thanks
1200 1200 for c in changes[:3]:
1201 1201 if '.hgsubstate' in c:
1202 1202 c.remove('.hgsubstate')
1203 1203
1204 1204 # compare current state to last committed state
1205 1205 # build new substate based on last committed state
1206 1206 oldstate = wctx.p1().substate
1207 1207 for s in sorted(newstate.keys()):
1208 1208 if not match(s):
1209 1209 # ignore working copy, use old state if present
1210 1210 if s in oldstate:
1211 1211 newstate[s] = oldstate[s]
1212 1212 continue
1213 1213 if not force:
1214 1214 raise util.Abort(
1215 1215 _("commit with new subrepo %s excluded") % s)
1216 1216 if wctx.sub(s).dirty(True):
1217 1217 if not self.ui.configbool('ui', 'commitsubrepos'):
1218 1218 raise util.Abort(
1219 1219 _("uncommitted changes in subrepo %s") % s,
1220 1220 hint=_("use --subrepos for recursive commit"))
1221 1221 subs.append(s)
1222 1222 commitsubs.add(s)
1223 1223 else:
1224 1224 bs = wctx.sub(s).basestate()
1225 1225 newstate[s] = (newstate[s][0], bs, newstate[s][2])
1226 1226 if oldstate.get(s, (None, None, None))[1] != bs:
1227 1227 subs.append(s)
1228 1228
1229 1229 # check for removed subrepos
1230 1230 for p in wctx.parents():
1231 1231 r = [s for s in p.substate if s not in newstate]
1232 1232 subs += [s for s in r if match(s)]
1233 1233 if subs:
1234 1234 if (not match('.hgsub') and
1235 1235 '.hgsub' in (wctx.modified() + wctx.added())):
1236 1236 raise util.Abort(
1237 1237 _("can't commit subrepos without .hgsub"))
1238 1238 changes[0].insert(0, '.hgsubstate')
1239 1239
1240 1240 elif '.hgsub' in changes[2]:
1241 1241 # clean up .hgsubstate when .hgsub is removed
1242 1242 if ('.hgsubstate' in wctx and
1243 1243 '.hgsubstate' not in changes[0] + changes[1] + changes[2]):
1244 1244 changes[2].insert(0, '.hgsubstate')
1245 1245
1246 1246 # make sure all explicit patterns are matched
1247 1247 if not force and match.files():
1248 1248 matched = set(changes[0] + changes[1] + changes[2])
1249 1249
1250 1250 for f in match.files():
1251 1251 f = self.dirstate.normalize(f)
1252 1252 if f == '.' or f in matched or f in wctx.substate:
1253 1253 continue
1254 1254 if f in changes[3]: # missing
1255 1255 fail(f, _('file not found!'))
1256 1256 if f in vdirs: # visited directory
1257 1257 d = f + '/'
1258 1258 for mf in matched:
1259 1259 if mf.startswith(d):
1260 1260 break
1261 1261 else:
1262 1262 fail(f, _("no match under directory!"))
1263 1263 elif f not in self.dirstate:
1264 1264 fail(f, _("file not tracked!"))
1265 1265
1266 1266 cctx = context.workingctx(self, text, user, date, extra, changes)
1267 1267
1268 1268 if (not force and not extra.get("close") and not merge
1269 1269 and not cctx.files()
1270 1270 and wctx.branch() == wctx.p1().branch()):
1271 1271 return None
1272 1272
1273 1273 if merge and cctx.deleted():
1274 1274 raise util.Abort(_("cannot commit merge with missing files"))
1275 1275
1276 1276 ms = mergemod.mergestate(self)
1277 1277 for f in changes[0]:
1278 1278 if f in ms and ms[f] == 'u':
1279 1279 raise util.Abort(_("unresolved merge conflicts "
1280 1280 "(see hg help resolve)"))
1281 1281
1282 1282 if editor:
1283 1283 cctx._text = editor(self, cctx, subs)
1284 1284 edited = (text != cctx._text)
1285 1285
1286 1286 # Save commit message in case this transaction gets rolled back
1287 1287 # (e.g. by a pretxncommit hook). Leave the content alone on
1288 1288 # the assumption that the user will use the same editor again.
1289 1289 msgfn = self.savecommitmessage(cctx._text)
1290 1290
1291 1291 # commit subs and write new state
1292 1292 if subs:
1293 1293 for s in sorted(commitsubs):
1294 1294 sub = wctx.sub(s)
1295 1295 self.ui.status(_('committing subrepository %s\n') %
1296 1296 subrepo.subrelpath(sub))
1297 1297 sr = sub.commit(cctx._text, user, date)
1298 1298 newstate[s] = (newstate[s][0], sr)
1299 1299 subrepo.writestate(self, newstate)
1300 1300
1301 1301 p1, p2 = self.dirstate.parents()
1302 1302 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1303 1303 try:
1304 1304 self.hook("precommit", throw=True, parent1=hookp1,
1305 1305 parent2=hookp2)
1306 1306 ret = self.commitctx(cctx, True)
1307 1307 except: # re-raises
1308 1308 if edited:
1309 1309 self.ui.write(
1310 1310 _('note: commit message saved in %s\n') % msgfn)
1311 1311 raise
1312 1312
1313 1313 # update bookmarks, dirstate and mergestate
1314 1314 bookmarks.update(self, [p1, p2], ret)
1315 1315 cctx.markcommitted(ret)
1316 1316 ms.reset()
1317 1317 finally:
1318 1318 wlock.release()
1319 1319
1320 1320 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
1321 1321 self.hook("commit", node=node, parent1=parent1, parent2=parent2)
1322 1322 self._afterlock(commithook)
1323 1323 return ret
1324 1324
1325 1325 @unfilteredmethod
1326 1326 def commitctx(self, ctx, error=False):
1327 1327 """Add a new revision to current repository.
1328 1328 Revision information is passed via the context argument.
1329 1329 """
1330 1330
1331 1331 tr = lock = None
1332 1332 removed = list(ctx.removed())
1333 1333 p1, p2 = ctx.p1(), ctx.p2()
1334 1334 user = ctx.user()
1335 1335
1336 1336 lock = self.lock()
1337 1337 try:
1338 1338 tr = self.transaction("commit")
1339 1339 trp = weakref.proxy(tr)
1340 1340
1341 1341 if ctx.files():
1342 1342 m1 = p1.manifest().copy()
1343 1343 m2 = p2.manifest()
1344 1344
1345 1345 # check in files
1346 1346 new = {}
1347 1347 changed = []
1348 1348 linkrev = len(self)
1349 1349 for f in sorted(ctx.modified() + ctx.added()):
1350 1350 self.ui.note(f + "\n")
1351 1351 try:
1352 1352 fctx = ctx[f]
1353 1353 new[f] = self._filecommit(fctx, m1, m2, linkrev, trp,
1354 1354 changed)
1355 1355 m1.set(f, fctx.flags())
1356 1356 except OSError, inst:
1357 1357 self.ui.warn(_("trouble committing %s!\n") % f)
1358 1358 raise
1359 1359 except IOError, inst:
1360 1360 errcode = getattr(inst, 'errno', errno.ENOENT)
1361 1361 if error or errcode and errcode != errno.ENOENT:
1362 1362 self.ui.warn(_("trouble committing %s!\n") % f)
1363 1363 raise
1364 1364 else:
1365 1365 removed.append(f)
1366 1366
1367 1367 # update manifest
1368 1368 m1.update(new)
1369 1369 removed = [f for f in sorted(removed) if f in m1 or f in m2]
1370 1370 drop = [f for f in removed if f in m1]
1371 1371 for f in drop:
1372 1372 del m1[f]
1373 1373 mn = self.manifest.add(m1, trp, linkrev, p1.manifestnode(),
1374 1374 p2.manifestnode(), (new, drop))
1375 1375 files = changed + removed
1376 1376 else:
1377 1377 mn = p1.manifestnode()
1378 1378 files = []
1379 1379
1380 1380 # update changelog
1381 1381 self.changelog.delayupdate()
1382 1382 n = self.changelog.add(mn, files, ctx.description(),
1383 1383 trp, p1.node(), p2.node(),
1384 1384 user, ctx.date(), ctx.extra().copy())
1385 1385 p = lambda: self.changelog.writepending() and self.root or ""
1386 1386 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
1387 1387 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
1388 1388 parent2=xp2, pending=p)
1389 1389 self.changelog.finalize(trp)
1390 1390 # set the new commit is proper phase
1391 1391 targetphase = subrepo.newcommitphase(self.ui, ctx)
1392 1392 if targetphase:
1393 1393 # retract boundary do not alter parent changeset.
1394 1394 # if a parent have higher the resulting phase will
1395 1395 # be compliant anyway
1396 1396 #
1397 1397 # if minimal phase was 0 we don't need to retract anything
1398 1398 phases.retractboundary(self, targetphase, [n])
1399 1399 tr.close()
1400 1400 branchmap.updatecache(self.filtered('served'))
1401 1401 return n
1402 1402 finally:
1403 1403 if tr:
1404 1404 tr.release()
1405 1405 lock.release()
1406 1406
1407 1407 @unfilteredmethod
1408 1408 def destroying(self):
1409 1409 '''Inform the repository that nodes are about to be destroyed.
1410 1410 Intended for use by strip and rollback, so there's a common
1411 1411 place for anything that has to be done before destroying history.
1412 1412
1413 1413 This is mostly useful for saving state that is in memory and waiting
1414 1414 to be flushed when the current lock is released. Because a call to
1415 1415 destroyed is imminent, the repo will be invalidated causing those
1416 1416 changes to stay in memory (waiting for the next unlock), or vanish
1417 1417 completely.
1418 1418 '''
1419 1419 # When using the same lock to commit and strip, the phasecache is left
1420 1420 # dirty after committing. Then when we strip, the repo is invalidated,
1421 1421 # causing those changes to disappear.
1422 1422 if '_phasecache' in vars(self):
1423 1423 self._phasecache.write()
1424 1424
1425 1425 @unfilteredmethod
1426 1426 def destroyed(self):
1427 1427 '''Inform the repository that nodes have been destroyed.
1428 1428 Intended for use by strip and rollback, so there's a common
1429 1429 place for anything that has to be done after destroying history.
1430 1430 '''
1431 1431 # When one tries to:
1432 1432 # 1) destroy nodes thus calling this method (e.g. strip)
1433 1433 # 2) use phasecache somewhere (e.g. commit)
1434 1434 #
1435 1435 # then 2) will fail because the phasecache contains nodes that were
1436 1436 # removed. We can either remove phasecache from the filecache,
1437 1437 # causing it to reload next time it is accessed, or simply filter
1438 1438 # the removed nodes now and write the updated cache.
1439 1439 self._phasecache.filterunknown(self)
1440 1440 self._phasecache.write()
1441 1441
1442 1442 # update the 'served' branch cache to help read only server process
1443 1443 # Thanks to branchcache collaboration this is done from the nearest
1444 1444 # filtered subset and it is expected to be fast.
1445 1445 branchmap.updatecache(self.filtered('served'))
1446 1446
1447 1447 # Ensure the persistent tag cache is updated. Doing it now
1448 1448 # means that the tag cache only has to worry about destroyed
1449 1449 # heads immediately after a strip/rollback. That in turn
1450 1450 # guarantees that "cachetip == currenttip" (comparing both rev
1451 1451 # and node) always means no nodes have been added or destroyed.
1452 1452
1453 1453 # XXX this is suboptimal when qrefresh'ing: we strip the current
1454 1454 # head, refresh the tag cache, then immediately add a new head.
1455 1455 # But I think doing it this way is necessary for the "instant
1456 1456 # tag cache retrieval" case to work.
1457 1457 self.invalidate()
1458 1458
1459 1459 def walk(self, match, node=None):
1460 1460 '''
1461 1461 walk recursively through the directory tree or a given
1462 1462 changeset, finding all files matched by the match
1463 1463 function
1464 1464 '''
1465 1465 return self[node].walk(match)
1466 1466
1467 1467 def status(self, node1='.', node2=None, match=None,
1468 1468 ignored=False, clean=False, unknown=False,
1469 1469 listsubrepos=False):
1470 1470 """return status of files between two nodes or node and working
1471 1471 directory.
1472 1472
1473 1473 If node1 is None, use the first dirstate parent instead.
1474 1474 If node2 is None, compare node1 with working directory.
1475 1475 """
1476 1476
1477 1477 def mfmatches(ctx):
1478 1478 mf = ctx.manifest().copy()
1479 1479 if match.always():
1480 1480 return mf
1481 1481 for fn in mf.keys():
1482 1482 if not match(fn):
1483 1483 del mf[fn]
1484 1484 return mf
1485 1485
1486 1486 ctx1 = self[node1]
1487 1487 ctx2 = self[node2]
1488 1488
1489 1489 working = ctx2.rev() is None
1490 1490 parentworking = working and ctx1 == self['.']
1491 1491 match = match or matchmod.always(self.root, self.getcwd())
1492 1492 listignored, listclean, listunknown = ignored, clean, unknown
1493 1493
1494 1494 # load earliest manifest first for caching reasons
1495 1495 if not working and ctx2.rev() < ctx1.rev():
1496 1496 ctx2.manifest()
1497 1497
1498 1498 if not parentworking:
1499 1499 def bad(f, msg):
1500 1500 # 'f' may be a directory pattern from 'match.files()',
1501 1501 # so 'f not in ctx1' is not enough
1502 1502 if f not in ctx1 and f not in ctx1.dirs():
1503 1503 self.ui.warn('%s: %s\n' % (self.dirstate.pathto(f), msg))
1504 1504 match.bad = bad
1505 1505
1506 1506 if working: # we need to scan the working dir
1507 1507 subrepos = []
1508 1508 if '.hgsub' in self.dirstate:
1509 1509 subrepos = sorted(ctx2.substate)
1510 1510 s = self.dirstate.status(match, subrepos, listignored,
1511 1511 listclean, listunknown)
1512 1512 cmp, modified, added, removed, deleted, unknown, ignored, clean = s
1513 1513
1514 1514 # check for any possibly clean files
1515 1515 if parentworking and cmp:
1516 1516 fixup = []
1517 1517 # do a full compare of any files that might have changed
1518 1518 for f in sorted(cmp):
1519 1519 if (f not in ctx1 or ctx2.flags(f) != ctx1.flags(f)
1520 1520 or ctx1[f].cmp(ctx2[f])):
1521 1521 modified.append(f)
1522 1522 else:
1523 1523 fixup.append(f)
1524 1524
1525 1525 # update dirstate for files that are actually clean
1526 1526 if fixup:
1527 1527 if listclean:
1528 1528 clean += fixup
1529 1529
1530 1530 try:
1531 1531 # updating the dirstate is optional
1532 1532 # so we don't wait on the lock
1533 1533 wlock = self.wlock(False)
1534 1534 try:
1535 1535 for f in fixup:
1536 1536 self.dirstate.normal(f)
1537 1537 finally:
1538 1538 wlock.release()
1539 1539 except error.LockError:
1540 1540 pass
1541 1541
1542 1542 if not parentworking:
1543 1543 mf1 = mfmatches(ctx1)
1544 1544 if working:
1545 1545 # we are comparing working dir against non-parent
1546 1546 # generate a pseudo-manifest for the working dir
1547 1547 mf2 = mfmatches(self['.'])
1548 1548 for f in cmp + modified + added:
1549 1549 mf2[f] = None
1550 1550 mf2.set(f, ctx2.flags(f))
1551 1551 for f in removed:
1552 1552 if f in mf2:
1553 1553 del mf2[f]
1554 1554 else:
1555 1555 # we are comparing two revisions
1556 1556 deleted, unknown, ignored = [], [], []
1557 1557 mf2 = mfmatches(ctx2)
1558 1558
1559 1559 modified, added, clean = [], [], []
1560 1560 withflags = mf1.withflags() | mf2.withflags()
1561 1561 for fn, mf2node in mf2.iteritems():
1562 1562 if fn in mf1:
1563 1563 if (fn not in deleted and
1564 1564 ((fn in withflags and mf1.flags(fn) != mf2.flags(fn)) or
1565 1565 (mf1[fn] != mf2node and
1566 1566 (mf2node or ctx1[fn].cmp(ctx2[fn]))))):
1567 1567 modified.append(fn)
1568 1568 elif listclean:
1569 1569 clean.append(fn)
1570 1570 del mf1[fn]
1571 1571 elif fn not in deleted:
1572 1572 added.append(fn)
1573 1573 removed = mf1.keys()
1574 1574
1575 1575 if working and modified and not self.dirstate._checklink:
1576 1576 # Symlink placeholders may get non-symlink-like contents
1577 1577 # via user error or dereferencing by NFS or Samba servers,
1578 1578 # so we filter out any placeholders that don't look like a
1579 1579 # symlink
1580 1580 sane = []
1581 1581 for f in modified:
1582 1582 if ctx2.flags(f) == 'l':
1583 1583 d = ctx2[f].data()
1584 1584 if d == '' or len(d) >= 1024 or '\n' in d or util.binary(d):
1585 1585 self.ui.debug('ignoring suspect symlink placeholder'
1586 1586 ' "%s"\n' % f)
1587 1587 continue
1588 1588 sane.append(f)
1589 1589 modified = sane
1590 1590
1591 1591 r = modified, added, removed, deleted, unknown, ignored, clean
1592 1592
1593 1593 if listsubrepos:
1594 1594 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1595 1595 if working:
1596 1596 rev2 = None
1597 1597 else:
1598 1598 rev2 = ctx2.substate[subpath][1]
1599 1599 try:
1600 1600 submatch = matchmod.narrowmatcher(subpath, match)
1601 1601 s = sub.status(rev2, match=submatch, ignored=listignored,
1602 1602 clean=listclean, unknown=listunknown,
1603 1603 listsubrepos=True)
1604 1604 for rfiles, sfiles in zip(r, s):
1605 1605 rfiles.extend("%s/%s" % (subpath, f) for f in sfiles)
1606 1606 except error.LookupError:
1607 1607 self.ui.status(_("skipping missing subrepository: %s\n")
1608 1608 % subpath)
1609 1609
1610 1610 for l in r:
1611 1611 l.sort()
1612 1612 return r
1613 1613
1614 1614 def heads(self, start=None):
1615 1615 heads = self.changelog.heads(start)
1616 1616 # sort the output in rev descending order
1617 1617 return sorted(heads, key=self.changelog.rev, reverse=True)
1618 1618
1619 1619 def branchheads(self, branch=None, start=None, closed=False):
1620 1620 '''return a (possibly filtered) list of heads for the given branch
1621 1621
1622 1622 Heads are returned in topological order, from newest to oldest.
1623 1623 If branch is None, use the dirstate branch.
1624 1624 If start is not None, return only heads reachable from start.
1625 1625 If closed is True, return heads that are marked as closed as well.
1626 1626 '''
1627 1627 if branch is None:
1628 1628 branch = self[None].branch()
1629 1629 branches = self.branchmap()
1630 1630 if branch not in branches:
1631 1631 return []
1632 1632 # the cache returns heads ordered lowest to highest
1633 1633 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
1634 1634 if start is not None:
1635 1635 # filter out the heads that cannot be reached from startrev
1636 1636 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
1637 1637 bheads = [h for h in bheads if h in fbheads]
1638 1638 return bheads
1639 1639
1640 1640 def branches(self, nodes):
1641 1641 if not nodes:
1642 1642 nodes = [self.changelog.tip()]
1643 1643 b = []
1644 1644 for n in nodes:
1645 1645 t = n
1646 1646 while True:
1647 1647 p = self.changelog.parents(n)
1648 1648 if p[1] != nullid or p[0] == nullid:
1649 1649 b.append((t, n, p[0], p[1]))
1650 1650 break
1651 1651 n = p[0]
1652 1652 return b
1653 1653
1654 1654 def between(self, pairs):
1655 1655 r = []
1656 1656
1657 1657 for top, bottom in pairs:
1658 1658 n, l, i = top, [], 0
1659 1659 f = 1
1660 1660
1661 1661 while n != bottom and n != nullid:
1662 1662 p = self.changelog.parents(n)[0]
1663 1663 if i == f:
1664 1664 l.append(n)
1665 1665 f = f * 2
1666 1666 n = p
1667 1667 i += 1
1668 1668
1669 1669 r.append(l)
1670 1670
1671 1671 return r
1672 1672
1673 1673 def pull(self, remote, heads=None, force=False):
1674 1674 return exchange.pull (self, remote, heads, force)
1675 1675
1676 1676 def checkpush(self, pushop):
1677 1677 """Extensions can override this function if additional checks have
1678 1678 to be performed before pushing, or call it if they override push
1679 1679 command.
1680 1680 """
1681 1681 pass
1682 1682
1683 1683 def push(self, remote, force=False, revs=None, newbranch=False):
1684 1684 return exchange.push(self, remote, force, revs, newbranch)
1685 1685
1686 def changegroup(self, basenodes, source):
1687 # to avoid a race we use changegroupsubset() (issue1320)
1688 return changegroup.changegroupsubset(self, basenodes, self.heads(),
1689 source)
1690
1691 1686 @unfilteredmethod
1692 1687 def addchangegroup(self, source, srctype, url, emptyok=False):
1693 1688 """Add the changegroup returned by source.read() to this repo.
1694 1689 srctype is a string like 'push', 'pull', or 'unbundle'. url is
1695 1690 the URL of the repo where this changegroup is coming from.
1696 1691
1697 1692 Return an integer summarizing the change to this repo:
1698 1693 - nothing changed or no source: 0
1699 1694 - more heads than before: 1+added heads (2..n)
1700 1695 - fewer heads than before: -1-removed heads (-2..-n)
1701 1696 - number of heads stays the same: 1
1702 1697 """
1703 1698 def csmap(x):
1704 1699 self.ui.debug("add changeset %s\n" % short(x))
1705 1700 return len(cl)
1706 1701
1707 1702 def revmap(x):
1708 1703 return cl.rev(x)
1709 1704
1710 1705 if not source:
1711 1706 return 0
1712 1707
1713 1708 self.hook('prechangegroup', throw=True, source=srctype, url=url)
1714 1709
1715 1710 changesets = files = revisions = 0
1716 1711 efiles = set()
1717 1712
1718 1713 # write changelog data to temp files so concurrent readers will not see
1719 1714 # inconsistent view
1720 1715 cl = self.changelog
1721 1716 cl.delayupdate()
1722 1717 oldheads = cl.heads()
1723 1718
1724 1719 tr = self.transaction("\n".join([srctype, util.hidepassword(url)]))
1725 1720 try:
1726 1721 trp = weakref.proxy(tr)
1727 1722 # pull off the changeset group
1728 1723 self.ui.status(_("adding changesets\n"))
1729 1724 clstart = len(cl)
1730 1725 class prog(object):
1731 1726 step = _('changesets')
1732 1727 count = 1
1733 1728 ui = self.ui
1734 1729 total = None
1735 1730 def __call__(self):
1736 1731 self.ui.progress(self.step, self.count, unit=_('chunks'),
1737 1732 total=self.total)
1738 1733 self.count += 1
1739 1734 pr = prog()
1740 1735 source.callback = pr
1741 1736
1742 1737 source.changelogheader()
1743 1738 srccontent = cl.addgroup(source, csmap, trp)
1744 1739 if not (srccontent or emptyok):
1745 1740 raise util.Abort(_("received changelog group is empty"))
1746 1741 clend = len(cl)
1747 1742 changesets = clend - clstart
1748 1743 for c in xrange(clstart, clend):
1749 1744 efiles.update(self[c].files())
1750 1745 efiles = len(efiles)
1751 1746 self.ui.progress(_('changesets'), None)
1752 1747
1753 1748 # pull off the manifest group
1754 1749 self.ui.status(_("adding manifests\n"))
1755 1750 pr.step = _('manifests')
1756 1751 pr.count = 1
1757 1752 pr.total = changesets # manifests <= changesets
1758 1753 # no need to check for empty manifest group here:
1759 1754 # if the result of the merge of 1 and 2 is the same in 3 and 4,
1760 1755 # no new manifest will be created and the manifest group will
1761 1756 # be empty during the pull
1762 1757 source.manifestheader()
1763 1758 self.manifest.addgroup(source, revmap, trp)
1764 1759 self.ui.progress(_('manifests'), None)
1765 1760
1766 1761 needfiles = {}
1767 1762 if self.ui.configbool('server', 'validate', default=False):
1768 1763 # validate incoming csets have their manifests
1769 1764 for cset in xrange(clstart, clend):
1770 1765 mfest = self.changelog.read(self.changelog.node(cset))[0]
1771 1766 mfest = self.manifest.readdelta(mfest)
1772 1767 # store file nodes we must see
1773 1768 for f, n in mfest.iteritems():
1774 1769 needfiles.setdefault(f, set()).add(n)
1775 1770
1776 1771 # process the files
1777 1772 self.ui.status(_("adding file changes\n"))
1778 1773 pr.step = _('files')
1779 1774 pr.count = 1
1780 1775 pr.total = efiles
1781 1776 source.callback = None
1782 1777
1783 1778 newrevs, newfiles = self.addchangegroupfiles(source, revmap, trp,
1784 1779 pr, needfiles)
1785 1780 revisions += newrevs
1786 1781 files += newfiles
1787 1782
1788 1783 dh = 0
1789 1784 if oldheads:
1790 1785 heads = cl.heads()
1791 1786 dh = len(heads) - len(oldheads)
1792 1787 for h in heads:
1793 1788 if h not in oldheads and self[h].closesbranch():
1794 1789 dh -= 1
1795 1790 htext = ""
1796 1791 if dh:
1797 1792 htext = _(" (%+d heads)") % dh
1798 1793
1799 1794 self.ui.status(_("added %d changesets"
1800 1795 " with %d changes to %d files%s\n")
1801 1796 % (changesets, revisions, files, htext))
1802 1797 self.invalidatevolatilesets()
1803 1798
1804 1799 if changesets > 0:
1805 1800 p = lambda: cl.writepending() and self.root or ""
1806 1801 self.hook('pretxnchangegroup', throw=True,
1807 1802 node=hex(cl.node(clstart)), source=srctype,
1808 1803 url=url, pending=p)
1809 1804
1810 1805 added = [cl.node(r) for r in xrange(clstart, clend)]
1811 1806 publishing = self.ui.configbool('phases', 'publish', True)
1812 1807 if srctype == 'push':
1813 1808 # Old servers can not push the boundary themselves.
1814 1809 # New servers won't push the boundary if changeset already
1815 1810 # exists locally as secret
1816 1811 #
1817 1812 # We should not use added here but the list of all change in
1818 1813 # the bundle
1819 1814 if publishing:
1820 1815 phases.advanceboundary(self, phases.public, srccontent)
1821 1816 else:
1822 1817 phases.advanceboundary(self, phases.draft, srccontent)
1823 1818 phases.retractboundary(self, phases.draft, added)
1824 1819 elif srctype != 'strip':
1825 1820 # publishing only alter behavior during push
1826 1821 #
1827 1822 # strip should not touch boundary at all
1828 1823 phases.retractboundary(self, phases.draft, added)
1829 1824
1830 1825 # make changelog see real files again
1831 1826 cl.finalize(trp)
1832 1827
1833 1828 tr.close()
1834 1829
1835 1830 if changesets > 0:
1836 1831 if srctype != 'strip':
1837 1832 # During strip, branchcache is invalid but coming call to
1838 1833 # `destroyed` will repair it.
1839 1834 # In other case we can safely update cache on disk.
1840 1835 branchmap.updatecache(self.filtered('served'))
1841 1836 def runhooks():
1842 1837 # These hooks run when the lock releases, not when the
1843 1838 # transaction closes. So it's possible for the changelog
1844 1839 # to have changed since we last saw it.
1845 1840 if clstart >= len(self):
1846 1841 return
1847 1842
1848 1843 # forcefully update the on-disk branch cache
1849 1844 self.ui.debug("updating the branch cache\n")
1850 1845 self.hook("changegroup", node=hex(cl.node(clstart)),
1851 1846 source=srctype, url=url)
1852 1847
1853 1848 for n in added:
1854 1849 self.hook("incoming", node=hex(n), source=srctype,
1855 1850 url=url)
1856 1851
1857 1852 newheads = [h for h in self.heads() if h not in oldheads]
1858 1853 self.ui.log("incoming",
1859 1854 "%s incoming changes - new heads: %s\n",
1860 1855 len(added),
1861 1856 ', '.join([hex(c[:6]) for c in newheads]))
1862 1857 self._afterlock(runhooks)
1863 1858
1864 1859 finally:
1865 1860 tr.release()
1866 1861 # never return 0 here:
1867 1862 if dh < 0:
1868 1863 return dh - 1
1869 1864 else:
1870 1865 return dh + 1
1871 1866
1872 1867 def addchangegroupfiles(self, source, revmap, trp, pr, needfiles):
1873 1868 revisions = 0
1874 1869 files = 0
1875 1870 while True:
1876 1871 chunkdata = source.filelogheader()
1877 1872 if not chunkdata:
1878 1873 break
1879 1874 f = chunkdata["filename"]
1880 1875 self.ui.debug("adding %s revisions\n" % f)
1881 1876 pr()
1882 1877 fl = self.file(f)
1883 1878 o = len(fl)
1884 1879 if not fl.addgroup(source, revmap, trp):
1885 1880 raise util.Abort(_("received file revlog group is empty"))
1886 1881 revisions += len(fl) - o
1887 1882 files += 1
1888 1883 if f in needfiles:
1889 1884 needs = needfiles[f]
1890 1885 for new in xrange(o, len(fl)):
1891 1886 n = fl.node(new)
1892 1887 if n in needs:
1893 1888 needs.remove(n)
1894 1889 else:
1895 1890 raise util.Abort(
1896 1891 _("received spurious file revlog entry"))
1897 1892 if not needs:
1898 1893 del needfiles[f]
1899 1894 self.ui.progress(_('files'), None)
1900 1895
1901 1896 for f, needs in needfiles.iteritems():
1902 1897 fl = self.file(f)
1903 1898 for n in needs:
1904 1899 try:
1905 1900 fl.rev(n)
1906 1901 except error.LookupError:
1907 1902 raise util.Abort(
1908 1903 _('missing file data for %s:%s - run hg verify') %
1909 1904 (f, hex(n)))
1910 1905
1911 1906 return revisions, files
1912 1907
1913 1908 def stream_in(self, remote, requirements):
1914 1909 lock = self.lock()
1915 1910 try:
1916 1911 # Save remote branchmap. We will use it later
1917 1912 # to speed up branchcache creation
1918 1913 rbranchmap = None
1919 1914 if remote.capable("branchmap"):
1920 1915 rbranchmap = remote.branchmap()
1921 1916
1922 1917 fp = remote.stream_out()
1923 1918 l = fp.readline()
1924 1919 try:
1925 1920 resp = int(l)
1926 1921 except ValueError:
1927 1922 raise error.ResponseError(
1928 1923 _('unexpected response from remote server:'), l)
1929 1924 if resp == 1:
1930 1925 raise util.Abort(_('operation forbidden by server'))
1931 1926 elif resp == 2:
1932 1927 raise util.Abort(_('locking the remote repository failed'))
1933 1928 elif resp != 0:
1934 1929 raise util.Abort(_('the server sent an unknown error code'))
1935 1930 self.ui.status(_('streaming all changes\n'))
1936 1931 l = fp.readline()
1937 1932 try:
1938 1933 total_files, total_bytes = map(int, l.split(' ', 1))
1939 1934 except (ValueError, TypeError):
1940 1935 raise error.ResponseError(
1941 1936 _('unexpected response from remote server:'), l)
1942 1937 self.ui.status(_('%d files to transfer, %s of data\n') %
1943 1938 (total_files, util.bytecount(total_bytes)))
1944 1939 handled_bytes = 0
1945 1940 self.ui.progress(_('clone'), 0, total=total_bytes)
1946 1941 start = time.time()
1947 1942
1948 1943 tr = self.transaction(_('clone'))
1949 1944 try:
1950 1945 for i in xrange(total_files):
1951 1946 # XXX doesn't support '\n' or '\r' in filenames
1952 1947 l = fp.readline()
1953 1948 try:
1954 1949 name, size = l.split('\0', 1)
1955 1950 size = int(size)
1956 1951 except (ValueError, TypeError):
1957 1952 raise error.ResponseError(
1958 1953 _('unexpected response from remote server:'), l)
1959 1954 if self.ui.debugflag:
1960 1955 self.ui.debug('adding %s (%s)\n' %
1961 1956 (name, util.bytecount(size)))
1962 1957 # for backwards compat, name was partially encoded
1963 1958 ofp = self.sopener(store.decodedir(name), 'w')
1964 1959 for chunk in util.filechunkiter(fp, limit=size):
1965 1960 handled_bytes += len(chunk)
1966 1961 self.ui.progress(_('clone'), handled_bytes,
1967 1962 total=total_bytes)
1968 1963 ofp.write(chunk)
1969 1964 ofp.close()
1970 1965 tr.close()
1971 1966 finally:
1972 1967 tr.release()
1973 1968
1974 1969 # Writing straight to files circumvented the inmemory caches
1975 1970 self.invalidate()
1976 1971
1977 1972 elapsed = time.time() - start
1978 1973 if elapsed <= 0:
1979 1974 elapsed = 0.001
1980 1975 self.ui.progress(_('clone'), None)
1981 1976 self.ui.status(_('transferred %s in %.1f seconds (%s/sec)\n') %
1982 1977 (util.bytecount(total_bytes), elapsed,
1983 1978 util.bytecount(total_bytes / elapsed)))
1984 1979
1985 1980 # new requirements = old non-format requirements +
1986 1981 # new format-related
1987 1982 # requirements from the streamed-in repository
1988 1983 requirements.update(set(self.requirements) - self.supportedformats)
1989 1984 self._applyrequirements(requirements)
1990 1985 self._writerequirements()
1991 1986
1992 1987 if rbranchmap:
1993 1988 rbheads = []
1994 1989 for bheads in rbranchmap.itervalues():
1995 1990 rbheads.extend(bheads)
1996 1991
1997 1992 if rbheads:
1998 1993 rtiprev = max((int(self.changelog.rev(node))
1999 1994 for node in rbheads))
2000 1995 cache = branchmap.branchcache(rbranchmap,
2001 1996 self[rtiprev].node(),
2002 1997 rtiprev)
2003 1998 # Try to stick it as low as possible
2004 1999 # filter above served are unlikely to be fetch from a clone
2005 2000 for candidate in ('base', 'immutable', 'served'):
2006 2001 rview = self.filtered(candidate)
2007 2002 if cache.validfor(rview):
2008 2003 self._branchcaches[candidate] = cache
2009 2004 cache.write(rview)
2010 2005 break
2011 2006 self.invalidate()
2012 2007 return len(self.heads()) + 1
2013 2008 finally:
2014 2009 lock.release()
2015 2010
2016 2011 def clone(self, remote, heads=[], stream=False):
2017 2012 '''clone remote repository.
2018 2013
2019 2014 keyword arguments:
2020 2015 heads: list of revs to clone (forces use of pull)
2021 2016 stream: use streaming clone if possible'''
2022 2017
2023 2018 # now, all clients that can request uncompressed clones can
2024 2019 # read repo formats supported by all servers that can serve
2025 2020 # them.
2026 2021
2027 2022 # if revlog format changes, client will have to check version
2028 2023 # and format flags on "stream" capability, and use
2029 2024 # uncompressed only if compatible.
2030 2025
2031 2026 if not stream:
2032 2027 # if the server explicitly prefers to stream (for fast LANs)
2033 2028 stream = remote.capable('stream-preferred')
2034 2029
2035 2030 if stream and not heads:
2036 2031 # 'stream' means remote revlog format is revlogv1 only
2037 2032 if remote.capable('stream'):
2038 2033 return self.stream_in(remote, set(('revlogv1',)))
2039 2034 # otherwise, 'streamreqs' contains the remote revlog format
2040 2035 streamreqs = remote.capable('streamreqs')
2041 2036 if streamreqs:
2042 2037 streamreqs = set(streamreqs.split(','))
2043 2038 # if we support it, stream in and adjust our requirements
2044 2039 if not streamreqs - self.supportedformats:
2045 2040 return self.stream_in(remote, streamreqs)
2046 2041 return self.pull(remote, heads)
2047 2042
2048 2043 def pushkey(self, namespace, key, old, new):
2049 2044 self.hook('prepushkey', throw=True, namespace=namespace, key=key,
2050 2045 old=old, new=new)
2051 2046 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2052 2047 ret = pushkey.push(self, namespace, key, old, new)
2053 2048 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2054 2049 ret=ret)
2055 2050 return ret
2056 2051
2057 2052 def listkeys(self, namespace):
2058 2053 self.hook('prelistkeys', throw=True, namespace=namespace)
2059 2054 self.ui.debug('listing keys for "%s"\n' % namespace)
2060 2055 values = pushkey.list(self, namespace)
2061 2056 self.hook('listkeys', namespace=namespace, values=values)
2062 2057 return values
2063 2058
2064 2059 def debugwireargs(self, one, two, three=None, four=None, five=None):
2065 2060 '''used to test argument passing over the wire'''
2066 2061 return "%s %s %s %s %s" % (one, two, three, four, five)
2067 2062
2068 2063 def savecommitmessage(self, text):
2069 2064 fp = self.opener('last-message.txt', 'wb')
2070 2065 try:
2071 2066 fp.write(text)
2072 2067 finally:
2073 2068 fp.close()
2074 2069 return self.pathto(fp.name[len(self.root) + 1:])
2075 2070
2076 2071 # used to avoid circular references so destructors work
2077 2072 def aftertrans(files):
2078 2073 renamefiles = [tuple(t) for t in files]
2079 2074 def a():
2080 2075 for vfs, src, dest in renamefiles:
2081 2076 try:
2082 2077 vfs.rename(src, dest)
2083 2078 except OSError: # journal file does not yet exist
2084 2079 pass
2085 2080 return a
2086 2081
2087 2082 def undoname(fn):
2088 2083 base, name = os.path.split(fn)
2089 2084 assert name.startswith('journal')
2090 2085 return os.path.join(base, name.replace('journal', 'undo', 1))
2091 2086
2092 2087 def instance(ui, path, create):
2093 2088 return localrepository(ui, util.urllocalpath(path), create)
2094 2089
2095 2090 def islocal(path):
2096 2091 return True
@@ -1,798 +1,798
1 1 # wireproto.py - generic wire protocol support functions
2 2 #
3 3 # Copyright 2005-2010 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 import urllib, tempfile, os, sys
9 9 from i18n import _
10 10 from node import bin, hex
11 11 import changegroup as changegroupmod
12 12 import peer, error, encoding, util, store
13 13
14 14
15 15 class abstractserverproto(object):
16 16 """abstract class that summarizes the protocol API
17 17
18 18 Used as reference and documentation.
19 19 """
20 20
21 21 def getargs(self, args):
22 22 """return the value for arguments in <args>
23 23
24 24 returns a list of values (same order as <args>)"""
25 25 raise NotImplementedError()
26 26
27 27 def getfile(self, fp):
28 28 """write the whole content of a file into a file like object
29 29
30 30 The file is in the form::
31 31
32 32 (<chunk-size>\n<chunk>)+0\n
33 33
34 34 chunk size is the ascii version of the int.
35 35 """
36 36 raise NotImplementedError()
37 37
38 38 def redirect(self):
39 39 """may setup interception for stdout and stderr
40 40
41 41 See also the `restore` method."""
42 42 raise NotImplementedError()
43 43
44 44 # If the `redirect` function does install interception, the `restore`
45 45 # function MUST be defined. If interception is not used, this function
46 46 # MUST NOT be defined.
47 47 #
48 48 # left commented here on purpose
49 49 #
50 50 #def restore(self):
51 51 # """reinstall previous stdout and stderr and return intercepted stdout
52 52 # """
53 53 # raise NotImplementedError()
54 54
55 55 def groupchunks(self, cg):
56 56 """return 4096 chunks from a changegroup object
57 57
58 58 Some protocols may have compressed the contents."""
59 59 raise NotImplementedError()
60 60
61 61 # abstract batching support
62 62
63 63 class future(object):
64 64 '''placeholder for a value to be set later'''
65 65 def set(self, value):
66 66 if util.safehasattr(self, 'value'):
67 67 raise error.RepoError("future is already set")
68 68 self.value = value
69 69
70 70 class batcher(object):
71 71 '''base class for batches of commands submittable in a single request
72 72
73 73 All methods invoked on instances of this class are simply queued and
74 74 return a a future for the result. Once you call submit(), all the queued
75 75 calls are performed and the results set in their respective futures.
76 76 '''
77 77 def __init__(self):
78 78 self.calls = []
79 79 def __getattr__(self, name):
80 80 def call(*args, **opts):
81 81 resref = future()
82 82 self.calls.append((name, args, opts, resref,))
83 83 return resref
84 84 return call
85 85 def submit(self):
86 86 pass
87 87
88 88 class localbatch(batcher):
89 89 '''performs the queued calls directly'''
90 90 def __init__(self, local):
91 91 batcher.__init__(self)
92 92 self.local = local
93 93 def submit(self):
94 94 for name, args, opts, resref in self.calls:
95 95 resref.set(getattr(self.local, name)(*args, **opts))
96 96
97 97 class remotebatch(batcher):
98 98 '''batches the queued calls; uses as few roundtrips as possible'''
99 99 def __init__(self, remote):
100 100 '''remote must support _submitbatch(encbatch) and
101 101 _submitone(op, encargs)'''
102 102 batcher.__init__(self)
103 103 self.remote = remote
104 104 def submit(self):
105 105 req, rsp = [], []
106 106 for name, args, opts, resref in self.calls:
107 107 mtd = getattr(self.remote, name)
108 108 batchablefn = getattr(mtd, 'batchable', None)
109 109 if batchablefn is not None:
110 110 batchable = batchablefn(mtd.im_self, *args, **opts)
111 111 encargsorres, encresref = batchable.next()
112 112 if encresref:
113 113 req.append((name, encargsorres,))
114 114 rsp.append((batchable, encresref, resref,))
115 115 else:
116 116 resref.set(encargsorres)
117 117 else:
118 118 if req:
119 119 self._submitreq(req, rsp)
120 120 req, rsp = [], []
121 121 resref.set(mtd(*args, **opts))
122 122 if req:
123 123 self._submitreq(req, rsp)
124 124 def _submitreq(self, req, rsp):
125 125 encresults = self.remote._submitbatch(req)
126 126 for encres, r in zip(encresults, rsp):
127 127 batchable, encresref, resref = r
128 128 encresref.set(encres)
129 129 resref.set(batchable.next())
130 130
131 131 def batchable(f):
132 132 '''annotation for batchable methods
133 133
134 134 Such methods must implement a coroutine as follows:
135 135
136 136 @batchable
137 137 def sample(self, one, two=None):
138 138 # Handle locally computable results first:
139 139 if not one:
140 140 yield "a local result", None
141 141 # Build list of encoded arguments suitable for your wire protocol:
142 142 encargs = [('one', encode(one),), ('two', encode(two),)]
143 143 # Create future for injection of encoded result:
144 144 encresref = future()
145 145 # Return encoded arguments and future:
146 146 yield encargs, encresref
147 147 # Assuming the future to be filled with the result from the batched
148 148 # request now. Decode it:
149 149 yield decode(encresref.value)
150 150
151 151 The decorator returns a function which wraps this coroutine as a plain
152 152 method, but adds the original method as an attribute called "batchable",
153 153 which is used by remotebatch to split the call into separate encoding and
154 154 decoding phases.
155 155 '''
156 156 def plain(*args, **opts):
157 157 batchable = f(*args, **opts)
158 158 encargsorres, encresref = batchable.next()
159 159 if not encresref:
160 160 return encargsorres # a local result in this case
161 161 self = args[0]
162 162 encresref.set(self._submitone(f.func_name, encargsorres))
163 163 return batchable.next()
164 164 setattr(plain, 'batchable', f)
165 165 return plain
166 166
167 167 # list of nodes encoding / decoding
168 168
169 169 def decodelist(l, sep=' '):
170 170 if l:
171 171 return map(bin, l.split(sep))
172 172 return []
173 173
174 174 def encodelist(l, sep=' '):
175 175 return sep.join(map(hex, l))
176 176
177 177 # batched call argument encoding
178 178
179 179 def escapearg(plain):
180 180 return (plain
181 181 .replace(':', '::')
182 182 .replace(',', ':,')
183 183 .replace(';', ':;')
184 184 .replace('=', ':='))
185 185
186 186 def unescapearg(escaped):
187 187 return (escaped
188 188 .replace(':=', '=')
189 189 .replace(':;', ';')
190 190 .replace(':,', ',')
191 191 .replace('::', ':'))
192 192
193 193 # client side
194 194
195 195 class wirepeer(peer.peerrepository):
196 196
197 197 def batch(self):
198 198 return remotebatch(self)
199 199 def _submitbatch(self, req):
200 200 cmds = []
201 201 for op, argsdict in req:
202 202 args = ','.join('%s=%s' % p for p in argsdict.iteritems())
203 203 cmds.append('%s %s' % (op, args))
204 204 rsp = self._call("batch", cmds=';'.join(cmds))
205 205 return rsp.split(';')
206 206 def _submitone(self, op, args):
207 207 return self._call(op, **args)
208 208
209 209 @batchable
210 210 def lookup(self, key):
211 211 self.requirecap('lookup', _('look up remote revision'))
212 212 f = future()
213 213 yield {'key': encoding.fromlocal(key)}, f
214 214 d = f.value
215 215 success, data = d[:-1].split(" ", 1)
216 216 if int(success):
217 217 yield bin(data)
218 218 self._abort(error.RepoError(data))
219 219
220 220 @batchable
221 221 def heads(self):
222 222 f = future()
223 223 yield {}, f
224 224 d = f.value
225 225 try:
226 226 yield decodelist(d[:-1])
227 227 except ValueError:
228 228 self._abort(error.ResponseError(_("unexpected response:"), d))
229 229
230 230 @batchable
231 231 def known(self, nodes):
232 232 f = future()
233 233 yield {'nodes': encodelist(nodes)}, f
234 234 d = f.value
235 235 try:
236 236 yield [bool(int(f)) for f in d]
237 237 except ValueError:
238 238 self._abort(error.ResponseError(_("unexpected response:"), d))
239 239
240 240 @batchable
241 241 def branchmap(self):
242 242 f = future()
243 243 yield {}, f
244 244 d = f.value
245 245 try:
246 246 branchmap = {}
247 247 for branchpart in d.splitlines():
248 248 branchname, branchheads = branchpart.split(' ', 1)
249 249 branchname = encoding.tolocal(urllib.unquote(branchname))
250 250 branchheads = decodelist(branchheads)
251 251 branchmap[branchname] = branchheads
252 252 yield branchmap
253 253 except TypeError:
254 254 self._abort(error.ResponseError(_("unexpected response:"), d))
255 255
256 256 def branches(self, nodes):
257 257 n = encodelist(nodes)
258 258 d = self._call("branches", nodes=n)
259 259 try:
260 260 br = [tuple(decodelist(b)) for b in d.splitlines()]
261 261 return br
262 262 except ValueError:
263 263 self._abort(error.ResponseError(_("unexpected response:"), d))
264 264
265 265 def between(self, pairs):
266 266 batch = 8 # avoid giant requests
267 267 r = []
268 268 for i in xrange(0, len(pairs), batch):
269 269 n = " ".join([encodelist(p, '-') for p in pairs[i:i + batch]])
270 270 d = self._call("between", pairs=n)
271 271 try:
272 272 r.extend(l and decodelist(l) or [] for l in d.splitlines())
273 273 except ValueError:
274 274 self._abort(error.ResponseError(_("unexpected response:"), d))
275 275 return r
276 276
277 277 @batchable
278 278 def pushkey(self, namespace, key, old, new):
279 279 if not self.capable('pushkey'):
280 280 yield False, None
281 281 f = future()
282 282 self.ui.debug('preparing pushkey for "%s:%s"\n' % (namespace, key))
283 283 yield {'namespace': encoding.fromlocal(namespace),
284 284 'key': encoding.fromlocal(key),
285 285 'old': encoding.fromlocal(old),
286 286 'new': encoding.fromlocal(new)}, f
287 287 d = f.value
288 288 d, output = d.split('\n', 1)
289 289 try:
290 290 d = bool(int(d))
291 291 except ValueError:
292 292 raise error.ResponseError(
293 293 _('push failed (unexpected response):'), d)
294 294 for l in output.splitlines(True):
295 295 self.ui.status(_('remote: '), l)
296 296 yield d
297 297
298 298 @batchable
299 299 def listkeys(self, namespace):
300 300 if not self.capable('pushkey'):
301 301 yield {}, None
302 302 f = future()
303 303 self.ui.debug('preparing listkeys for "%s"\n' % namespace)
304 304 yield {'namespace': encoding.fromlocal(namespace)}, f
305 305 d = f.value
306 306 r = {}
307 307 for l in d.splitlines():
308 308 k, v = l.split('\t')
309 309 r[encoding.tolocal(k)] = encoding.tolocal(v)
310 310 yield r
311 311
312 312 def stream_out(self):
313 313 return self._callstream('stream_out')
314 314
315 315 def changegroup(self, nodes, kind):
316 316 n = encodelist(nodes)
317 317 f = self._callcompressable("changegroup", roots=n)
318 318 return changegroupmod.unbundle10(f, 'UN')
319 319
320 320 def changegroupsubset(self, bases, heads, kind):
321 321 self.requirecap('changegroupsubset', _('look up remote changes'))
322 322 bases = encodelist(bases)
323 323 heads = encodelist(heads)
324 324 f = self._callcompressable("changegroupsubset",
325 325 bases=bases, heads=heads)
326 326 return changegroupmod.unbundle10(f, 'UN')
327 327
328 328 def getbundle(self, source, heads=None, common=None, bundlecaps=None):
329 329 self.requirecap('getbundle', _('look up remote changes'))
330 330 opts = {}
331 331 if heads is not None:
332 332 opts['heads'] = encodelist(heads)
333 333 if common is not None:
334 334 opts['common'] = encodelist(common)
335 335 if bundlecaps is not None:
336 336 opts['bundlecaps'] = ','.join(bundlecaps)
337 337 f = self._callcompressable("getbundle", **opts)
338 338 return changegroupmod.unbundle10(f, 'UN')
339 339
340 340 def unbundle(self, cg, heads, source):
341 341 '''Send cg (a readable file-like object representing the
342 342 changegroup to push, typically a chunkbuffer object) to the
343 343 remote server as a bundle. Return an integer indicating the
344 344 result of the push (see localrepository.addchangegroup()).'''
345 345
346 346 if heads != ['force'] and self.capable('unbundlehash'):
347 347 heads = encodelist(['hashed',
348 348 util.sha1(''.join(sorted(heads))).digest()])
349 349 else:
350 350 heads = encodelist(heads)
351 351
352 352 ret, output = self._callpush("unbundle", cg, heads=heads)
353 353 if ret == "":
354 354 raise error.ResponseError(
355 355 _('push failed:'), output)
356 356 try:
357 357 ret = int(ret)
358 358 except ValueError:
359 359 raise error.ResponseError(
360 360 _('push failed (unexpected response):'), ret)
361 361
362 362 for l in output.splitlines(True):
363 363 self.ui.status(_('remote: '), l)
364 364 return ret
365 365
366 366 def debugwireargs(self, one, two, three=None, four=None, five=None):
367 367 # don't pass optional arguments left at their default value
368 368 opts = {}
369 369 if three is not None:
370 370 opts['three'] = three
371 371 if four is not None:
372 372 opts['four'] = four
373 373 return self._call('debugwireargs', one=one, two=two, **opts)
374 374
375 375 def _call(self, cmd, **args):
376 376 """execute <cmd> on the server
377 377
378 378 The command is expected to return a simple string.
379 379
380 380 returns the server reply as a string."""
381 381 raise NotImplementedError()
382 382
383 383 def _callstream(self, cmd, **args):
384 384 """execute <cmd> on the server
385 385
386 386 The command is expected to return a stream.
387 387
388 388 returns the server reply as a file like object."""
389 389 raise NotImplementedError()
390 390
391 391 def _callcompressable(self, cmd, **args):
392 392 """execute <cmd> on the server
393 393
394 394 The command is expected to return a stream.
395 395
396 396 The stream may have been compressed in some implementaitons. This
397 397 function takes care of the decompression. This is the only difference
398 398 with _callstream.
399 399
400 400 returns the server reply as a file like object.
401 401 """
402 402 raise NotImplementedError()
403 403
404 404 def _callpush(self, cmd, fp, **args):
405 405 """execute a <cmd> on server
406 406
407 407 The command is expected to be related to a push. Push has a special
408 408 return method.
409 409
410 410 returns the server reply as a (ret, output) tuple. ret is either
411 411 empty (error) or a stringified int.
412 412 """
413 413 raise NotImplementedError()
414 414
415 415 def _abort(self, exception):
416 416 """clearly abort the wire protocol connection and raise the exception
417 417 """
418 418 raise NotImplementedError()
419 419
420 420 # server side
421 421
422 422 # wire protocol command can either return a string or one of these classes.
423 423 class streamres(object):
424 424 """wireproto reply: binary stream
425 425
426 426 The call was successful and the result is a stream.
427 427 Iterate on the `self.gen` attribute to retrieve chunks.
428 428 """
429 429 def __init__(self, gen):
430 430 self.gen = gen
431 431
432 432 class pushres(object):
433 433 """wireproto reply: success with simple integer return
434 434
435 435 The call was successful and returned an integer contained in `self.res`.
436 436 """
437 437 def __init__(self, res):
438 438 self.res = res
439 439
440 440 class pusherr(object):
441 441 """wireproto reply: failure
442 442
443 443 The call failed. The `self.res` attribute contains the error message.
444 444 """
445 445 def __init__(self, res):
446 446 self.res = res
447 447
448 448 class ooberror(object):
449 449 """wireproto reply: failure of a batch of operation
450 450
451 451 Something failed during a batch call. The error message is stored in
452 452 `self.message`.
453 453 """
454 454 def __init__(self, message):
455 455 self.message = message
456 456
457 457 def dispatch(repo, proto, command):
458 458 repo = repo.filtered("served")
459 459 func, spec = commands[command]
460 460 args = proto.getargs(spec)
461 461 return func(repo, proto, *args)
462 462
463 463 def options(cmd, keys, others):
464 464 opts = {}
465 465 for k in keys:
466 466 if k in others:
467 467 opts[k] = others[k]
468 468 del others[k]
469 469 if others:
470 470 sys.stderr.write("abort: %s got unexpected arguments %s\n"
471 471 % (cmd, ",".join(others)))
472 472 return opts
473 473
474 474 # list of commands
475 475 commands = {}
476 476
477 477 def wireprotocommand(name, args=''):
478 478 """decorator for wireprotocol command"""
479 479 def register(func):
480 480 commands[name] = (func, args)
481 481 return func
482 482 return register
483 483
484 484 @wireprotocommand('batch', 'cmds *')
485 485 def batch(repo, proto, cmds, others):
486 486 repo = repo.filtered("served")
487 487 res = []
488 488 for pair in cmds.split(';'):
489 489 op, args = pair.split(' ', 1)
490 490 vals = {}
491 491 for a in args.split(','):
492 492 if a:
493 493 n, v = a.split('=')
494 494 vals[n] = unescapearg(v)
495 495 func, spec = commands[op]
496 496 if spec:
497 497 keys = spec.split()
498 498 data = {}
499 499 for k in keys:
500 500 if k == '*':
501 501 star = {}
502 502 for key in vals.keys():
503 503 if key not in keys:
504 504 star[key] = vals[key]
505 505 data['*'] = star
506 506 else:
507 507 data[k] = vals[k]
508 508 result = func(repo, proto, *[data[k] for k in keys])
509 509 else:
510 510 result = func(repo, proto)
511 511 if isinstance(result, ooberror):
512 512 return result
513 513 res.append(escapearg(result))
514 514 return ';'.join(res)
515 515
516 516 @wireprotocommand('between', 'pairs')
517 517 def between(repo, proto, pairs):
518 518 pairs = [decodelist(p, '-') for p in pairs.split(" ")]
519 519 r = []
520 520 for b in repo.between(pairs):
521 521 r.append(encodelist(b) + "\n")
522 522 return "".join(r)
523 523
524 524 @wireprotocommand('branchmap')
525 525 def branchmap(repo, proto):
526 526 branchmap = repo.branchmap()
527 527 heads = []
528 528 for branch, nodes in branchmap.iteritems():
529 529 branchname = urllib.quote(encoding.fromlocal(branch))
530 530 branchnodes = encodelist(nodes)
531 531 heads.append('%s %s' % (branchname, branchnodes))
532 532 return '\n'.join(heads)
533 533
534 534 @wireprotocommand('branches', 'nodes')
535 535 def branches(repo, proto, nodes):
536 536 nodes = decodelist(nodes)
537 537 r = []
538 538 for b in repo.branches(nodes):
539 539 r.append(encodelist(b) + "\n")
540 540 return "".join(r)
541 541
542 542
543 543 wireprotocaps = ['lookup', 'changegroupsubset', 'branchmap', 'pushkey',
544 544 'known', 'getbundle', 'unbundlehash', 'batch']
545 545
546 546 def _capabilities(repo, proto):
547 547 """return a list of capabilities for a repo
548 548
549 549 This function exists to allow extensions to easily wrap capabilities
550 550 computation
551 551
552 552 - returns a lists: easy to alter
553 553 - change done here will be propagated to both `capabilities` and `hello`
554 554 command without any other effort. without any other action needed.
555 555 """
556 556 # copy to prevent modification of the global list
557 557 caps = list(wireprotocaps)
558 558 if _allowstream(repo.ui):
559 559 if repo.ui.configbool('server', 'preferuncompressed', False):
560 560 caps.append('stream-preferred')
561 561 requiredformats = repo.requirements & repo.supportedformats
562 562 # if our local revlogs are just revlogv1, add 'stream' cap
563 563 if not requiredformats - set(('revlogv1',)):
564 564 caps.append('stream')
565 565 # otherwise, add 'streamreqs' detailing our local revlog format
566 566 else:
567 567 caps.append('streamreqs=%s' % ','.join(requiredformats))
568 568 caps.append('unbundle=%s' % ','.join(changegroupmod.bundlepriority))
569 569 caps.append('httpheader=1024')
570 570 return caps
571 571
572 572 # If you are writting and extension and consider wrapping this function. Wrap
573 573 # `_capabilities` instead.
574 574 @wireprotocommand('capabilities')
575 575 def capabilities(repo, proto):
576 576 return ' '.join(_capabilities(repo, proto))
577 577
578 578 @wireprotocommand('changegroup', 'roots')
579 579 def changegroup(repo, proto, roots):
580 580 nodes = decodelist(roots)
581 cg = repo.changegroup(nodes, 'serve')
581 cg = changegroupmod.changegroup(repo, nodes, 'serve')
582 582 return streamres(proto.groupchunks(cg))
583 583
584 584 @wireprotocommand('changegroupsubset', 'bases heads')
585 585 def changegroupsubset(repo, proto, bases, heads):
586 586 bases = decodelist(bases)
587 587 heads = decodelist(heads)
588 588 cg = changegroupmod.changegroupsubset(repo, bases, heads, 'serve')
589 589 return streamres(proto.groupchunks(cg))
590 590
591 591 @wireprotocommand('debugwireargs', 'one two *')
592 592 def debugwireargs(repo, proto, one, two, others):
593 593 # only accept optional args from the known set
594 594 opts = options('debugwireargs', ['three', 'four'], others)
595 595 return repo.debugwireargs(one, two, **opts)
596 596
597 597 @wireprotocommand('getbundle', '*')
598 598 def getbundle(repo, proto, others):
599 599 opts = options('getbundle', ['heads', 'common', 'bundlecaps'], others)
600 600 for k, v in opts.iteritems():
601 601 if k in ('heads', 'common'):
602 602 opts[k] = decodelist(v)
603 603 elif k == 'bundlecaps':
604 604 opts[k] = set(v.split(','))
605 605 cg = changegroupmod.getbundle(repo, 'serve', **opts)
606 606 return streamres(proto.groupchunks(cg))
607 607
608 608 @wireprotocommand('heads')
609 609 def heads(repo, proto):
610 610 h = repo.heads()
611 611 return encodelist(h) + "\n"
612 612
613 613 @wireprotocommand('hello')
614 614 def hello(repo, proto):
615 615 '''the hello command returns a set of lines describing various
616 616 interesting things about the server, in an RFC822-like format.
617 617 Currently the only one defined is "capabilities", which
618 618 consists of a line in the form:
619 619
620 620 capabilities: space separated list of tokens
621 621 '''
622 622 return "capabilities: %s\n" % (capabilities(repo, proto))
623 623
624 624 @wireprotocommand('listkeys', 'namespace')
625 625 def listkeys(repo, proto, namespace):
626 626 d = repo.listkeys(encoding.tolocal(namespace)).items()
627 627 t = '\n'.join(['%s\t%s' % (encoding.fromlocal(k), encoding.fromlocal(v))
628 628 for k, v in d])
629 629 return t
630 630
631 631 @wireprotocommand('lookup', 'key')
632 632 def lookup(repo, proto, key):
633 633 try:
634 634 k = encoding.tolocal(key)
635 635 c = repo[k]
636 636 r = c.hex()
637 637 success = 1
638 638 except Exception, inst:
639 639 r = str(inst)
640 640 success = 0
641 641 return "%s %s\n" % (success, r)
642 642
643 643 @wireprotocommand('known', 'nodes *')
644 644 def known(repo, proto, nodes, others):
645 645 return ''.join(b and "1" or "0" for b in repo.known(decodelist(nodes)))
646 646
647 647 @wireprotocommand('pushkey', 'namespace key old new')
648 648 def pushkey(repo, proto, namespace, key, old, new):
649 649 # compatibility with pre-1.8 clients which were accidentally
650 650 # sending raw binary nodes rather than utf-8-encoded hex
651 651 if len(new) == 20 and new.encode('string-escape') != new:
652 652 # looks like it could be a binary node
653 653 try:
654 654 new.decode('utf-8')
655 655 new = encoding.tolocal(new) # but cleanly decodes as UTF-8
656 656 except UnicodeDecodeError:
657 657 pass # binary, leave unmodified
658 658 else:
659 659 new = encoding.tolocal(new) # normal path
660 660
661 661 if util.safehasattr(proto, 'restore'):
662 662
663 663 proto.redirect()
664 664
665 665 try:
666 666 r = repo.pushkey(encoding.tolocal(namespace), encoding.tolocal(key),
667 667 encoding.tolocal(old), new) or False
668 668 except util.Abort:
669 669 r = False
670 670
671 671 output = proto.restore()
672 672
673 673 return '%s\n%s' % (int(r), output)
674 674
675 675 r = repo.pushkey(encoding.tolocal(namespace), encoding.tolocal(key),
676 676 encoding.tolocal(old), new)
677 677 return '%s\n' % int(r)
678 678
679 679 def _allowstream(ui):
680 680 return ui.configbool('server', 'uncompressed', True, untrusted=True)
681 681
682 682 def _walkstreamfiles(repo):
683 683 # this is it's own function so extensions can override it
684 684 return repo.store.walk()
685 685
686 686 @wireprotocommand('stream_out')
687 687 def stream(repo, proto):
688 688 '''If the server supports streaming clone, it advertises the "stream"
689 689 capability with a value representing the version and flags of the repo
690 690 it is serving. Client checks to see if it understands the format.
691 691
692 692 The format is simple: the server writes out a line with the amount
693 693 of files, then the total amount of bytes to be transferred (separated
694 694 by a space). Then, for each file, the server first writes the filename
695 695 and filesize (separated by the null character), then the file contents.
696 696 '''
697 697
698 698 if not _allowstream(repo.ui):
699 699 return '1\n'
700 700
701 701 entries = []
702 702 total_bytes = 0
703 703 try:
704 704 # get consistent snapshot of repo, lock during scan
705 705 lock = repo.lock()
706 706 try:
707 707 repo.ui.debug('scanning\n')
708 708 for name, ename, size in _walkstreamfiles(repo):
709 709 if size:
710 710 entries.append((name, size))
711 711 total_bytes += size
712 712 finally:
713 713 lock.release()
714 714 except error.LockError:
715 715 return '2\n' # error: 2
716 716
717 717 def streamer(repo, entries, total):
718 718 '''stream out all metadata files in repository.'''
719 719 yield '0\n' # success
720 720 repo.ui.debug('%d files, %d bytes to transfer\n' %
721 721 (len(entries), total_bytes))
722 722 yield '%d %d\n' % (len(entries), total_bytes)
723 723
724 724 sopener = repo.sopener
725 725 oldaudit = sopener.mustaudit
726 726 debugflag = repo.ui.debugflag
727 727 sopener.mustaudit = False
728 728
729 729 try:
730 730 for name, size in entries:
731 731 if debugflag:
732 732 repo.ui.debug('sending %s (%d bytes)\n' % (name, size))
733 733 # partially encode name over the wire for backwards compat
734 734 yield '%s\0%d\n' % (store.encodedir(name), size)
735 735 if size <= 65536:
736 736 fp = sopener(name)
737 737 try:
738 738 data = fp.read(size)
739 739 finally:
740 740 fp.close()
741 741 yield data
742 742 else:
743 743 for chunk in util.filechunkiter(sopener(name), limit=size):
744 744 yield chunk
745 745 # replace with "finally:" when support for python 2.4 has been dropped
746 746 except Exception:
747 747 sopener.mustaudit = oldaudit
748 748 raise
749 749 sopener.mustaudit = oldaudit
750 750
751 751 return streamres(streamer(repo, entries, total_bytes))
752 752
753 753 @wireprotocommand('unbundle', 'heads')
754 754 def unbundle(repo, proto, heads):
755 755 their_heads = decodelist(heads)
756 756
757 757 def check_heads():
758 758 heads = repo.heads()
759 759 heads_hash = util.sha1(''.join(sorted(heads))).digest()
760 760 return (their_heads == ['force'] or their_heads == heads or
761 761 their_heads == ['hashed', heads_hash])
762 762
763 763 proto.redirect()
764 764
765 765 # fail early if possible
766 766 if not check_heads():
767 767 return pusherr('repository changed while preparing changes - '
768 768 'please try again')
769 769
770 770 # write bundle data to temporary file because it can be big
771 771 fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
772 772 fp = os.fdopen(fd, 'wb+')
773 773 r = 0
774 774 try:
775 775 proto.getfile(fp)
776 776 lock = repo.lock()
777 777 try:
778 778 if not check_heads():
779 779 # someone else committed/pushed/unbundled while we
780 780 # were transferring data
781 781 return pusherr('repository changed while uploading changes - '
782 782 'please try again')
783 783
784 784 # push can proceed
785 785 fp.seek(0)
786 786 gen = changegroupmod.readbundle(fp, None)
787 787
788 788 try:
789 789 r = repo.addchangegroup(gen, 'serve', proto._client())
790 790 except util.Abort, inst:
791 791 sys.stderr.write("abort: %s\n" % inst)
792 792 finally:
793 793 lock.release()
794 794 return pushres(r)
795 795
796 796 finally:
797 797 fp.close()
798 798 os.unlink(tempname)
General Comments 0
You need to be logged in to leave comments. Login now