##// END OF EJS Templates
narrow: move .hg/narrowspec to .hg/store/narrowspec (BC)...
Martin von Zweigbergk -
r38908:576eef1a default
parent child Browse files
Show More
@@ -1,93 +1,90 b''
1 1 # __init__.py - narrowhg extension
2 2 #
3 3 # Copyright 2017 Google, Inc.
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 '''create clones which fetch history data for subset of files (EXPERIMENTAL)'''
8 8
9 9 from __future__ import absolute_import
10 10
11 11 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
12 12 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
13 13 # be specifying the version(s) of Mercurial they are tested with, or
14 14 # leave the attribute unspecified.
15 15 testedwith = 'ships-with-hg-core'
16 16
17 17 from mercurial import (
18 18 extensions,
19 hg,
20 19 localrepo,
21 20 registrar,
22 21 repository,
23 22 verify as verifymod,
24 23 )
25 24
26 25 from . import (
27 26 narrowbundle2,
28 27 narrowchangegroup,
29 28 narrowcommands,
30 29 narrowcopies,
31 30 narrowpatch,
32 31 narrowrepo,
33 32 narrowrevlog,
34 33 narrowtemplates,
35 34 narrowwirepeer,
36 35 )
37 36
38 37 configtable = {}
39 38 configitem = registrar.configitem(configtable)
40 39 # Narrowhg *has* support for serving ellipsis nodes (which are used at
41 40 # least by Google's internal server), but that support is pretty
42 41 # fragile and has a lot of problems on real-world repositories that
43 42 # have complex graph topologies. This could probably be corrected, but
44 43 # absent someone needing the full support for ellipsis nodes in
45 44 # repositories with merges, it's unlikely this work will get done. As
46 45 # of this writining in late 2017, all repositories large enough for
47 46 # ellipsis nodes to be a hard requirement also enforce strictly linear
48 47 # history for other scaling reasons.
49 48 configitem('experimental', 'narrowservebrokenellipses',
50 49 default=False,
51 50 alias=[('narrow', 'serveellipses')],
52 51 )
53 52
54 53 # Export the commands table for Mercurial to see.
55 54 cmdtable = narrowcommands.table
56 55
57 56 def featuresetup(ui, features):
58 57 features.add(repository.NARROW_REQUIREMENT)
59 58
60 59 def uisetup(ui):
61 60 """Wraps user-facing mercurial commands with narrow-aware versions."""
62 61 localrepo.featuresetupfuncs.add(featuresetup)
63 62 narrowrevlog.setup()
64 63 narrowbundle2.setup()
65 64 narrowcommands.setup()
66 65 narrowchangegroup.setup()
67 66 narrowwirepeer.uisetup()
68 67
69 68 def reposetup(ui, repo):
70 69 """Wraps local repositories with narrow repo support."""
71 70 if not repo.local():
72 71 return
73 72
74 73 if repository.NARROW_REQUIREMENT in repo.requirements:
75 74 narrowrepo.wraprepo(repo)
76 75 narrowcopies.setup(repo)
77 76 narrowpatch.setup(repo)
78 77 narrowwirepeer.reposetup(repo)
79 78
80 79 def _verifierinit(orig, self, repo, matcher=None):
81 80 # The verifier's matcher argument was desgined for narrowhg, so it should
82 81 # be None from core. If another extension passes a matcher (unlikely),
83 82 # we'll have to fail until matchers can be composed more easily.
84 83 assert matcher is None
85 84 orig(self, repo, repo.narrowmatch())
86 85
87 86 def extsetup(ui):
88 87 extensions.wrapfunction(verifymod.verifier, '__init__', _verifierinit)
89 extensions.wrapfunction(hg, 'postshare', narrowrepo.wrappostshare)
90 extensions.wrapfunction(hg, 'copystore', narrowrepo.unsharenarrowspec)
91 88
92 89 templatekeyword = narrowtemplates.templatekeyword
93 90 revsetpredicate = narrowtemplates.revsetpredicate
@@ -1,52 +1,29 b''
1 1 # narrowrepo.py - repository which supports narrow revlogs, lazy loading
2 2 #
3 3 # Copyright 2017 Google, Inc.
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 __future__ import absolute_import
9 9
10 from mercurial import (
11 hg,
12 narrowspec,
13 repository,
14 )
15
16 10 from . import (
17 11 narrowdirstate,
18 12 narrowrevlog,
19 13 )
20 14
21 def wrappostshare(orig, sourcerepo, destrepo, **kwargs):
22 orig(sourcerepo, destrepo, **kwargs)
23 if repository.NARROW_REQUIREMENT in sourcerepo.requirements:
24 with destrepo.wlock():
25 with destrepo.vfs('shared', 'a') as fp:
26 fp.write(narrowspec.FILENAME + '\n')
27
28 def unsharenarrowspec(orig, ui, repo, repopath):
29 if (repository.NARROW_REQUIREMENT in repo.requirements
30 and repo.path == repopath and repo.shared()):
31 srcrepo = hg.sharedreposource(repo)
32 with srcrepo.vfs(narrowspec.FILENAME) as f:
33 spec = f.read()
34 with repo.vfs(narrowspec.FILENAME, 'w') as f:
35 f.write(spec)
36 return orig(ui, repo, repopath)
37
38 15 def wraprepo(repo):
39 16 """Enables narrow clone functionality on a single local repository."""
40 17
41 18 class narrowrepository(repo.__class__):
42 19
43 20 def file(self, f):
44 21 fl = super(narrowrepository, self).file(f)
45 22 narrowrevlog.makenarrowfilelog(fl, self.narrowmatch())
46 23 return fl
47 24
48 25 def _makedirstate(self):
49 26 dirstate = super(narrowrepository, self)._makedirstate()
50 27 return narrowdirstate.wrapdirstate(self, dirstate)
51 28
52 29 repo.__class__ = narrowrepository
@@ -1,2405 +1,2405 b''
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
8 8 from __future__ import absolute_import
9 9
10 10 import errno
11 11 import hashlib
12 12 import os
13 13 import random
14 14 import sys
15 15 import time
16 16 import weakref
17 17
18 18 from .i18n import _
19 19 from .node import (
20 20 hex,
21 21 nullid,
22 22 short,
23 23 )
24 24 from . import (
25 25 bookmarks,
26 26 branchmap,
27 27 bundle2,
28 28 changegroup,
29 29 changelog,
30 30 color,
31 31 context,
32 32 dirstate,
33 33 dirstateguard,
34 34 discovery,
35 35 encoding,
36 36 error,
37 37 exchange,
38 38 extensions,
39 39 filelog,
40 40 hook,
41 41 lock as lockmod,
42 42 manifest,
43 43 match as matchmod,
44 44 merge as mergemod,
45 45 mergeutil,
46 46 namespaces,
47 47 narrowspec,
48 48 obsolete,
49 49 pathutil,
50 50 phases,
51 51 pushkey,
52 52 pycompat,
53 53 repository,
54 54 repoview,
55 55 revset,
56 56 revsetlang,
57 57 scmutil,
58 58 sparse,
59 59 store,
60 60 subrepoutil,
61 61 tags as tagsmod,
62 62 transaction,
63 63 txnutil,
64 64 util,
65 65 vfs as vfsmod,
66 66 )
67 67 from .utils import (
68 68 interfaceutil,
69 69 procutil,
70 70 stringutil,
71 71 )
72 72
73 73 release = lockmod.release
74 74 urlerr = util.urlerr
75 75 urlreq = util.urlreq
76 76
77 77 # set of (path, vfs-location) tuples. vfs-location is:
78 78 # - 'plain for vfs relative paths
79 79 # - '' for svfs relative paths
80 80 _cachedfiles = set()
81 81
82 82 class _basefilecache(scmutil.filecache):
83 83 """All filecache usage on repo are done for logic that should be unfiltered
84 84 """
85 85 def __get__(self, repo, type=None):
86 86 if repo is None:
87 87 return self
88 88 return super(_basefilecache, self).__get__(repo.unfiltered(), type)
89 89 def __set__(self, repo, value):
90 90 return super(_basefilecache, self).__set__(repo.unfiltered(), value)
91 91 def __delete__(self, repo):
92 92 return super(_basefilecache, self).__delete__(repo.unfiltered())
93 93
94 94 class repofilecache(_basefilecache):
95 95 """filecache for files in .hg but outside of .hg/store"""
96 96 def __init__(self, *paths):
97 97 super(repofilecache, self).__init__(*paths)
98 98 for path in paths:
99 99 _cachedfiles.add((path, 'plain'))
100 100
101 101 def join(self, obj, fname):
102 102 return obj.vfs.join(fname)
103 103
104 104 class storecache(_basefilecache):
105 105 """filecache for files in the store"""
106 106 def __init__(self, *paths):
107 107 super(storecache, self).__init__(*paths)
108 108 for path in paths:
109 109 _cachedfiles.add((path, ''))
110 110
111 111 def join(self, obj, fname):
112 112 return obj.sjoin(fname)
113 113
114 114 def isfilecached(repo, name):
115 115 """check if a repo has already cached "name" filecache-ed property
116 116
117 117 This returns (cachedobj-or-None, iscached) tuple.
118 118 """
119 119 cacheentry = repo.unfiltered()._filecache.get(name, None)
120 120 if not cacheentry:
121 121 return None, False
122 122 return cacheentry.obj, True
123 123
124 124 class unfilteredpropertycache(util.propertycache):
125 125 """propertycache that apply to unfiltered repo only"""
126 126
127 127 def __get__(self, repo, type=None):
128 128 unfi = repo.unfiltered()
129 129 if unfi is repo:
130 130 return super(unfilteredpropertycache, self).__get__(unfi)
131 131 return getattr(unfi, self.name)
132 132
133 133 class filteredpropertycache(util.propertycache):
134 134 """propertycache that must take filtering in account"""
135 135
136 136 def cachevalue(self, obj, value):
137 137 object.__setattr__(obj, self.name, value)
138 138
139 139
140 140 def hasunfilteredcache(repo, name):
141 141 """check if a repo has an unfilteredpropertycache value for <name>"""
142 142 return name in vars(repo.unfiltered())
143 143
144 144 def unfilteredmethod(orig):
145 145 """decorate method that always need to be run on unfiltered version"""
146 146 def wrapper(repo, *args, **kwargs):
147 147 return orig(repo.unfiltered(), *args, **kwargs)
148 148 return wrapper
149 149
150 150 moderncaps = {'lookup', 'branchmap', 'pushkey', 'known', 'getbundle',
151 151 'unbundle'}
152 152 legacycaps = moderncaps.union({'changegroupsubset'})
153 153
154 154 @interfaceutil.implementer(repository.ipeercommandexecutor)
155 155 class localcommandexecutor(object):
156 156 def __init__(self, peer):
157 157 self._peer = peer
158 158 self._sent = False
159 159 self._closed = False
160 160
161 161 def __enter__(self):
162 162 return self
163 163
164 164 def __exit__(self, exctype, excvalue, exctb):
165 165 self.close()
166 166
167 167 def callcommand(self, command, args):
168 168 if self._sent:
169 169 raise error.ProgrammingError('callcommand() cannot be used after '
170 170 'sendcommands()')
171 171
172 172 if self._closed:
173 173 raise error.ProgrammingError('callcommand() cannot be used after '
174 174 'close()')
175 175
176 176 # We don't need to support anything fancy. Just call the named
177 177 # method on the peer and return a resolved future.
178 178 fn = getattr(self._peer, pycompat.sysstr(command))
179 179
180 180 f = pycompat.futures.Future()
181 181
182 182 try:
183 183 result = fn(**pycompat.strkwargs(args))
184 184 except Exception:
185 185 pycompat.future_set_exception_info(f, sys.exc_info()[1:])
186 186 else:
187 187 f.set_result(result)
188 188
189 189 return f
190 190
191 191 def sendcommands(self):
192 192 self._sent = True
193 193
194 194 def close(self):
195 195 self._closed = True
196 196
197 197 @interfaceutil.implementer(repository.ipeercommands)
198 198 class localpeer(repository.peer):
199 199 '''peer for a local repo; reflects only the most recent API'''
200 200
201 201 def __init__(self, repo, caps=None):
202 202 super(localpeer, self).__init__()
203 203
204 204 if caps is None:
205 205 caps = moderncaps.copy()
206 206 self._repo = repo.filtered('served')
207 207 self.ui = repo.ui
208 208 self._caps = repo._restrictcapabilities(caps)
209 209
210 210 # Begin of _basepeer interface.
211 211
212 212 def url(self):
213 213 return self._repo.url()
214 214
215 215 def local(self):
216 216 return self._repo
217 217
218 218 def peer(self):
219 219 return self
220 220
221 221 def canpush(self):
222 222 return True
223 223
224 224 def close(self):
225 225 self._repo.close()
226 226
227 227 # End of _basepeer interface.
228 228
229 229 # Begin of _basewirecommands interface.
230 230
231 231 def branchmap(self):
232 232 return self._repo.branchmap()
233 233
234 234 def capabilities(self):
235 235 return self._caps
236 236
237 237 def clonebundles(self):
238 238 return self._repo.tryread('clonebundles.manifest')
239 239
240 240 def debugwireargs(self, one, two, three=None, four=None, five=None):
241 241 """Used to test argument passing over the wire"""
242 242 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
243 243 pycompat.bytestr(four),
244 244 pycompat.bytestr(five))
245 245
246 246 def getbundle(self, source, heads=None, common=None, bundlecaps=None,
247 247 **kwargs):
248 248 chunks = exchange.getbundlechunks(self._repo, source, heads=heads,
249 249 common=common, bundlecaps=bundlecaps,
250 250 **kwargs)[1]
251 251 cb = util.chunkbuffer(chunks)
252 252
253 253 if exchange.bundle2requested(bundlecaps):
254 254 # When requesting a bundle2, getbundle returns a stream to make the
255 255 # wire level function happier. We need to build a proper object
256 256 # from it in local peer.
257 257 return bundle2.getunbundler(self.ui, cb)
258 258 else:
259 259 return changegroup.getunbundler('01', cb, None)
260 260
261 261 def heads(self):
262 262 return self._repo.heads()
263 263
264 264 def known(self, nodes):
265 265 return self._repo.known(nodes)
266 266
267 267 def listkeys(self, namespace):
268 268 return self._repo.listkeys(namespace)
269 269
270 270 def lookup(self, key):
271 271 return self._repo.lookup(key)
272 272
273 273 def pushkey(self, namespace, key, old, new):
274 274 return self._repo.pushkey(namespace, key, old, new)
275 275
276 276 def stream_out(self):
277 277 raise error.Abort(_('cannot perform stream clone against local '
278 278 'peer'))
279 279
280 280 def unbundle(self, bundle, heads, url):
281 281 """apply a bundle on a repo
282 282
283 283 This function handles the repo locking itself."""
284 284 try:
285 285 try:
286 286 bundle = exchange.readbundle(self.ui, bundle, None)
287 287 ret = exchange.unbundle(self._repo, bundle, heads, 'push', url)
288 288 if util.safehasattr(ret, 'getchunks'):
289 289 # This is a bundle20 object, turn it into an unbundler.
290 290 # This little dance should be dropped eventually when the
291 291 # API is finally improved.
292 292 stream = util.chunkbuffer(ret.getchunks())
293 293 ret = bundle2.getunbundler(self.ui, stream)
294 294 return ret
295 295 except Exception as exc:
296 296 # If the exception contains output salvaged from a bundle2
297 297 # reply, we need to make sure it is printed before continuing
298 298 # to fail. So we build a bundle2 with such output and consume
299 299 # it directly.
300 300 #
301 301 # This is not very elegant but allows a "simple" solution for
302 302 # issue4594
303 303 output = getattr(exc, '_bundle2salvagedoutput', ())
304 304 if output:
305 305 bundler = bundle2.bundle20(self._repo.ui)
306 306 for out in output:
307 307 bundler.addpart(out)
308 308 stream = util.chunkbuffer(bundler.getchunks())
309 309 b = bundle2.getunbundler(self.ui, stream)
310 310 bundle2.processbundle(self._repo, b)
311 311 raise
312 312 except error.PushRaced as exc:
313 313 raise error.ResponseError(_('push failed:'),
314 314 stringutil.forcebytestr(exc))
315 315
316 316 # End of _basewirecommands interface.
317 317
318 318 # Begin of peer interface.
319 319
320 320 def commandexecutor(self):
321 321 return localcommandexecutor(self)
322 322
323 323 # End of peer interface.
324 324
325 325 @interfaceutil.implementer(repository.ipeerlegacycommands)
326 326 class locallegacypeer(localpeer):
327 327 '''peer extension which implements legacy methods too; used for tests with
328 328 restricted capabilities'''
329 329
330 330 def __init__(self, repo):
331 331 super(locallegacypeer, self).__init__(repo, caps=legacycaps)
332 332
333 333 # Begin of baselegacywirecommands interface.
334 334
335 335 def between(self, pairs):
336 336 return self._repo.between(pairs)
337 337
338 338 def branches(self, nodes):
339 339 return self._repo.branches(nodes)
340 340
341 341 def changegroup(self, nodes, source):
342 342 outgoing = discovery.outgoing(self._repo, missingroots=nodes,
343 343 missingheads=self._repo.heads())
344 344 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
345 345
346 346 def changegroupsubset(self, bases, heads, source):
347 347 outgoing = discovery.outgoing(self._repo, missingroots=bases,
348 348 missingheads=heads)
349 349 return changegroup.makechangegroup(self._repo, outgoing, '01', source)
350 350
351 351 # End of baselegacywirecommands interface.
352 352
353 353 # Increment the sub-version when the revlog v2 format changes to lock out old
354 354 # clients.
355 355 REVLOGV2_REQUIREMENT = 'exp-revlogv2.0'
356 356
357 357 # A repository with the sparserevlog feature will have delta chains that
358 358 # can spread over a larger span. Sparse reading cuts these large spans into
359 359 # pieces, so that each piece isn't too big.
360 360 # Without the sparserevlog capability, reading from the repository could use
361 361 # huge amounts of memory, because the whole span would be read at once,
362 362 # including all the intermediate revisions that aren't pertinent for the chain.
363 363 # This is why once a repository has enabled sparse-read, it becomes required.
364 364 SPARSEREVLOG_REQUIREMENT = 'sparserevlog'
365 365
366 366 # Functions receiving (ui, features) that extensions can register to impact
367 367 # the ability to load repositories with custom requirements. Only
368 368 # functions defined in loaded extensions are called.
369 369 #
370 370 # The function receives a set of requirement strings that the repository
371 371 # is capable of opening. Functions will typically add elements to the
372 372 # set to reflect that the extension knows how to handle that requirements.
373 373 featuresetupfuncs = set()
374 374
375 375 @interfaceutil.implementer(repository.completelocalrepository)
376 376 class localrepository(object):
377 377
378 378 # obsolete experimental requirements:
379 379 # - manifestv2: An experimental new manifest format that allowed
380 380 # for stem compression of long paths. Experiment ended up not
381 381 # being successful (repository sizes went up due to worse delta
382 382 # chains), and the code was deleted in 4.6.
383 383 supportedformats = {
384 384 'revlogv1',
385 385 'generaldelta',
386 386 'treemanifest',
387 387 REVLOGV2_REQUIREMENT,
388 388 SPARSEREVLOG_REQUIREMENT,
389 389 }
390 390 _basesupported = supportedformats | {
391 391 'store',
392 392 'fncache',
393 393 'shared',
394 394 'relshared',
395 395 'dotencode',
396 396 'exp-sparse',
397 397 }
398 398 openerreqs = {
399 399 'revlogv1',
400 400 'generaldelta',
401 401 'treemanifest',
402 402 }
403 403
404 404 # list of prefix for file which can be written without 'wlock'
405 405 # Extensions should extend this list when needed
406 406 _wlockfreeprefix = {
407 407 # We migh consider requiring 'wlock' for the next
408 408 # two, but pretty much all the existing code assume
409 409 # wlock is not needed so we keep them excluded for
410 410 # now.
411 411 'hgrc',
412 412 'requires',
413 413 # XXX cache is a complicatged business someone
414 414 # should investigate this in depth at some point
415 415 'cache/',
416 416 # XXX shouldn't be dirstate covered by the wlock?
417 417 'dirstate',
418 418 # XXX bisect was still a bit too messy at the time
419 419 # this changeset was introduced. Someone should fix
420 420 # the remainig bit and drop this line
421 421 'bisect.state',
422 422 }
423 423
424 424 def __init__(self, baseui, path, create=False, intents=None):
425 425 self.requirements = set()
426 426 self.filtername = None
427 427 # wvfs: rooted at the repository root, used to access the working copy
428 428 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
429 429 # vfs: rooted at .hg, used to access repo files outside of .hg/store
430 430 self.vfs = None
431 431 # svfs: usually rooted at .hg/store, used to access repository history
432 432 # If this is a shared repository, this vfs may point to another
433 433 # repository's .hg/store directory.
434 434 self.svfs = None
435 435 self.root = self.wvfs.base
436 436 self.path = self.wvfs.join(".hg")
437 437 self.origroot = path
438 438 # This is only used by context.workingctx.match in order to
439 439 # detect files in subrepos.
440 440 self.auditor = pathutil.pathauditor(
441 441 self.root, callback=self._checknested)
442 442 # This is only used by context.basectx.match in order to detect
443 443 # files in subrepos.
444 444 self.nofsauditor = pathutil.pathauditor(
445 445 self.root, callback=self._checknested, realfs=False, cached=True)
446 446 self.baseui = baseui
447 447 self.ui = baseui.copy()
448 448 self.ui.copy = baseui.copy # prevent copying repo configuration
449 449 self.vfs = vfsmod.vfs(self.path, cacheaudited=True)
450 450 if (self.ui.configbool('devel', 'all-warnings') or
451 451 self.ui.configbool('devel', 'check-locks')):
452 452 self.vfs.audit = self._getvfsward(self.vfs.audit)
453 453 # A list of callback to shape the phase if no data were found.
454 454 # Callback are in the form: func(repo, roots) --> processed root.
455 455 # This list it to be filled by extension during repo setup
456 456 self._phasedefaults = []
457 457 try:
458 458 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
459 459 self._loadextensions()
460 460 except IOError:
461 461 pass
462 462
463 463 if featuresetupfuncs:
464 464 self.supported = set(self._basesupported) # use private copy
465 465 extmods = set(m.__name__ for n, m
466 466 in extensions.extensions(self.ui))
467 467 for setupfunc in featuresetupfuncs:
468 468 if setupfunc.__module__ in extmods:
469 469 setupfunc(self.ui, self.supported)
470 470 else:
471 471 self.supported = self._basesupported
472 472 color.setup(self.ui)
473 473
474 474 # Add compression engines.
475 475 for name in util.compengines:
476 476 engine = util.compengines[name]
477 477 if engine.revlogheader():
478 478 self.supported.add('exp-compression-%s' % name)
479 479
480 480 if not self.vfs.isdir():
481 481 if create:
482 482 self.requirements = newreporequirements(self)
483 483
484 484 if not self.wvfs.exists():
485 485 self.wvfs.makedirs()
486 486 self.vfs.makedir(notindexed=True)
487 487
488 488 if 'store' in self.requirements:
489 489 self.vfs.mkdir("store")
490 490
491 491 # create an invalid changelog
492 492 self.vfs.append(
493 493 "00changelog.i",
494 494 '\0\0\0\2' # represents revlogv2
495 495 ' dummy changelog to prevent using the old repo layout'
496 496 )
497 497 else:
498 498 raise error.RepoError(_("repository %s not found") % path)
499 499 elif create:
500 500 raise error.RepoError(_("repository %s already exists") % path)
501 501 else:
502 502 try:
503 503 self.requirements = scmutil.readrequires(
504 504 self.vfs, self.supported)
505 505 except IOError as inst:
506 506 if inst.errno != errno.ENOENT:
507 507 raise
508 508
509 509 cachepath = self.vfs.join('cache')
510 510 self.sharedpath = self.path
511 511 try:
512 512 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
513 513 if 'relshared' in self.requirements:
514 514 sharedpath = self.vfs.join(sharedpath)
515 515 vfs = vfsmod.vfs(sharedpath, realpath=True)
516 516 cachepath = vfs.join('cache')
517 517 s = vfs.base
518 518 if not vfs.exists():
519 519 raise error.RepoError(
520 520 _('.hg/sharedpath points to nonexistent directory %s') % s)
521 521 self.sharedpath = s
522 522 except IOError as inst:
523 523 if inst.errno != errno.ENOENT:
524 524 raise
525 525
526 526 if 'exp-sparse' in self.requirements and not sparse.enabled:
527 527 raise error.RepoError(_('repository is using sparse feature but '
528 528 'sparse is not enabled; enable the '
529 529 '"sparse" extensions to access'))
530 530
531 531 self.store = store.store(
532 532 self.requirements, self.sharedpath,
533 533 lambda base: vfsmod.vfs(base, cacheaudited=True))
534 534 self.spath = self.store.path
535 535 self.svfs = self.store.vfs
536 536 self.sjoin = self.store.join
537 537 self.vfs.createmode = self.store.createmode
538 538 self.cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
539 539 self.cachevfs.createmode = self.store.createmode
540 540 if (self.ui.configbool('devel', 'all-warnings') or
541 541 self.ui.configbool('devel', 'check-locks')):
542 542 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
543 543 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
544 544 else: # standard vfs
545 545 self.svfs.audit = self._getsvfsward(self.svfs.audit)
546 546 self._applyopenerreqs()
547 547 if create:
548 548 self._writerequirements()
549 549
550 550 self._dirstatevalidatewarned = False
551 551
552 552 self._branchcaches = {}
553 553 self._revbranchcache = None
554 554 self._filterpats = {}
555 555 self._datafilters = {}
556 556 self._transref = self._lockref = self._wlockref = None
557 557
558 558 # A cache for various files under .hg/ that tracks file changes,
559 559 # (used by the filecache decorator)
560 560 #
561 561 # Maps a property name to its util.filecacheentry
562 562 self._filecache = {}
563 563
564 564 # hold sets of revision to be filtered
565 565 # should be cleared when something might have changed the filter value:
566 566 # - new changesets,
567 567 # - phase change,
568 568 # - new obsolescence marker,
569 569 # - working directory parent change,
570 570 # - bookmark changes
571 571 self.filteredrevcache = {}
572 572
573 573 # post-dirstate-status hooks
574 574 self._postdsstatus = []
575 575
576 576 # generic mapping between names and nodes
577 577 self.names = namespaces.namespaces()
578 578
579 579 # Key to signature value.
580 580 self._sparsesignaturecache = {}
581 581 # Signature to cached matcher instance.
582 582 self._sparsematchercache = {}
583 583
584 584 def _getvfsward(self, origfunc):
585 585 """build a ward for self.vfs"""
586 586 rref = weakref.ref(self)
587 587 def checkvfs(path, mode=None):
588 588 ret = origfunc(path, mode=mode)
589 589 repo = rref()
590 590 if (repo is None
591 591 or not util.safehasattr(repo, '_wlockref')
592 592 or not util.safehasattr(repo, '_lockref')):
593 593 return
594 594 if mode in (None, 'r', 'rb'):
595 595 return
596 596 if path.startswith(repo.path):
597 597 # truncate name relative to the repository (.hg)
598 598 path = path[len(repo.path) + 1:]
599 599 if path.startswith('cache/'):
600 600 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
601 601 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
602 602 if path.startswith('journal.'):
603 603 # journal is covered by 'lock'
604 604 if repo._currentlock(repo._lockref) is None:
605 605 repo.ui.develwarn('write with no lock: "%s"' % path,
606 606 stacklevel=2, config='check-locks')
607 607 elif repo._currentlock(repo._wlockref) is None:
608 608 # rest of vfs files are covered by 'wlock'
609 609 #
610 610 # exclude special files
611 611 for prefix in self._wlockfreeprefix:
612 612 if path.startswith(prefix):
613 613 return
614 614 repo.ui.develwarn('write with no wlock: "%s"' % path,
615 615 stacklevel=2, config='check-locks')
616 616 return ret
617 617 return checkvfs
618 618
619 619 def _getsvfsward(self, origfunc):
620 620 """build a ward for self.svfs"""
621 621 rref = weakref.ref(self)
622 622 def checksvfs(path, mode=None):
623 623 ret = origfunc(path, mode=mode)
624 624 repo = rref()
625 625 if repo is None or not util.safehasattr(repo, '_lockref'):
626 626 return
627 627 if mode in (None, 'r', 'rb'):
628 628 return
629 629 if path.startswith(repo.sharedpath):
630 630 # truncate name relative to the repository (.hg)
631 631 path = path[len(repo.sharedpath) + 1:]
632 632 if repo._currentlock(repo._lockref) is None:
633 633 repo.ui.develwarn('write with no lock: "%s"' % path,
634 634 stacklevel=3)
635 635 return ret
636 636 return checksvfs
637 637
638 638 def close(self):
639 639 self._writecaches()
640 640
641 641 def _loadextensions(self):
642 642 extensions.loadall(self.ui)
643 643
644 644 def _writecaches(self):
645 645 if self._revbranchcache:
646 646 self._revbranchcache.write()
647 647
648 648 def _restrictcapabilities(self, caps):
649 649 if self.ui.configbool('experimental', 'bundle2-advertise'):
650 650 caps = set(caps)
651 651 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self,
652 652 role='client'))
653 653 caps.add('bundle2=' + urlreq.quote(capsblob))
654 654 return caps
655 655
656 656 def _applyopenerreqs(self):
657 657 self.svfs.options = dict((r, 1) for r in self.requirements
658 658 if r in self.openerreqs)
659 659 # experimental config: format.chunkcachesize
660 660 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
661 661 if chunkcachesize is not None:
662 662 self.svfs.options['chunkcachesize'] = chunkcachesize
663 663 # experimental config: format.maxchainlen
664 664 maxchainlen = self.ui.configint('format', 'maxchainlen')
665 665 if maxchainlen is not None:
666 666 self.svfs.options['maxchainlen'] = maxchainlen
667 667 # experimental config: format.manifestcachesize
668 668 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
669 669 if manifestcachesize is not None:
670 670 self.svfs.options['manifestcachesize'] = manifestcachesize
671 671 deltabothparents = self.ui.configbool('storage',
672 672 'revlog.optimize-delta-parent-choice')
673 673 self.svfs.options['deltabothparents'] = deltabothparents
674 674 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
675 675 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan')
676 676 if 0 <= chainspan:
677 677 self.svfs.options['maxdeltachainspan'] = chainspan
678 678 mmapindexthreshold = self.ui.configbytes('experimental',
679 679 'mmapindexthreshold')
680 680 if mmapindexthreshold is not None:
681 681 self.svfs.options['mmapindexthreshold'] = mmapindexthreshold
682 682 withsparseread = self.ui.configbool('experimental', 'sparse-read')
683 683 srdensitythres = float(self.ui.config('experimental',
684 684 'sparse-read.density-threshold'))
685 685 srmingapsize = self.ui.configbytes('experimental',
686 686 'sparse-read.min-gap-size')
687 687 self.svfs.options['with-sparse-read'] = withsparseread
688 688 self.svfs.options['sparse-read-density-threshold'] = srdensitythres
689 689 self.svfs.options['sparse-read-min-gap-size'] = srmingapsize
690 690 sparserevlog = SPARSEREVLOG_REQUIREMENT in self.requirements
691 691 self.svfs.options['sparse-revlog'] = sparserevlog
692 692 if sparserevlog:
693 693 self.svfs.options['generaldelta'] = True
694 694
695 695 for r in self.requirements:
696 696 if r.startswith('exp-compression-'):
697 697 self.svfs.options['compengine'] = r[len('exp-compression-'):]
698 698
699 699 # TODO move "revlogv2" to openerreqs once finalized.
700 700 if REVLOGV2_REQUIREMENT in self.requirements:
701 701 self.svfs.options['revlogv2'] = True
702 702
703 703 def _writerequirements(self):
704 704 scmutil.writerequires(self.vfs, self.requirements)
705 705
706 706 def _checknested(self, path):
707 707 """Determine if path is a legal nested repository."""
708 708 if not path.startswith(self.root):
709 709 return False
710 710 subpath = path[len(self.root) + 1:]
711 711 normsubpath = util.pconvert(subpath)
712 712
713 713 # XXX: Checking against the current working copy is wrong in
714 714 # the sense that it can reject things like
715 715 #
716 716 # $ hg cat -r 10 sub/x.txt
717 717 #
718 718 # if sub/ is no longer a subrepository in the working copy
719 719 # parent revision.
720 720 #
721 721 # However, it can of course also allow things that would have
722 722 # been rejected before, such as the above cat command if sub/
723 723 # is a subrepository now, but was a normal directory before.
724 724 # The old path auditor would have rejected by mistake since it
725 725 # panics when it sees sub/.hg/.
726 726 #
727 727 # All in all, checking against the working copy seems sensible
728 728 # since we want to prevent access to nested repositories on
729 729 # the filesystem *now*.
730 730 ctx = self[None]
731 731 parts = util.splitpath(subpath)
732 732 while parts:
733 733 prefix = '/'.join(parts)
734 734 if prefix in ctx.substate:
735 735 if prefix == normsubpath:
736 736 return True
737 737 else:
738 738 sub = ctx.sub(prefix)
739 739 return sub.checknested(subpath[len(prefix) + 1:])
740 740 else:
741 741 parts.pop()
742 742 return False
743 743
744 744 def peer(self):
745 745 return localpeer(self) # not cached to avoid reference cycle
746 746
747 747 def unfiltered(self):
748 748 """Return unfiltered version of the repository
749 749
750 750 Intended to be overwritten by filtered repo."""
751 751 return self
752 752
753 753 def filtered(self, name, visibilityexceptions=None):
754 754 """Return a filtered version of a repository"""
755 755 cls = repoview.newtype(self.unfiltered().__class__)
756 756 return cls(self, name, visibilityexceptions)
757 757
758 758 @repofilecache('bookmarks', 'bookmarks.current')
759 759 def _bookmarks(self):
760 760 return bookmarks.bmstore(self)
761 761
762 762 @property
763 763 def _activebookmark(self):
764 764 return self._bookmarks.active
765 765
766 766 # _phasesets depend on changelog. what we need is to call
767 767 # _phasecache.invalidate() if '00changelog.i' was changed, but it
768 768 # can't be easily expressed in filecache mechanism.
769 769 @storecache('phaseroots', '00changelog.i')
770 770 def _phasecache(self):
771 771 return phases.phasecache(self, self._phasedefaults)
772 772
773 773 @storecache('obsstore')
774 774 def obsstore(self):
775 775 return obsolete.makestore(self.ui, self)
776 776
777 777 @storecache('00changelog.i')
778 778 def changelog(self):
779 779 return changelog.changelog(self.svfs,
780 780 trypending=txnutil.mayhavepending(self.root))
781 781
782 782 def _constructmanifest(self):
783 783 # This is a temporary function while we migrate from manifest to
784 784 # manifestlog. It allows bundlerepo and unionrepo to intercept the
785 785 # manifest creation.
786 786 return manifest.manifestrevlog(self.svfs)
787 787
788 788 @storecache('00manifest.i')
789 789 def manifestlog(self):
790 790 return manifest.manifestlog(self.svfs, self)
791 791
792 792 @repofilecache('dirstate')
793 793 def dirstate(self):
794 794 return self._makedirstate()
795 795
796 796 def _makedirstate(self):
797 797 """Extension point for wrapping the dirstate per-repo."""
798 798 sparsematchfn = lambda: sparse.matcher(self)
799 799
800 800 return dirstate.dirstate(self.vfs, self.ui, self.root,
801 801 self._dirstatevalidate, sparsematchfn)
802 802
803 803 def _dirstatevalidate(self, node):
804 804 try:
805 805 self.changelog.rev(node)
806 806 return node
807 807 except error.LookupError:
808 808 if not self._dirstatevalidatewarned:
809 809 self._dirstatevalidatewarned = True
810 810 self.ui.warn(_("warning: ignoring unknown"
811 811 " working parent %s!\n") % short(node))
812 812 return nullid
813 813
814 @repofilecache(narrowspec.FILENAME)
814 @storecache(narrowspec.FILENAME)
815 815 def narrowpats(self):
816 816 """matcher patterns for this repository's narrowspec
817 817
818 818 A tuple of (includes, excludes).
819 819 """
820 820 source = self
821 821 if self.shared():
822 822 from . import hg
823 823 source = hg.sharedreposource(self)
824 824 return narrowspec.load(source)
825 825
826 @repofilecache(narrowspec.FILENAME)
826 @storecache(narrowspec.FILENAME)
827 827 def _narrowmatch(self):
828 828 if repository.NARROW_REQUIREMENT not in self.requirements:
829 829 return matchmod.always(self.root, '')
830 830 include, exclude = self.narrowpats
831 831 return narrowspec.match(self.root, include=include, exclude=exclude)
832 832
833 833 # TODO(martinvonz): make this property-like instead?
834 834 def narrowmatch(self):
835 835 return self._narrowmatch
836 836
837 837 def setnarrowpats(self, newincludes, newexcludes):
838 838 target = self
839 839 if self.shared():
840 840 from . import hg
841 841 target = hg.sharedreposource(self)
842 842 narrowspec.save(target, newincludes, newexcludes)
843 843 self.invalidate(clearfilecache=True)
844 844
845 845 def __getitem__(self, changeid):
846 846 if changeid is None:
847 847 return context.workingctx(self)
848 848 if isinstance(changeid, context.basectx):
849 849 return changeid
850 850 if isinstance(changeid, slice):
851 851 # wdirrev isn't contiguous so the slice shouldn't include it
852 852 return [context.changectx(self, i)
853 853 for i in pycompat.xrange(*changeid.indices(len(self)))
854 854 if i not in self.changelog.filteredrevs]
855 855 try:
856 856 return context.changectx(self, changeid)
857 857 except error.WdirUnsupported:
858 858 return context.workingctx(self)
859 859
860 860 def __contains__(self, changeid):
861 861 """True if the given changeid exists
862 862
863 863 error.AmbiguousPrefixLookupError is raised if an ambiguous node
864 864 specified.
865 865 """
866 866 try:
867 867 self[changeid]
868 868 return True
869 869 except error.RepoLookupError:
870 870 return False
871 871
872 872 def __nonzero__(self):
873 873 return True
874 874
875 875 __bool__ = __nonzero__
876 876
877 877 def __len__(self):
878 878 # no need to pay the cost of repoview.changelog
879 879 unfi = self.unfiltered()
880 880 return len(unfi.changelog)
881 881
882 882 def __iter__(self):
883 883 return iter(self.changelog)
884 884
885 885 def revs(self, expr, *args):
886 886 '''Find revisions matching a revset.
887 887
888 888 The revset is specified as a string ``expr`` that may contain
889 889 %-formatting to escape certain types. See ``revsetlang.formatspec``.
890 890
891 891 Revset aliases from the configuration are not expanded. To expand
892 892 user aliases, consider calling ``scmutil.revrange()`` or
893 893 ``repo.anyrevs([expr], user=True)``.
894 894
895 895 Returns a revset.abstractsmartset, which is a list-like interface
896 896 that contains integer revisions.
897 897 '''
898 898 expr = revsetlang.formatspec(expr, *args)
899 899 m = revset.match(None, expr)
900 900 return m(self)
901 901
902 902 def set(self, expr, *args):
903 903 '''Find revisions matching a revset and emit changectx instances.
904 904
905 905 This is a convenience wrapper around ``revs()`` that iterates the
906 906 result and is a generator of changectx instances.
907 907
908 908 Revset aliases from the configuration are not expanded. To expand
909 909 user aliases, consider calling ``scmutil.revrange()``.
910 910 '''
911 911 for r in self.revs(expr, *args):
912 912 yield self[r]
913 913
914 914 def anyrevs(self, specs, user=False, localalias=None):
915 915 '''Find revisions matching one of the given revsets.
916 916
917 917 Revset aliases from the configuration are not expanded by default. To
918 918 expand user aliases, specify ``user=True``. To provide some local
919 919 definitions overriding user aliases, set ``localalias`` to
920 920 ``{name: definitionstring}``.
921 921 '''
922 922 if user:
923 923 m = revset.matchany(self.ui, specs,
924 924 lookup=revset.lookupfn(self),
925 925 localalias=localalias)
926 926 else:
927 927 m = revset.matchany(None, specs, localalias=localalias)
928 928 return m(self)
929 929
930 930 def url(self):
931 931 return 'file:' + self.root
932 932
933 933 def hook(self, name, throw=False, **args):
934 934 """Call a hook, passing this repo instance.
935 935
936 936 This a convenience method to aid invoking hooks. Extensions likely
937 937 won't call this unless they have registered a custom hook or are
938 938 replacing code that is expected to call a hook.
939 939 """
940 940 return hook.hook(self.ui, self, name, throw, **args)
941 941
942 942 @filteredpropertycache
943 943 def _tagscache(self):
944 944 '''Returns a tagscache object that contains various tags related
945 945 caches.'''
946 946
947 947 # This simplifies its cache management by having one decorated
948 948 # function (this one) and the rest simply fetch things from it.
949 949 class tagscache(object):
950 950 def __init__(self):
951 951 # These two define the set of tags for this repository. tags
952 952 # maps tag name to node; tagtypes maps tag name to 'global' or
953 953 # 'local'. (Global tags are defined by .hgtags across all
954 954 # heads, and local tags are defined in .hg/localtags.)
955 955 # They constitute the in-memory cache of tags.
956 956 self.tags = self.tagtypes = None
957 957
958 958 self.nodetagscache = self.tagslist = None
959 959
960 960 cache = tagscache()
961 961 cache.tags, cache.tagtypes = self._findtags()
962 962
963 963 return cache
964 964
965 965 def tags(self):
966 966 '''return a mapping of tag to node'''
967 967 t = {}
968 968 if self.changelog.filteredrevs:
969 969 tags, tt = self._findtags()
970 970 else:
971 971 tags = self._tagscache.tags
972 972 for k, v in tags.iteritems():
973 973 try:
974 974 # ignore tags to unknown nodes
975 975 self.changelog.rev(v)
976 976 t[k] = v
977 977 except (error.LookupError, ValueError):
978 978 pass
979 979 return t
980 980
981 981 def _findtags(self):
982 982 '''Do the hard work of finding tags. Return a pair of dicts
983 983 (tags, tagtypes) where tags maps tag name to node, and tagtypes
984 984 maps tag name to a string like \'global\' or \'local\'.
985 985 Subclasses or extensions are free to add their own tags, but
986 986 should be aware that the returned dicts will be retained for the
987 987 duration of the localrepo object.'''
988 988
989 989 # XXX what tagtype should subclasses/extensions use? Currently
990 990 # mq and bookmarks add tags, but do not set the tagtype at all.
991 991 # Should each extension invent its own tag type? Should there
992 992 # be one tagtype for all such "virtual" tags? Or is the status
993 993 # quo fine?
994 994
995 995
996 996 # map tag name to (node, hist)
997 997 alltags = tagsmod.findglobaltags(self.ui, self)
998 998 # map tag name to tag type
999 999 tagtypes = dict((tag, 'global') for tag in alltags)
1000 1000
1001 1001 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
1002 1002
1003 1003 # Build the return dicts. Have to re-encode tag names because
1004 1004 # the tags module always uses UTF-8 (in order not to lose info
1005 1005 # writing to the cache), but the rest of Mercurial wants them in
1006 1006 # local encoding.
1007 1007 tags = {}
1008 1008 for (name, (node, hist)) in alltags.iteritems():
1009 1009 if node != nullid:
1010 1010 tags[encoding.tolocal(name)] = node
1011 1011 tags['tip'] = self.changelog.tip()
1012 1012 tagtypes = dict([(encoding.tolocal(name), value)
1013 1013 for (name, value) in tagtypes.iteritems()])
1014 1014 return (tags, tagtypes)
1015 1015
1016 1016 def tagtype(self, tagname):
1017 1017 '''
1018 1018 return the type of the given tag. result can be:
1019 1019
1020 1020 'local' : a local tag
1021 1021 'global' : a global tag
1022 1022 None : tag does not exist
1023 1023 '''
1024 1024
1025 1025 return self._tagscache.tagtypes.get(tagname)
1026 1026
1027 1027 def tagslist(self):
1028 1028 '''return a list of tags ordered by revision'''
1029 1029 if not self._tagscache.tagslist:
1030 1030 l = []
1031 1031 for t, n in self.tags().iteritems():
1032 1032 l.append((self.changelog.rev(n), t, n))
1033 1033 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
1034 1034
1035 1035 return self._tagscache.tagslist
1036 1036
1037 1037 def nodetags(self, node):
1038 1038 '''return the tags associated with a node'''
1039 1039 if not self._tagscache.nodetagscache:
1040 1040 nodetagscache = {}
1041 1041 for t, n in self._tagscache.tags.iteritems():
1042 1042 nodetagscache.setdefault(n, []).append(t)
1043 1043 for tags in nodetagscache.itervalues():
1044 1044 tags.sort()
1045 1045 self._tagscache.nodetagscache = nodetagscache
1046 1046 return self._tagscache.nodetagscache.get(node, [])
1047 1047
1048 1048 def nodebookmarks(self, node):
1049 1049 """return the list of bookmarks pointing to the specified node"""
1050 1050 return self._bookmarks.names(node)
1051 1051
1052 1052 def branchmap(self):
1053 1053 '''returns a dictionary {branch: [branchheads]} with branchheads
1054 1054 ordered by increasing revision number'''
1055 1055 branchmap.updatecache(self)
1056 1056 return self._branchcaches[self.filtername]
1057 1057
1058 1058 @unfilteredmethod
1059 1059 def revbranchcache(self):
1060 1060 if not self._revbranchcache:
1061 1061 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
1062 1062 return self._revbranchcache
1063 1063
1064 1064 def branchtip(self, branch, ignoremissing=False):
1065 1065 '''return the tip node for a given branch
1066 1066
1067 1067 If ignoremissing is True, then this method will not raise an error.
1068 1068 This is helpful for callers that only expect None for a missing branch
1069 1069 (e.g. namespace).
1070 1070
1071 1071 '''
1072 1072 try:
1073 1073 return self.branchmap().branchtip(branch)
1074 1074 except KeyError:
1075 1075 if not ignoremissing:
1076 1076 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
1077 1077 else:
1078 1078 pass
1079 1079
1080 1080 def lookup(self, key):
1081 1081 return scmutil.revsymbol(self, key).node()
1082 1082
1083 1083 def lookupbranch(self, key):
1084 1084 if key in self.branchmap():
1085 1085 return key
1086 1086
1087 1087 return scmutil.revsymbol(self, key).branch()
1088 1088
1089 1089 def known(self, nodes):
1090 1090 cl = self.changelog
1091 1091 nm = cl.nodemap
1092 1092 filtered = cl.filteredrevs
1093 1093 result = []
1094 1094 for n in nodes:
1095 1095 r = nm.get(n)
1096 1096 resp = not (r is None or r in filtered)
1097 1097 result.append(resp)
1098 1098 return result
1099 1099
1100 1100 def local(self):
1101 1101 return self
1102 1102
1103 1103 def publishing(self):
1104 1104 # it's safe (and desirable) to trust the publish flag unconditionally
1105 1105 # so that we don't finalize changes shared between users via ssh or nfs
1106 1106 return self.ui.configbool('phases', 'publish', untrusted=True)
1107 1107
1108 1108 def cancopy(self):
1109 1109 # so statichttprepo's override of local() works
1110 1110 if not self.local():
1111 1111 return False
1112 1112 if not self.publishing():
1113 1113 return True
1114 1114 # if publishing we can't copy if there is filtered content
1115 1115 return not self.filtered('visible').changelog.filteredrevs
1116 1116
1117 1117 def shared(self):
1118 1118 '''the type of shared repository (None if not shared)'''
1119 1119 if self.sharedpath != self.path:
1120 1120 return 'store'
1121 1121 return None
1122 1122
1123 1123 def wjoin(self, f, *insidef):
1124 1124 return self.vfs.reljoin(self.root, f, *insidef)
1125 1125
1126 1126 def file(self, f):
1127 1127 if f[0] == '/':
1128 1128 f = f[1:]
1129 1129 return filelog.filelog(self.svfs, f)
1130 1130
1131 1131 def setparents(self, p1, p2=nullid):
1132 1132 with self.dirstate.parentchange():
1133 1133 copies = self.dirstate.setparents(p1, p2)
1134 1134 pctx = self[p1]
1135 1135 if copies:
1136 1136 # Adjust copy records, the dirstate cannot do it, it
1137 1137 # requires access to parents manifests. Preserve them
1138 1138 # only for entries added to first parent.
1139 1139 for f in copies:
1140 1140 if f not in pctx and copies[f] in pctx:
1141 1141 self.dirstate.copy(copies[f], f)
1142 1142 if p2 == nullid:
1143 1143 for f, s in sorted(self.dirstate.copies().items()):
1144 1144 if f not in pctx and s not in pctx:
1145 1145 self.dirstate.copy(None, f)
1146 1146
1147 1147 def filectx(self, path, changeid=None, fileid=None, changectx=None):
1148 1148 """changeid can be a changeset revision, node, or tag.
1149 1149 fileid can be a file revision or node."""
1150 1150 return context.filectx(self, path, changeid, fileid,
1151 1151 changectx=changectx)
1152 1152
1153 1153 def getcwd(self):
1154 1154 return self.dirstate.getcwd()
1155 1155
1156 1156 def pathto(self, f, cwd=None):
1157 1157 return self.dirstate.pathto(f, cwd)
1158 1158
1159 1159 def _loadfilter(self, filter):
1160 1160 if filter not in self._filterpats:
1161 1161 l = []
1162 1162 for pat, cmd in self.ui.configitems(filter):
1163 1163 if cmd == '!':
1164 1164 continue
1165 1165 mf = matchmod.match(self.root, '', [pat])
1166 1166 fn = None
1167 1167 params = cmd
1168 1168 for name, filterfn in self._datafilters.iteritems():
1169 1169 if cmd.startswith(name):
1170 1170 fn = filterfn
1171 1171 params = cmd[len(name):].lstrip()
1172 1172 break
1173 1173 if not fn:
1174 1174 fn = lambda s, c, **kwargs: procutil.filter(s, c)
1175 1175 # Wrap old filters not supporting keyword arguments
1176 1176 if not pycompat.getargspec(fn)[2]:
1177 1177 oldfn = fn
1178 1178 fn = lambda s, c, **kwargs: oldfn(s, c)
1179 1179 l.append((mf, fn, params))
1180 1180 self._filterpats[filter] = l
1181 1181 return self._filterpats[filter]
1182 1182
1183 1183 def _filter(self, filterpats, filename, data):
1184 1184 for mf, fn, cmd in filterpats:
1185 1185 if mf(filename):
1186 1186 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1187 1187 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1188 1188 break
1189 1189
1190 1190 return data
1191 1191
1192 1192 @unfilteredpropertycache
1193 1193 def _encodefilterpats(self):
1194 1194 return self._loadfilter('encode')
1195 1195
1196 1196 @unfilteredpropertycache
1197 1197 def _decodefilterpats(self):
1198 1198 return self._loadfilter('decode')
1199 1199
1200 1200 def adddatafilter(self, name, filter):
1201 1201 self._datafilters[name] = filter
1202 1202
1203 1203 def wread(self, filename):
1204 1204 if self.wvfs.islink(filename):
1205 1205 data = self.wvfs.readlink(filename)
1206 1206 else:
1207 1207 data = self.wvfs.read(filename)
1208 1208 return self._filter(self._encodefilterpats, filename, data)
1209 1209
1210 1210 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
1211 1211 """write ``data`` into ``filename`` in the working directory
1212 1212
1213 1213 This returns length of written (maybe decoded) data.
1214 1214 """
1215 1215 data = self._filter(self._decodefilterpats, filename, data)
1216 1216 if 'l' in flags:
1217 1217 self.wvfs.symlink(data, filename)
1218 1218 else:
1219 1219 self.wvfs.write(filename, data, backgroundclose=backgroundclose,
1220 1220 **kwargs)
1221 1221 if 'x' in flags:
1222 1222 self.wvfs.setflags(filename, False, True)
1223 1223 else:
1224 1224 self.wvfs.setflags(filename, False, False)
1225 1225 return len(data)
1226 1226
1227 1227 def wwritedata(self, filename, data):
1228 1228 return self._filter(self._decodefilterpats, filename, data)
1229 1229
1230 1230 def currenttransaction(self):
1231 1231 """return the current transaction or None if non exists"""
1232 1232 if self._transref:
1233 1233 tr = self._transref()
1234 1234 else:
1235 1235 tr = None
1236 1236
1237 1237 if tr and tr.running():
1238 1238 return tr
1239 1239 return None
1240 1240
1241 1241 def transaction(self, desc, report=None):
1242 1242 if (self.ui.configbool('devel', 'all-warnings')
1243 1243 or self.ui.configbool('devel', 'check-locks')):
1244 1244 if self._currentlock(self._lockref) is None:
1245 1245 raise error.ProgrammingError('transaction requires locking')
1246 1246 tr = self.currenttransaction()
1247 1247 if tr is not None:
1248 1248 return tr.nest(name=desc)
1249 1249
1250 1250 # abort here if the journal already exists
1251 1251 if self.svfs.exists("journal"):
1252 1252 raise error.RepoError(
1253 1253 _("abandoned transaction found"),
1254 1254 hint=_("run 'hg recover' to clean up transaction"))
1255 1255
1256 1256 idbase = "%.40f#%f" % (random.random(), time.time())
1257 1257 ha = hex(hashlib.sha1(idbase).digest())
1258 1258 txnid = 'TXN:' + ha
1259 1259 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1260 1260
1261 1261 self._writejournal(desc)
1262 1262 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1263 1263 if report:
1264 1264 rp = report
1265 1265 else:
1266 1266 rp = self.ui.warn
1267 1267 vfsmap = {'plain': self.vfs} # root of .hg/
1268 1268 # we must avoid cyclic reference between repo and transaction.
1269 1269 reporef = weakref.ref(self)
1270 1270 # Code to track tag movement
1271 1271 #
1272 1272 # Since tags are all handled as file content, it is actually quite hard
1273 1273 # to track these movement from a code perspective. So we fallback to a
1274 1274 # tracking at the repository level. One could envision to track changes
1275 1275 # to the '.hgtags' file through changegroup apply but that fails to
1276 1276 # cope with case where transaction expose new heads without changegroup
1277 1277 # being involved (eg: phase movement).
1278 1278 #
1279 1279 # For now, We gate the feature behind a flag since this likely comes
1280 1280 # with performance impacts. The current code run more often than needed
1281 1281 # and do not use caches as much as it could. The current focus is on
1282 1282 # the behavior of the feature so we disable it by default. The flag
1283 1283 # will be removed when we are happy with the performance impact.
1284 1284 #
1285 1285 # Once this feature is no longer experimental move the following
1286 1286 # documentation to the appropriate help section:
1287 1287 #
1288 1288 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1289 1289 # tags (new or changed or deleted tags). In addition the details of
1290 1290 # these changes are made available in a file at:
1291 1291 # ``REPOROOT/.hg/changes/tags.changes``.
1292 1292 # Make sure you check for HG_TAG_MOVED before reading that file as it
1293 1293 # might exist from a previous transaction even if no tag were touched
1294 1294 # in this one. Changes are recorded in a line base format::
1295 1295 #
1296 1296 # <action> <hex-node> <tag-name>\n
1297 1297 #
1298 1298 # Actions are defined as follow:
1299 1299 # "-R": tag is removed,
1300 1300 # "+A": tag is added,
1301 1301 # "-M": tag is moved (old value),
1302 1302 # "+M": tag is moved (new value),
1303 1303 tracktags = lambda x: None
1304 1304 # experimental config: experimental.hook-track-tags
1305 1305 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1306 1306 if desc != 'strip' and shouldtracktags:
1307 1307 oldheads = self.changelog.headrevs()
1308 1308 def tracktags(tr2):
1309 1309 repo = reporef()
1310 1310 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1311 1311 newheads = repo.changelog.headrevs()
1312 1312 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1313 1313 # notes: we compare lists here.
1314 1314 # As we do it only once buiding set would not be cheaper
1315 1315 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1316 1316 if changes:
1317 1317 tr2.hookargs['tag_moved'] = '1'
1318 1318 with repo.vfs('changes/tags.changes', 'w',
1319 1319 atomictemp=True) as changesfile:
1320 1320 # note: we do not register the file to the transaction
1321 1321 # because we needs it to still exist on the transaction
1322 1322 # is close (for txnclose hooks)
1323 1323 tagsmod.writediff(changesfile, changes)
1324 1324 def validate(tr2):
1325 1325 """will run pre-closing hooks"""
1326 1326 # XXX the transaction API is a bit lacking here so we take a hacky
1327 1327 # path for now
1328 1328 #
1329 1329 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1330 1330 # dict is copied before these run. In addition we needs the data
1331 1331 # available to in memory hooks too.
1332 1332 #
1333 1333 # Moreover, we also need to make sure this runs before txnclose
1334 1334 # hooks and there is no "pending" mechanism that would execute
1335 1335 # logic only if hooks are about to run.
1336 1336 #
1337 1337 # Fixing this limitation of the transaction is also needed to track
1338 1338 # other families of changes (bookmarks, phases, obsolescence).
1339 1339 #
1340 1340 # This will have to be fixed before we remove the experimental
1341 1341 # gating.
1342 1342 tracktags(tr2)
1343 1343 repo = reporef()
1344 1344 if repo.ui.configbool('experimental', 'single-head-per-branch'):
1345 1345 scmutil.enforcesinglehead(repo, tr2, desc)
1346 1346 if hook.hashook(repo.ui, 'pretxnclose-bookmark'):
1347 1347 for name, (old, new) in sorted(tr.changes['bookmarks'].items()):
1348 1348 args = tr.hookargs.copy()
1349 1349 args.update(bookmarks.preparehookargs(name, old, new))
1350 1350 repo.hook('pretxnclose-bookmark', throw=True,
1351 1351 txnname=desc,
1352 1352 **pycompat.strkwargs(args))
1353 1353 if hook.hashook(repo.ui, 'pretxnclose-phase'):
1354 1354 cl = repo.unfiltered().changelog
1355 1355 for rev, (old, new) in tr.changes['phases'].items():
1356 1356 args = tr.hookargs.copy()
1357 1357 node = hex(cl.node(rev))
1358 1358 args.update(phases.preparehookargs(node, old, new))
1359 1359 repo.hook('pretxnclose-phase', throw=True, txnname=desc,
1360 1360 **pycompat.strkwargs(args))
1361 1361
1362 1362 repo.hook('pretxnclose', throw=True,
1363 1363 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1364 1364 def releasefn(tr, success):
1365 1365 repo = reporef()
1366 1366 if success:
1367 1367 # this should be explicitly invoked here, because
1368 1368 # in-memory changes aren't written out at closing
1369 1369 # transaction, if tr.addfilegenerator (via
1370 1370 # dirstate.write or so) isn't invoked while
1371 1371 # transaction running
1372 1372 repo.dirstate.write(None)
1373 1373 else:
1374 1374 # discard all changes (including ones already written
1375 1375 # out) in this transaction
1376 1376 narrowspec.restorebackup(self, 'journal.narrowspec')
1377 1377 repo.dirstate.restorebackup(None, 'journal.dirstate')
1378 1378
1379 1379 repo.invalidate(clearfilecache=True)
1380 1380
1381 1381 tr = transaction.transaction(rp, self.svfs, vfsmap,
1382 1382 "journal",
1383 1383 "undo",
1384 1384 aftertrans(renames),
1385 1385 self.store.createmode,
1386 1386 validator=validate,
1387 1387 releasefn=releasefn,
1388 1388 checkambigfiles=_cachedfiles,
1389 1389 name=desc)
1390 1390 tr.changes['revs'] = pycompat.xrange(0, 0)
1391 1391 tr.changes['obsmarkers'] = set()
1392 1392 tr.changes['phases'] = {}
1393 1393 tr.changes['bookmarks'] = {}
1394 1394
1395 1395 tr.hookargs['txnid'] = txnid
1396 1396 # note: writing the fncache only during finalize mean that the file is
1397 1397 # outdated when running hooks. As fncache is used for streaming clone,
1398 1398 # this is not expected to break anything that happen during the hooks.
1399 1399 tr.addfinalize('flush-fncache', self.store.write)
1400 1400 def txnclosehook(tr2):
1401 1401 """To be run if transaction is successful, will schedule a hook run
1402 1402 """
1403 1403 # Don't reference tr2 in hook() so we don't hold a reference.
1404 1404 # This reduces memory consumption when there are multiple
1405 1405 # transactions per lock. This can likely go away if issue5045
1406 1406 # fixes the function accumulation.
1407 1407 hookargs = tr2.hookargs
1408 1408
1409 1409 def hookfunc():
1410 1410 repo = reporef()
1411 1411 if hook.hashook(repo.ui, 'txnclose-bookmark'):
1412 1412 bmchanges = sorted(tr.changes['bookmarks'].items())
1413 1413 for name, (old, new) in bmchanges:
1414 1414 args = tr.hookargs.copy()
1415 1415 args.update(bookmarks.preparehookargs(name, old, new))
1416 1416 repo.hook('txnclose-bookmark', throw=False,
1417 1417 txnname=desc, **pycompat.strkwargs(args))
1418 1418
1419 1419 if hook.hashook(repo.ui, 'txnclose-phase'):
1420 1420 cl = repo.unfiltered().changelog
1421 1421 phasemv = sorted(tr.changes['phases'].items())
1422 1422 for rev, (old, new) in phasemv:
1423 1423 args = tr.hookargs.copy()
1424 1424 node = hex(cl.node(rev))
1425 1425 args.update(phases.preparehookargs(node, old, new))
1426 1426 repo.hook('txnclose-phase', throw=False, txnname=desc,
1427 1427 **pycompat.strkwargs(args))
1428 1428
1429 1429 repo.hook('txnclose', throw=False, txnname=desc,
1430 1430 **pycompat.strkwargs(hookargs))
1431 1431 reporef()._afterlock(hookfunc)
1432 1432 tr.addfinalize('txnclose-hook', txnclosehook)
1433 1433 # Include a leading "-" to make it happen before the transaction summary
1434 1434 # reports registered via scmutil.registersummarycallback() whose names
1435 1435 # are 00-txnreport etc. That way, the caches will be warm when the
1436 1436 # callbacks run.
1437 1437 tr.addpostclose('-warm-cache', self._buildcacheupdater(tr))
1438 1438 def txnaborthook(tr2):
1439 1439 """To be run if transaction is aborted
1440 1440 """
1441 1441 reporef().hook('txnabort', throw=False, txnname=desc,
1442 1442 **pycompat.strkwargs(tr2.hookargs))
1443 1443 tr.addabort('txnabort-hook', txnaborthook)
1444 1444 # avoid eager cache invalidation. in-memory data should be identical
1445 1445 # to stored data if transaction has no error.
1446 1446 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1447 1447 self._transref = weakref.ref(tr)
1448 1448 scmutil.registersummarycallback(self, tr, desc)
1449 1449 return tr
1450 1450
1451 1451 def _journalfiles(self):
1452 1452 return ((self.svfs, 'journal'),
1453 1453 (self.vfs, 'journal.dirstate'),
1454 1454 (self.vfs, 'journal.branch'),
1455 1455 (self.vfs, 'journal.desc'),
1456 1456 (self.vfs, 'journal.bookmarks'),
1457 1457 (self.svfs, 'journal.phaseroots'))
1458 1458
1459 1459 def undofiles(self):
1460 1460 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1461 1461
1462 1462 @unfilteredmethod
1463 1463 def _writejournal(self, desc):
1464 1464 self.dirstate.savebackup(None, 'journal.dirstate')
1465 1465 narrowspec.savebackup(self, 'journal.narrowspec')
1466 1466 self.vfs.write("journal.branch",
1467 1467 encoding.fromlocal(self.dirstate.branch()))
1468 1468 self.vfs.write("journal.desc",
1469 1469 "%d\n%s\n" % (len(self), desc))
1470 1470 self.vfs.write("journal.bookmarks",
1471 1471 self.vfs.tryread("bookmarks"))
1472 1472 self.svfs.write("journal.phaseroots",
1473 1473 self.svfs.tryread("phaseroots"))
1474 1474
1475 1475 def recover(self):
1476 1476 with self.lock():
1477 1477 if self.svfs.exists("journal"):
1478 1478 self.ui.status(_("rolling back interrupted transaction\n"))
1479 1479 vfsmap = {'': self.svfs,
1480 1480 'plain': self.vfs,}
1481 1481 transaction.rollback(self.svfs, vfsmap, "journal",
1482 1482 self.ui.warn,
1483 1483 checkambigfiles=_cachedfiles)
1484 1484 self.invalidate()
1485 1485 return True
1486 1486 else:
1487 1487 self.ui.warn(_("no interrupted transaction available\n"))
1488 1488 return False
1489 1489
1490 1490 def rollback(self, dryrun=False, force=False):
1491 1491 wlock = lock = dsguard = None
1492 1492 try:
1493 1493 wlock = self.wlock()
1494 1494 lock = self.lock()
1495 1495 if self.svfs.exists("undo"):
1496 1496 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1497 1497
1498 1498 return self._rollback(dryrun, force, dsguard)
1499 1499 else:
1500 1500 self.ui.warn(_("no rollback information available\n"))
1501 1501 return 1
1502 1502 finally:
1503 1503 release(dsguard, lock, wlock)
1504 1504
1505 1505 @unfilteredmethod # Until we get smarter cache management
1506 1506 def _rollback(self, dryrun, force, dsguard):
1507 1507 ui = self.ui
1508 1508 try:
1509 1509 args = self.vfs.read('undo.desc').splitlines()
1510 1510 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1511 1511 if len(args) >= 3:
1512 1512 detail = args[2]
1513 1513 oldtip = oldlen - 1
1514 1514
1515 1515 if detail and ui.verbose:
1516 1516 msg = (_('repository tip rolled back to revision %d'
1517 1517 ' (undo %s: %s)\n')
1518 1518 % (oldtip, desc, detail))
1519 1519 else:
1520 1520 msg = (_('repository tip rolled back to revision %d'
1521 1521 ' (undo %s)\n')
1522 1522 % (oldtip, desc))
1523 1523 except IOError:
1524 1524 msg = _('rolling back unknown transaction\n')
1525 1525 desc = None
1526 1526
1527 1527 if not force and self['.'] != self['tip'] and desc == 'commit':
1528 1528 raise error.Abort(
1529 1529 _('rollback of last commit while not checked out '
1530 1530 'may lose data'), hint=_('use -f to force'))
1531 1531
1532 1532 ui.status(msg)
1533 1533 if dryrun:
1534 1534 return 0
1535 1535
1536 1536 parents = self.dirstate.parents()
1537 1537 self.destroying()
1538 1538 vfsmap = {'plain': self.vfs, '': self.svfs}
1539 1539 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1540 1540 checkambigfiles=_cachedfiles)
1541 1541 if self.vfs.exists('undo.bookmarks'):
1542 1542 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1543 1543 if self.svfs.exists('undo.phaseroots'):
1544 1544 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1545 1545 self.invalidate()
1546 1546
1547 1547 parentgone = (parents[0] not in self.changelog.nodemap or
1548 1548 parents[1] not in self.changelog.nodemap)
1549 1549 if parentgone:
1550 1550 # prevent dirstateguard from overwriting already restored one
1551 1551 dsguard.close()
1552 1552
1553 1553 narrowspec.restorebackup(self, 'undo.narrowspec')
1554 1554 self.dirstate.restorebackup(None, 'undo.dirstate')
1555 1555 try:
1556 1556 branch = self.vfs.read('undo.branch')
1557 1557 self.dirstate.setbranch(encoding.tolocal(branch))
1558 1558 except IOError:
1559 1559 ui.warn(_('named branch could not be reset: '
1560 1560 'current branch is still \'%s\'\n')
1561 1561 % self.dirstate.branch())
1562 1562
1563 1563 parents = tuple([p.rev() for p in self[None].parents()])
1564 1564 if len(parents) > 1:
1565 1565 ui.status(_('working directory now based on '
1566 1566 'revisions %d and %d\n') % parents)
1567 1567 else:
1568 1568 ui.status(_('working directory now based on '
1569 1569 'revision %d\n') % parents)
1570 1570 mergemod.mergestate.clean(self, self['.'].node())
1571 1571
1572 1572 # TODO: if we know which new heads may result from this rollback, pass
1573 1573 # them to destroy(), which will prevent the branchhead cache from being
1574 1574 # invalidated.
1575 1575 self.destroyed()
1576 1576 return 0
1577 1577
1578 1578 def _buildcacheupdater(self, newtransaction):
1579 1579 """called during transaction to build the callback updating cache
1580 1580
1581 1581 Lives on the repository to help extension who might want to augment
1582 1582 this logic. For this purpose, the created transaction is passed to the
1583 1583 method.
1584 1584 """
1585 1585 # we must avoid cyclic reference between repo and transaction.
1586 1586 reporef = weakref.ref(self)
1587 1587 def updater(tr):
1588 1588 repo = reporef()
1589 1589 repo.updatecaches(tr)
1590 1590 return updater
1591 1591
1592 1592 @unfilteredmethod
1593 1593 def updatecaches(self, tr=None, full=False):
1594 1594 """warm appropriate caches
1595 1595
1596 1596 If this function is called after a transaction closed. The transaction
1597 1597 will be available in the 'tr' argument. This can be used to selectively
1598 1598 update caches relevant to the changes in that transaction.
1599 1599
1600 1600 If 'full' is set, make sure all caches the function knows about have
1601 1601 up-to-date data. Even the ones usually loaded more lazily.
1602 1602 """
1603 1603 if tr is not None and tr.hookargs.get('source') == 'strip':
1604 1604 # During strip, many caches are invalid but
1605 1605 # later call to `destroyed` will refresh them.
1606 1606 return
1607 1607
1608 1608 if tr is None or tr.changes['revs']:
1609 1609 # updating the unfiltered branchmap should refresh all the others,
1610 1610 self.ui.debug('updating the branch cache\n')
1611 1611 branchmap.updatecache(self.filtered('served'))
1612 1612
1613 1613 if full:
1614 1614 rbc = self.revbranchcache()
1615 1615 for r in self.changelog:
1616 1616 rbc.branchinfo(r)
1617 1617 rbc.write()
1618 1618
1619 1619 # ensure the working copy parents are in the manifestfulltextcache
1620 1620 for ctx in self['.'].parents():
1621 1621 ctx.manifest() # accessing the manifest is enough
1622 1622
1623 1623 def invalidatecaches(self):
1624 1624
1625 1625 if '_tagscache' in vars(self):
1626 1626 # can't use delattr on proxy
1627 1627 del self.__dict__['_tagscache']
1628 1628
1629 1629 self.unfiltered()._branchcaches.clear()
1630 1630 self.invalidatevolatilesets()
1631 1631 self._sparsesignaturecache.clear()
1632 1632
1633 1633 def invalidatevolatilesets(self):
1634 1634 self.filteredrevcache.clear()
1635 1635 obsolete.clearobscaches(self)
1636 1636
1637 1637 def invalidatedirstate(self):
1638 1638 '''Invalidates the dirstate, causing the next call to dirstate
1639 1639 to check if it was modified since the last time it was read,
1640 1640 rereading it if it has.
1641 1641
1642 1642 This is different to dirstate.invalidate() that it doesn't always
1643 1643 rereads the dirstate. Use dirstate.invalidate() if you want to
1644 1644 explicitly read the dirstate again (i.e. restoring it to a previous
1645 1645 known good state).'''
1646 1646 if hasunfilteredcache(self, 'dirstate'):
1647 1647 for k in self.dirstate._filecache:
1648 1648 try:
1649 1649 delattr(self.dirstate, k)
1650 1650 except AttributeError:
1651 1651 pass
1652 1652 delattr(self.unfiltered(), 'dirstate')
1653 1653
1654 1654 def invalidate(self, clearfilecache=False):
1655 1655 '''Invalidates both store and non-store parts other than dirstate
1656 1656
1657 1657 If a transaction is running, invalidation of store is omitted,
1658 1658 because discarding in-memory changes might cause inconsistency
1659 1659 (e.g. incomplete fncache causes unintentional failure, but
1660 1660 redundant one doesn't).
1661 1661 '''
1662 1662 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1663 1663 for k in list(self._filecache.keys()):
1664 1664 # dirstate is invalidated separately in invalidatedirstate()
1665 1665 if k == 'dirstate':
1666 1666 continue
1667 1667 if (k == 'changelog' and
1668 1668 self.currenttransaction() and
1669 1669 self.changelog._delayed):
1670 1670 # The changelog object may store unwritten revisions. We don't
1671 1671 # want to lose them.
1672 1672 # TODO: Solve the problem instead of working around it.
1673 1673 continue
1674 1674
1675 1675 if clearfilecache:
1676 1676 del self._filecache[k]
1677 1677 try:
1678 1678 delattr(unfiltered, k)
1679 1679 except AttributeError:
1680 1680 pass
1681 1681 self.invalidatecaches()
1682 1682 if not self.currenttransaction():
1683 1683 # TODO: Changing contents of store outside transaction
1684 1684 # causes inconsistency. We should make in-memory store
1685 1685 # changes detectable, and abort if changed.
1686 1686 self.store.invalidatecaches()
1687 1687
1688 1688 def invalidateall(self):
1689 1689 '''Fully invalidates both store and non-store parts, causing the
1690 1690 subsequent operation to reread any outside changes.'''
1691 1691 # extension should hook this to invalidate its caches
1692 1692 self.invalidate()
1693 1693 self.invalidatedirstate()
1694 1694
1695 1695 @unfilteredmethod
1696 1696 def _refreshfilecachestats(self, tr):
1697 1697 """Reload stats of cached files so that they are flagged as valid"""
1698 1698 for k, ce in self._filecache.items():
1699 1699 k = pycompat.sysstr(k)
1700 1700 if k == r'dirstate' or k not in self.__dict__:
1701 1701 continue
1702 1702 ce.refresh()
1703 1703
1704 1704 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1705 1705 inheritchecker=None, parentenvvar=None):
1706 1706 parentlock = None
1707 1707 # the contents of parentenvvar are used by the underlying lock to
1708 1708 # determine whether it can be inherited
1709 1709 if parentenvvar is not None:
1710 1710 parentlock = encoding.environ.get(parentenvvar)
1711 1711
1712 1712 timeout = 0
1713 1713 warntimeout = 0
1714 1714 if wait:
1715 1715 timeout = self.ui.configint("ui", "timeout")
1716 1716 warntimeout = self.ui.configint("ui", "timeout.warn")
1717 1717 # internal config: ui.signal-safe-lock
1718 1718 signalsafe = self.ui.configbool('ui', 'signal-safe-lock')
1719 1719
1720 1720 l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout,
1721 1721 releasefn=releasefn,
1722 1722 acquirefn=acquirefn, desc=desc,
1723 1723 inheritchecker=inheritchecker,
1724 1724 parentlock=parentlock,
1725 1725 signalsafe=signalsafe)
1726 1726 return l
1727 1727
1728 1728 def _afterlock(self, callback):
1729 1729 """add a callback to be run when the repository is fully unlocked
1730 1730
1731 1731 The callback will be executed when the outermost lock is released
1732 1732 (with wlock being higher level than 'lock')."""
1733 1733 for ref in (self._wlockref, self._lockref):
1734 1734 l = ref and ref()
1735 1735 if l and l.held:
1736 1736 l.postrelease.append(callback)
1737 1737 break
1738 1738 else: # no lock have been found.
1739 1739 callback()
1740 1740
1741 1741 def lock(self, wait=True):
1742 1742 '''Lock the repository store (.hg/store) and return a weak reference
1743 1743 to the lock. Use this before modifying the store (e.g. committing or
1744 1744 stripping). If you are opening a transaction, get a lock as well.)
1745 1745
1746 1746 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1747 1747 'wlock' first to avoid a dead-lock hazard.'''
1748 1748 l = self._currentlock(self._lockref)
1749 1749 if l is not None:
1750 1750 l.lock()
1751 1751 return l
1752 1752
1753 1753 l = self._lock(self.svfs, "lock", wait, None,
1754 1754 self.invalidate, _('repository %s') % self.origroot)
1755 1755 self._lockref = weakref.ref(l)
1756 1756 return l
1757 1757
1758 1758 def _wlockchecktransaction(self):
1759 1759 if self.currenttransaction() is not None:
1760 1760 raise error.LockInheritanceContractViolation(
1761 1761 'wlock cannot be inherited in the middle of a transaction')
1762 1762
1763 1763 def wlock(self, wait=True):
1764 1764 '''Lock the non-store parts of the repository (everything under
1765 1765 .hg except .hg/store) and return a weak reference to the lock.
1766 1766
1767 1767 Use this before modifying files in .hg.
1768 1768
1769 1769 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1770 1770 'wlock' first to avoid a dead-lock hazard.'''
1771 1771 l = self._wlockref and self._wlockref()
1772 1772 if l is not None and l.held:
1773 1773 l.lock()
1774 1774 return l
1775 1775
1776 1776 # We do not need to check for non-waiting lock acquisition. Such
1777 1777 # acquisition would not cause dead-lock as they would just fail.
1778 1778 if wait and (self.ui.configbool('devel', 'all-warnings')
1779 1779 or self.ui.configbool('devel', 'check-locks')):
1780 1780 if self._currentlock(self._lockref) is not None:
1781 1781 self.ui.develwarn('"wlock" acquired after "lock"')
1782 1782
1783 1783 def unlock():
1784 1784 if self.dirstate.pendingparentchange():
1785 1785 self.dirstate.invalidate()
1786 1786 else:
1787 1787 self.dirstate.write(None)
1788 1788
1789 1789 self._filecache['dirstate'].refresh()
1790 1790
1791 1791 l = self._lock(self.vfs, "wlock", wait, unlock,
1792 1792 self.invalidatedirstate, _('working directory of %s') %
1793 1793 self.origroot,
1794 1794 inheritchecker=self._wlockchecktransaction,
1795 1795 parentenvvar='HG_WLOCK_LOCKER')
1796 1796 self._wlockref = weakref.ref(l)
1797 1797 return l
1798 1798
1799 1799 def _currentlock(self, lockref):
1800 1800 """Returns the lock if it's held, or None if it's not."""
1801 1801 if lockref is None:
1802 1802 return None
1803 1803 l = lockref()
1804 1804 if l is None or not l.held:
1805 1805 return None
1806 1806 return l
1807 1807
1808 1808 def currentwlock(self):
1809 1809 """Returns the wlock if it's held, or None if it's not."""
1810 1810 return self._currentlock(self._wlockref)
1811 1811
1812 1812 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1813 1813 """
1814 1814 commit an individual file as part of a larger transaction
1815 1815 """
1816 1816
1817 1817 fname = fctx.path()
1818 1818 fparent1 = manifest1.get(fname, nullid)
1819 1819 fparent2 = manifest2.get(fname, nullid)
1820 1820 if isinstance(fctx, context.filectx):
1821 1821 node = fctx.filenode()
1822 1822 if node in [fparent1, fparent2]:
1823 1823 self.ui.debug('reusing %s filelog entry\n' % fname)
1824 1824 if manifest1.flags(fname) != fctx.flags():
1825 1825 changelist.append(fname)
1826 1826 return node
1827 1827
1828 1828 flog = self.file(fname)
1829 1829 meta = {}
1830 1830 copy = fctx.renamed()
1831 1831 if copy and copy[0] != fname:
1832 1832 # Mark the new revision of this file as a copy of another
1833 1833 # file. This copy data will effectively act as a parent
1834 1834 # of this new revision. If this is a merge, the first
1835 1835 # parent will be the nullid (meaning "look up the copy data")
1836 1836 # and the second one will be the other parent. For example:
1837 1837 #
1838 1838 # 0 --- 1 --- 3 rev1 changes file foo
1839 1839 # \ / rev2 renames foo to bar and changes it
1840 1840 # \- 2 -/ rev3 should have bar with all changes and
1841 1841 # should record that bar descends from
1842 1842 # bar in rev2 and foo in rev1
1843 1843 #
1844 1844 # this allows this merge to succeed:
1845 1845 #
1846 1846 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1847 1847 # \ / merging rev3 and rev4 should use bar@rev2
1848 1848 # \- 2 --- 4 as the merge base
1849 1849 #
1850 1850
1851 1851 cfname = copy[0]
1852 1852 crev = manifest1.get(cfname)
1853 1853 newfparent = fparent2
1854 1854
1855 1855 if manifest2: # branch merge
1856 1856 if fparent2 == nullid or crev is None: # copied on remote side
1857 1857 if cfname in manifest2:
1858 1858 crev = manifest2[cfname]
1859 1859 newfparent = fparent1
1860 1860
1861 1861 # Here, we used to search backwards through history to try to find
1862 1862 # where the file copy came from if the source of a copy was not in
1863 1863 # the parent directory. However, this doesn't actually make sense to
1864 1864 # do (what does a copy from something not in your working copy even
1865 1865 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1866 1866 # the user that copy information was dropped, so if they didn't
1867 1867 # expect this outcome it can be fixed, but this is the correct
1868 1868 # behavior in this circumstance.
1869 1869
1870 1870 if crev:
1871 1871 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1872 1872 meta["copy"] = cfname
1873 1873 meta["copyrev"] = hex(crev)
1874 1874 fparent1, fparent2 = nullid, newfparent
1875 1875 else:
1876 1876 self.ui.warn(_("warning: can't find ancestor for '%s' "
1877 1877 "copied from '%s'!\n") % (fname, cfname))
1878 1878
1879 1879 elif fparent1 == nullid:
1880 1880 fparent1, fparent2 = fparent2, nullid
1881 1881 elif fparent2 != nullid:
1882 1882 # is one parent an ancestor of the other?
1883 1883 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1884 1884 if fparent1 in fparentancestors:
1885 1885 fparent1, fparent2 = fparent2, nullid
1886 1886 elif fparent2 in fparentancestors:
1887 1887 fparent2 = nullid
1888 1888
1889 1889 # is the file changed?
1890 1890 text = fctx.data()
1891 1891 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1892 1892 changelist.append(fname)
1893 1893 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1894 1894 # are just the flags changed during merge?
1895 1895 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1896 1896 changelist.append(fname)
1897 1897
1898 1898 return fparent1
1899 1899
1900 1900 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1901 1901 """check for commit arguments that aren't committable"""
1902 1902 if match.isexact() or match.prefix():
1903 1903 matched = set(status.modified + status.added + status.removed)
1904 1904
1905 1905 for f in match.files():
1906 1906 f = self.dirstate.normalize(f)
1907 1907 if f == '.' or f in matched or f in wctx.substate:
1908 1908 continue
1909 1909 if f in status.deleted:
1910 1910 fail(f, _('file not found!'))
1911 1911 if f in vdirs: # visited directory
1912 1912 d = f + '/'
1913 1913 for mf in matched:
1914 1914 if mf.startswith(d):
1915 1915 break
1916 1916 else:
1917 1917 fail(f, _("no match under directory!"))
1918 1918 elif f not in self.dirstate:
1919 1919 fail(f, _("file not tracked!"))
1920 1920
1921 1921 @unfilteredmethod
1922 1922 def commit(self, text="", user=None, date=None, match=None, force=False,
1923 1923 editor=False, extra=None):
1924 1924 """Add a new revision to current repository.
1925 1925
1926 1926 Revision information is gathered from the working directory,
1927 1927 match can be used to filter the committed files. If editor is
1928 1928 supplied, it is called to get a commit message.
1929 1929 """
1930 1930 if extra is None:
1931 1931 extra = {}
1932 1932
1933 1933 def fail(f, msg):
1934 1934 raise error.Abort('%s: %s' % (f, msg))
1935 1935
1936 1936 if not match:
1937 1937 match = matchmod.always(self.root, '')
1938 1938
1939 1939 if not force:
1940 1940 vdirs = []
1941 1941 match.explicitdir = vdirs.append
1942 1942 match.bad = fail
1943 1943
1944 1944 wlock = lock = tr = None
1945 1945 try:
1946 1946 wlock = self.wlock()
1947 1947 lock = self.lock() # for recent changelog (see issue4368)
1948 1948
1949 1949 wctx = self[None]
1950 1950 merge = len(wctx.parents()) > 1
1951 1951
1952 1952 if not force and merge and not match.always():
1953 1953 raise error.Abort(_('cannot partially commit a merge '
1954 1954 '(do not specify files or patterns)'))
1955 1955
1956 1956 status = self.status(match=match, clean=force)
1957 1957 if force:
1958 1958 status.modified.extend(status.clean) # mq may commit clean files
1959 1959
1960 1960 # check subrepos
1961 1961 subs, commitsubs, newstate = subrepoutil.precommit(
1962 1962 self.ui, wctx, status, match, force=force)
1963 1963
1964 1964 # make sure all explicit patterns are matched
1965 1965 if not force:
1966 1966 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1967 1967
1968 1968 cctx = context.workingcommitctx(self, status,
1969 1969 text, user, date, extra)
1970 1970
1971 1971 # internal config: ui.allowemptycommit
1972 1972 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1973 1973 or extra.get('close') or merge or cctx.files()
1974 1974 or self.ui.configbool('ui', 'allowemptycommit'))
1975 1975 if not allowemptycommit:
1976 1976 return None
1977 1977
1978 1978 if merge and cctx.deleted():
1979 1979 raise error.Abort(_("cannot commit merge with missing files"))
1980 1980
1981 1981 ms = mergemod.mergestate.read(self)
1982 1982 mergeutil.checkunresolved(ms)
1983 1983
1984 1984 if editor:
1985 1985 cctx._text = editor(self, cctx, subs)
1986 1986 edited = (text != cctx._text)
1987 1987
1988 1988 # Save commit message in case this transaction gets rolled back
1989 1989 # (e.g. by a pretxncommit hook). Leave the content alone on
1990 1990 # the assumption that the user will use the same editor again.
1991 1991 msgfn = self.savecommitmessage(cctx._text)
1992 1992
1993 1993 # commit subs and write new state
1994 1994 if subs:
1995 1995 for s in sorted(commitsubs):
1996 1996 sub = wctx.sub(s)
1997 1997 self.ui.status(_('committing subrepository %s\n') %
1998 1998 subrepoutil.subrelpath(sub))
1999 1999 sr = sub.commit(cctx._text, user, date)
2000 2000 newstate[s] = (newstate[s][0], sr)
2001 2001 subrepoutil.writestate(self, newstate)
2002 2002
2003 2003 p1, p2 = self.dirstate.parents()
2004 2004 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
2005 2005 try:
2006 2006 self.hook("precommit", throw=True, parent1=hookp1,
2007 2007 parent2=hookp2)
2008 2008 tr = self.transaction('commit')
2009 2009 ret = self.commitctx(cctx, True)
2010 2010 except: # re-raises
2011 2011 if edited:
2012 2012 self.ui.write(
2013 2013 _('note: commit message saved in %s\n') % msgfn)
2014 2014 raise
2015 2015 # update bookmarks, dirstate and mergestate
2016 2016 bookmarks.update(self, [p1, p2], ret)
2017 2017 cctx.markcommitted(ret)
2018 2018 ms.reset()
2019 2019 tr.close()
2020 2020
2021 2021 finally:
2022 2022 lockmod.release(tr, lock, wlock)
2023 2023
2024 2024 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
2025 2025 # hack for command that use a temporary commit (eg: histedit)
2026 2026 # temporary commit got stripped before hook release
2027 2027 if self.changelog.hasnode(ret):
2028 2028 self.hook("commit", node=node, parent1=parent1,
2029 2029 parent2=parent2)
2030 2030 self._afterlock(commithook)
2031 2031 return ret
2032 2032
2033 2033 @unfilteredmethod
2034 2034 def commitctx(self, ctx, error=False):
2035 2035 """Add a new revision to current repository.
2036 2036 Revision information is passed via the context argument.
2037 2037 """
2038 2038
2039 2039 tr = None
2040 2040 p1, p2 = ctx.p1(), ctx.p2()
2041 2041 user = ctx.user()
2042 2042
2043 2043 lock = self.lock()
2044 2044 try:
2045 2045 tr = self.transaction("commit")
2046 2046 trp = weakref.proxy(tr)
2047 2047
2048 2048 if ctx.manifestnode():
2049 2049 # reuse an existing manifest revision
2050 2050 mn = ctx.manifestnode()
2051 2051 files = ctx.files()
2052 2052 elif ctx.files():
2053 2053 m1ctx = p1.manifestctx()
2054 2054 m2ctx = p2.manifestctx()
2055 2055 mctx = m1ctx.copy()
2056 2056
2057 2057 m = mctx.read()
2058 2058 m1 = m1ctx.read()
2059 2059 m2 = m2ctx.read()
2060 2060
2061 2061 # check in files
2062 2062 added = []
2063 2063 changed = []
2064 2064 removed = list(ctx.removed())
2065 2065 linkrev = len(self)
2066 2066 self.ui.note(_("committing files:\n"))
2067 2067 for f in sorted(ctx.modified() + ctx.added()):
2068 2068 self.ui.note(f + "\n")
2069 2069 try:
2070 2070 fctx = ctx[f]
2071 2071 if fctx is None:
2072 2072 removed.append(f)
2073 2073 else:
2074 2074 added.append(f)
2075 2075 m[f] = self._filecommit(fctx, m1, m2, linkrev,
2076 2076 trp, changed)
2077 2077 m.setflag(f, fctx.flags())
2078 2078 except OSError as inst:
2079 2079 self.ui.warn(_("trouble committing %s!\n") % f)
2080 2080 raise
2081 2081 except IOError as inst:
2082 2082 errcode = getattr(inst, 'errno', errno.ENOENT)
2083 2083 if error or errcode and errcode != errno.ENOENT:
2084 2084 self.ui.warn(_("trouble committing %s!\n") % f)
2085 2085 raise
2086 2086
2087 2087 # update manifest
2088 2088 self.ui.note(_("committing manifest\n"))
2089 2089 removed = [f for f in sorted(removed) if f in m1 or f in m2]
2090 2090 drop = [f for f in removed if f in m]
2091 2091 for f in drop:
2092 2092 del m[f]
2093 2093 mn = mctx.write(trp, linkrev,
2094 2094 p1.manifestnode(), p2.manifestnode(),
2095 2095 added, drop)
2096 2096 files = changed + removed
2097 2097 else:
2098 2098 mn = p1.manifestnode()
2099 2099 files = []
2100 2100
2101 2101 # update changelog
2102 2102 self.ui.note(_("committing changelog\n"))
2103 2103 self.changelog.delayupdate(tr)
2104 2104 n = self.changelog.add(mn, files, ctx.description(),
2105 2105 trp, p1.node(), p2.node(),
2106 2106 user, ctx.date(), ctx.extra().copy())
2107 2107 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
2108 2108 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
2109 2109 parent2=xp2)
2110 2110 # set the new commit is proper phase
2111 2111 targetphase = subrepoutil.newcommitphase(self.ui, ctx)
2112 2112 if targetphase:
2113 2113 # retract boundary do not alter parent changeset.
2114 2114 # if a parent have higher the resulting phase will
2115 2115 # be compliant anyway
2116 2116 #
2117 2117 # if minimal phase was 0 we don't need to retract anything
2118 2118 phases.registernew(self, tr, targetphase, [n])
2119 2119 tr.close()
2120 2120 return n
2121 2121 finally:
2122 2122 if tr:
2123 2123 tr.release()
2124 2124 lock.release()
2125 2125
2126 2126 @unfilteredmethod
2127 2127 def destroying(self):
2128 2128 '''Inform the repository that nodes are about to be destroyed.
2129 2129 Intended for use by strip and rollback, so there's a common
2130 2130 place for anything that has to be done before destroying history.
2131 2131
2132 2132 This is mostly useful for saving state that is in memory and waiting
2133 2133 to be flushed when the current lock is released. Because a call to
2134 2134 destroyed is imminent, the repo will be invalidated causing those
2135 2135 changes to stay in memory (waiting for the next unlock), or vanish
2136 2136 completely.
2137 2137 '''
2138 2138 # When using the same lock to commit and strip, the phasecache is left
2139 2139 # dirty after committing. Then when we strip, the repo is invalidated,
2140 2140 # causing those changes to disappear.
2141 2141 if '_phasecache' in vars(self):
2142 2142 self._phasecache.write()
2143 2143
2144 2144 @unfilteredmethod
2145 2145 def destroyed(self):
2146 2146 '''Inform the repository that nodes have been destroyed.
2147 2147 Intended for use by strip and rollback, so there's a common
2148 2148 place for anything that has to be done after destroying history.
2149 2149 '''
2150 2150 # When one tries to:
2151 2151 # 1) destroy nodes thus calling this method (e.g. strip)
2152 2152 # 2) use phasecache somewhere (e.g. commit)
2153 2153 #
2154 2154 # then 2) will fail because the phasecache contains nodes that were
2155 2155 # removed. We can either remove phasecache from the filecache,
2156 2156 # causing it to reload next time it is accessed, or simply filter
2157 2157 # the removed nodes now and write the updated cache.
2158 2158 self._phasecache.filterunknown(self)
2159 2159 self._phasecache.write()
2160 2160
2161 2161 # refresh all repository caches
2162 2162 self.updatecaches()
2163 2163
2164 2164 # Ensure the persistent tag cache is updated. Doing it now
2165 2165 # means that the tag cache only has to worry about destroyed
2166 2166 # heads immediately after a strip/rollback. That in turn
2167 2167 # guarantees that "cachetip == currenttip" (comparing both rev
2168 2168 # and node) always means no nodes have been added or destroyed.
2169 2169
2170 2170 # XXX this is suboptimal when qrefresh'ing: we strip the current
2171 2171 # head, refresh the tag cache, then immediately add a new head.
2172 2172 # But I think doing it this way is necessary for the "instant
2173 2173 # tag cache retrieval" case to work.
2174 2174 self.invalidate()
2175 2175
2176 2176 def status(self, node1='.', node2=None, match=None,
2177 2177 ignored=False, clean=False, unknown=False,
2178 2178 listsubrepos=False):
2179 2179 '''a convenience method that calls node1.status(node2)'''
2180 2180 return self[node1].status(node2, match, ignored, clean, unknown,
2181 2181 listsubrepos)
2182 2182
2183 2183 def addpostdsstatus(self, ps):
2184 2184 """Add a callback to run within the wlock, at the point at which status
2185 2185 fixups happen.
2186 2186
2187 2187 On status completion, callback(wctx, status) will be called with the
2188 2188 wlock held, unless the dirstate has changed from underneath or the wlock
2189 2189 couldn't be grabbed.
2190 2190
2191 2191 Callbacks should not capture and use a cached copy of the dirstate --
2192 2192 it might change in the meanwhile. Instead, they should access the
2193 2193 dirstate via wctx.repo().dirstate.
2194 2194
2195 2195 This list is emptied out after each status run -- extensions should
2196 2196 make sure it adds to this list each time dirstate.status is called.
2197 2197 Extensions should also make sure they don't call this for statuses
2198 2198 that don't involve the dirstate.
2199 2199 """
2200 2200
2201 2201 # The list is located here for uniqueness reasons -- it is actually
2202 2202 # managed by the workingctx, but that isn't unique per-repo.
2203 2203 self._postdsstatus.append(ps)
2204 2204
2205 2205 def postdsstatus(self):
2206 2206 """Used by workingctx to get the list of post-dirstate-status hooks."""
2207 2207 return self._postdsstatus
2208 2208
2209 2209 def clearpostdsstatus(self):
2210 2210 """Used by workingctx to clear post-dirstate-status hooks."""
2211 2211 del self._postdsstatus[:]
2212 2212
2213 2213 def heads(self, start=None):
2214 2214 if start is None:
2215 2215 cl = self.changelog
2216 2216 headrevs = reversed(cl.headrevs())
2217 2217 return [cl.node(rev) for rev in headrevs]
2218 2218
2219 2219 heads = self.changelog.heads(start)
2220 2220 # sort the output in rev descending order
2221 2221 return sorted(heads, key=self.changelog.rev, reverse=True)
2222 2222
2223 2223 def branchheads(self, branch=None, start=None, closed=False):
2224 2224 '''return a (possibly filtered) list of heads for the given branch
2225 2225
2226 2226 Heads are returned in topological order, from newest to oldest.
2227 2227 If branch is None, use the dirstate branch.
2228 2228 If start is not None, return only heads reachable from start.
2229 2229 If closed is True, return heads that are marked as closed as well.
2230 2230 '''
2231 2231 if branch is None:
2232 2232 branch = self[None].branch()
2233 2233 branches = self.branchmap()
2234 2234 if branch not in branches:
2235 2235 return []
2236 2236 # the cache returns heads ordered lowest to highest
2237 2237 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2238 2238 if start is not None:
2239 2239 # filter out the heads that cannot be reached from startrev
2240 2240 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2241 2241 bheads = [h for h in bheads if h in fbheads]
2242 2242 return bheads
2243 2243
2244 2244 def branches(self, nodes):
2245 2245 if not nodes:
2246 2246 nodes = [self.changelog.tip()]
2247 2247 b = []
2248 2248 for n in nodes:
2249 2249 t = n
2250 2250 while True:
2251 2251 p = self.changelog.parents(n)
2252 2252 if p[1] != nullid or p[0] == nullid:
2253 2253 b.append((t, n, p[0], p[1]))
2254 2254 break
2255 2255 n = p[0]
2256 2256 return b
2257 2257
2258 2258 def between(self, pairs):
2259 2259 r = []
2260 2260
2261 2261 for top, bottom in pairs:
2262 2262 n, l, i = top, [], 0
2263 2263 f = 1
2264 2264
2265 2265 while n != bottom and n != nullid:
2266 2266 p = self.changelog.parents(n)[0]
2267 2267 if i == f:
2268 2268 l.append(n)
2269 2269 f = f * 2
2270 2270 n = p
2271 2271 i += 1
2272 2272
2273 2273 r.append(l)
2274 2274
2275 2275 return r
2276 2276
2277 2277 def checkpush(self, pushop):
2278 2278 """Extensions can override this function if additional checks have
2279 2279 to be performed before pushing, or call it if they override push
2280 2280 command.
2281 2281 """
2282 2282
2283 2283 @unfilteredpropertycache
2284 2284 def prepushoutgoinghooks(self):
2285 2285 """Return util.hooks consists of a pushop with repo, remote, outgoing
2286 2286 methods, which are called before pushing changesets.
2287 2287 """
2288 2288 return util.hooks()
2289 2289
2290 2290 def pushkey(self, namespace, key, old, new):
2291 2291 try:
2292 2292 tr = self.currenttransaction()
2293 2293 hookargs = {}
2294 2294 if tr is not None:
2295 2295 hookargs.update(tr.hookargs)
2296 2296 hookargs = pycompat.strkwargs(hookargs)
2297 2297 hookargs[r'namespace'] = namespace
2298 2298 hookargs[r'key'] = key
2299 2299 hookargs[r'old'] = old
2300 2300 hookargs[r'new'] = new
2301 2301 self.hook('prepushkey', throw=True, **hookargs)
2302 2302 except error.HookAbort as exc:
2303 2303 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2304 2304 if exc.hint:
2305 2305 self.ui.write_err(_("(%s)\n") % exc.hint)
2306 2306 return False
2307 2307 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2308 2308 ret = pushkey.push(self, namespace, key, old, new)
2309 2309 def runhook():
2310 2310 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2311 2311 ret=ret)
2312 2312 self._afterlock(runhook)
2313 2313 return ret
2314 2314
2315 2315 def listkeys(self, namespace):
2316 2316 self.hook('prelistkeys', throw=True, namespace=namespace)
2317 2317 self.ui.debug('listing keys for "%s"\n' % namespace)
2318 2318 values = pushkey.list(self, namespace)
2319 2319 self.hook('listkeys', namespace=namespace, values=values)
2320 2320 return values
2321 2321
2322 2322 def debugwireargs(self, one, two, three=None, four=None, five=None):
2323 2323 '''used to test argument passing over the wire'''
2324 2324 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
2325 2325 pycompat.bytestr(four),
2326 2326 pycompat.bytestr(five))
2327 2327
2328 2328 def savecommitmessage(self, text):
2329 2329 fp = self.vfs('last-message.txt', 'wb')
2330 2330 try:
2331 2331 fp.write(text)
2332 2332 finally:
2333 2333 fp.close()
2334 2334 return self.pathto(fp.name[len(self.root) + 1:])
2335 2335
2336 2336 # used to avoid circular references so destructors work
2337 2337 def aftertrans(files):
2338 2338 renamefiles = [tuple(t) for t in files]
2339 2339 def a():
2340 2340 for vfs, src, dest in renamefiles:
2341 2341 # if src and dest refer to a same file, vfs.rename is a no-op,
2342 2342 # leaving both src and dest on disk. delete dest to make sure
2343 2343 # the rename couldn't be such a no-op.
2344 2344 vfs.tryunlink(dest)
2345 2345 try:
2346 2346 vfs.rename(src, dest)
2347 2347 except OSError: # journal file does not yet exist
2348 2348 pass
2349 2349 return a
2350 2350
2351 2351 def undoname(fn):
2352 2352 base, name = os.path.split(fn)
2353 2353 assert name.startswith('journal')
2354 2354 return os.path.join(base, name.replace('journal', 'undo', 1))
2355 2355
2356 2356 def instance(ui, path, create, intents=None):
2357 2357 return localrepository(ui, util.urllocalpath(path), create,
2358 2358 intents=intents)
2359 2359
2360 2360 def islocal(path):
2361 2361 return True
2362 2362
2363 2363 def newreporequirements(repo):
2364 2364 """Determine the set of requirements for a new local repository.
2365 2365
2366 2366 Extensions can wrap this function to specify custom requirements for
2367 2367 new repositories.
2368 2368 """
2369 2369 ui = repo.ui
2370 2370 requirements = {'revlogv1'}
2371 2371 if ui.configbool('format', 'usestore'):
2372 2372 requirements.add('store')
2373 2373 if ui.configbool('format', 'usefncache'):
2374 2374 requirements.add('fncache')
2375 2375 if ui.configbool('format', 'dotencode'):
2376 2376 requirements.add('dotencode')
2377 2377
2378 2378 compengine = ui.config('experimental', 'format.compression')
2379 2379 if compengine not in util.compengines:
2380 2380 raise error.Abort(_('compression engine %s defined by '
2381 2381 'experimental.format.compression not available') %
2382 2382 compengine,
2383 2383 hint=_('run "hg debuginstall" to list available '
2384 2384 'compression engines'))
2385 2385
2386 2386 # zlib is the historical default and doesn't need an explicit requirement.
2387 2387 if compengine != 'zlib':
2388 2388 requirements.add('exp-compression-%s' % compengine)
2389 2389
2390 2390 if scmutil.gdinitconfig(ui):
2391 2391 requirements.add('generaldelta')
2392 2392 if ui.configbool('experimental', 'treemanifest'):
2393 2393 requirements.add('treemanifest')
2394 2394 # experimental config: format.sparse-revlog
2395 2395 if ui.configbool('format', 'sparse-revlog'):
2396 2396 requirements.add(SPARSEREVLOG_REQUIREMENT)
2397 2397
2398 2398 revlogv2 = ui.config('experimental', 'revlogv2')
2399 2399 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2400 2400 requirements.remove('revlogv1')
2401 2401 # generaldelta is implied by revlogv2.
2402 2402 requirements.discard('generaldelta')
2403 2403 requirements.add(REVLOGV2_REQUIREMENT)
2404 2404
2405 2405 return requirements
@@ -1,198 +1,198 b''
1 1 # narrowspec.py - methods for working with a narrow view of a repository
2 2 #
3 3 # Copyright 2017 Google, Inc.
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 __future__ import absolute_import
9 9
10 10 import errno
11 11
12 12 from .i18n import _
13 13 from . import (
14 14 error,
15 15 match as matchmod,
16 16 repository,
17 17 sparse,
18 18 util,
19 19 )
20 20
21 21 FILENAME = 'narrowspec'
22 22
23 23 def parseserverpatterns(text):
24 24 """Parses the narrowspec format that's returned by the server."""
25 25 includepats = set()
26 26 excludepats = set()
27 27
28 28 # We get one entry per line, in the format "<key> <value>".
29 29 # It's OK for value to contain other spaces.
30 30 for kp in (l.split(' ', 1) for l in text.splitlines()):
31 31 if len(kp) != 2:
32 32 raise error.Abort(_('Invalid narrowspec pattern line: "%s"') % kp)
33 33 key = kp[0]
34 34 pat = kp[1]
35 35 if key == 'include':
36 36 includepats.add(pat)
37 37 elif key == 'exclude':
38 38 excludepats.add(pat)
39 39 else:
40 40 raise error.Abort(_('Invalid key "%s" in server response') % key)
41 41
42 42 return includepats, excludepats
43 43
44 44 def normalizesplitpattern(kind, pat):
45 45 """Returns the normalized version of a pattern and kind.
46 46
47 47 Returns a tuple with the normalized kind and normalized pattern.
48 48 """
49 49 pat = pat.rstrip('/')
50 50 _validatepattern(pat)
51 51 return kind, pat
52 52
53 53 def _numlines(s):
54 54 """Returns the number of lines in s, including ending empty lines."""
55 55 # We use splitlines because it is Unicode-friendly and thus Python 3
56 56 # compatible. However, it does not count empty lines at the end, so trick
57 57 # it by adding a character at the end.
58 58 return len((s + 'x').splitlines())
59 59
60 60 def _validatepattern(pat):
61 61 """Validates the pattern and aborts if it is invalid.
62 62
63 63 Patterns are stored in the narrowspec as newline-separated
64 64 POSIX-style bytestring paths. There's no escaping.
65 65 """
66 66
67 67 # We use newlines as separators in the narrowspec file, so don't allow them
68 68 # in patterns.
69 69 if _numlines(pat) > 1:
70 70 raise error.Abort(_('newlines are not allowed in narrowspec paths'))
71 71
72 72 components = pat.split('/')
73 73 if '.' in components or '..' in components:
74 74 raise error.Abort(_('"." and ".." are not allowed in narrowspec paths'))
75 75
76 76 def normalizepattern(pattern, defaultkind='path'):
77 77 """Returns the normalized version of a text-format pattern.
78 78
79 79 If the pattern has no kind, the default will be added.
80 80 """
81 81 kind, pat = matchmod._patsplit(pattern, defaultkind)
82 82 return '%s:%s' % normalizesplitpattern(kind, pat)
83 83
84 84 def parsepatterns(pats):
85 85 """Parses a list of patterns into a typed pattern set."""
86 86 return set(normalizepattern(p) for p in pats)
87 87
88 88 def format(includes, excludes):
89 89 output = '[include]\n'
90 90 for i in sorted(includes - excludes):
91 91 output += i + '\n'
92 92 output += '[exclude]\n'
93 93 for e in sorted(excludes):
94 94 output += e + '\n'
95 95 return output
96 96
97 97 def match(root, include=None, exclude=None):
98 98 if not include:
99 99 # Passing empty include and empty exclude to matchmod.match()
100 100 # gives a matcher that matches everything, so explicitly use
101 101 # the nevermatcher.
102 102 return matchmod.never(root, '')
103 103 return matchmod.match(root, '', [], include=include or [],
104 104 exclude=exclude or [])
105 105
106 106 def needsexpansion(includes):
107 107 return [i for i in includes if i.startswith('include:')]
108 108
109 109 def load(repo):
110 110 try:
111 spec = repo.vfs.read(FILENAME)
111 spec = repo.svfs.read(FILENAME)
112 112 except IOError as e:
113 113 # Treat "narrowspec does not exist" the same as "narrowspec file exists
114 114 # and is empty".
115 115 if e.errno == errno.ENOENT:
116 116 return set(), set()
117 117 raise
118 118 # maybe we should care about the profiles returned too
119 119 includepats, excludepats, profiles = sparse.parseconfig(repo.ui, spec,
120 120 'narrow')
121 121 if profiles:
122 122 raise error.Abort(_("including other spec files using '%include' is not"
123 123 " suported in narrowspec"))
124 124 return includepats, excludepats
125 125
126 126 def save(repo, includepats, excludepats):
127 127 spec = format(includepats, excludepats)
128 repo.vfs.write(FILENAME, spec)
128 repo.svfs.write(FILENAME, spec)
129 129
130 130 def savebackup(repo, backupname):
131 131 if repository.NARROW_REQUIREMENT not in repo.requirements:
132 132 return
133 133 vfs = repo.vfs
134 134 vfs.tryunlink(backupname)
135 util.copyfile(vfs.join(FILENAME), vfs.join(backupname), hardlink=True)
135 util.copyfile(repo.svfs.join(FILENAME), vfs.join(backupname), hardlink=True)
136 136
137 137 def restorebackup(repo, backupname):
138 138 if repository.NARROW_REQUIREMENT not in repo.requirements:
139 139 return
140 repo.vfs.rename(backupname, FILENAME)
140 util.rename(repo.vfs.join(backupname), repo.svfs.join(FILENAME))
141 141
142 142 def clearbackup(repo, backupname):
143 143 if repository.NARROW_REQUIREMENT not in repo.requirements:
144 144 return
145 145 repo.vfs.unlink(backupname)
146 146
147 147 def restrictpatterns(req_includes, req_excludes, repo_includes, repo_excludes):
148 148 r""" Restricts the patterns according to repo settings,
149 149 results in a logical AND operation
150 150
151 151 :param req_includes: requested includes
152 152 :param req_excludes: requested excludes
153 153 :param repo_includes: repo includes
154 154 :param repo_excludes: repo excludes
155 155 :return: include patterns, exclude patterns, and invalid include patterns.
156 156
157 157 >>> restrictpatterns({'f1','f2'}, {}, ['f1'], [])
158 158 (set(['f1']), {}, [])
159 159 >>> restrictpatterns({'f1'}, {}, ['f1','f2'], [])
160 160 (set(['f1']), {}, [])
161 161 >>> restrictpatterns({'f1/fc1', 'f3/fc3'}, {}, ['f1','f2'], [])
162 162 (set(['f1/fc1']), {}, [])
163 163 >>> restrictpatterns({'f1_fc1'}, {}, ['f1','f2'], [])
164 164 ([], set(['path:.']), [])
165 165 >>> restrictpatterns({'f1/../f2/fc2'}, {}, ['f1','f2'], [])
166 166 (set(['f2/fc2']), {}, [])
167 167 >>> restrictpatterns({'f1/../f3/fc3'}, {}, ['f1','f2'], [])
168 168 ([], set(['path:.']), [])
169 169 >>> restrictpatterns({'f1/$non_exitent_var'}, {}, ['f1','f2'], [])
170 170 (set(['f1/$non_exitent_var']), {}, [])
171 171 """
172 172 res_excludes = set(req_excludes)
173 173 res_excludes.update(repo_excludes)
174 174 invalid_includes = []
175 175 if not req_includes:
176 176 res_includes = set(repo_includes)
177 177 elif 'path:.' not in repo_includes:
178 178 res_includes = []
179 179 for req_include in req_includes:
180 180 req_include = util.expandpath(util.normpath(req_include))
181 181 if req_include in repo_includes:
182 182 res_includes.append(req_include)
183 183 continue
184 184 valid = False
185 185 for repo_include in repo_includes:
186 186 if req_include.startswith(repo_include + '/'):
187 187 valid = True
188 188 res_includes.append(req_include)
189 189 break
190 190 if not valid:
191 191 invalid_includes.append(req_include)
192 192 if len(res_includes) == 0:
193 193 res_excludes = {'path:.'}
194 194 else:
195 195 res_includes = set(res_includes)
196 196 else:
197 197 res_includes = set(req_includes)
198 198 return res_includes, res_excludes, invalid_includes
@@ -1,594 +1,594 b''
1 1 # store.py - repository store handling for Mercurial
2 2 #
3 3 # Copyright 2008 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 __future__ import absolute_import
9 9
10 10 import errno
11 11 import hashlib
12 12 import os
13 13 import stat
14 14
15 15 from .i18n import _
16 16 from . import (
17 17 error,
18 18 node,
19 19 policy,
20 20 pycompat,
21 21 util,
22 22 vfs as vfsmod,
23 23 )
24 24
25 25 parsers = policy.importmod(r'parsers')
26 26
27 27 # This avoids a collision between a file named foo and a dir named
28 28 # foo.i or foo.d
29 29 def _encodedir(path):
30 30 '''
31 31 >>> _encodedir(b'data/foo.i')
32 32 'data/foo.i'
33 33 >>> _encodedir(b'data/foo.i/bla.i')
34 34 'data/foo.i.hg/bla.i'
35 35 >>> _encodedir(b'data/foo.i.hg/bla.i')
36 36 'data/foo.i.hg.hg/bla.i'
37 37 >>> _encodedir(b'data/foo.i\\ndata/foo.i/bla.i\\ndata/foo.i.hg/bla.i\\n')
38 38 'data/foo.i\\ndata/foo.i.hg/bla.i\\ndata/foo.i.hg.hg/bla.i\\n'
39 39 '''
40 40 return (path
41 41 .replace(".hg/", ".hg.hg/")
42 42 .replace(".i/", ".i.hg/")
43 43 .replace(".d/", ".d.hg/"))
44 44
45 45 encodedir = getattr(parsers, 'encodedir', _encodedir)
46 46
47 47 def decodedir(path):
48 48 '''
49 49 >>> decodedir(b'data/foo.i')
50 50 'data/foo.i'
51 51 >>> decodedir(b'data/foo.i.hg/bla.i')
52 52 'data/foo.i/bla.i'
53 53 >>> decodedir(b'data/foo.i.hg.hg/bla.i')
54 54 'data/foo.i.hg/bla.i'
55 55 '''
56 56 if ".hg/" not in path:
57 57 return path
58 58 return (path
59 59 .replace(".d.hg/", ".d/")
60 60 .replace(".i.hg/", ".i/")
61 61 .replace(".hg.hg/", ".hg/"))
62 62
63 63 def _reserved():
64 64 ''' characters that are problematic for filesystems
65 65
66 66 * ascii escapes (0..31)
67 67 * ascii hi (126..255)
68 68 * windows specials
69 69
70 70 these characters will be escaped by encodefunctions
71 71 '''
72 72 winreserved = [ord(x) for x in u'\\:*?"<>|']
73 73 for x in range(32):
74 74 yield x
75 75 for x in range(126, 256):
76 76 yield x
77 77 for x in winreserved:
78 78 yield x
79 79
80 80 def _buildencodefun():
81 81 '''
82 82 >>> enc, dec = _buildencodefun()
83 83
84 84 >>> enc(b'nothing/special.txt')
85 85 'nothing/special.txt'
86 86 >>> dec(b'nothing/special.txt')
87 87 'nothing/special.txt'
88 88
89 89 >>> enc(b'HELLO')
90 90 '_h_e_l_l_o'
91 91 >>> dec(b'_h_e_l_l_o')
92 92 'HELLO'
93 93
94 94 >>> enc(b'hello:world?')
95 95 'hello~3aworld~3f'
96 96 >>> dec(b'hello~3aworld~3f')
97 97 'hello:world?'
98 98
99 99 >>> enc(b'the\\x07quick\\xADshot')
100 100 'the~07quick~adshot'
101 101 >>> dec(b'the~07quick~adshot')
102 102 'the\\x07quick\\xadshot'
103 103 '''
104 104 e = '_'
105 105 xchr = pycompat.bytechr
106 106 asciistr = list(map(xchr, range(127)))
107 107 capitals = list(range(ord("A"), ord("Z") + 1))
108 108
109 109 cmap = dict((x, x) for x in asciistr)
110 110 for x in _reserved():
111 111 cmap[xchr(x)] = "~%02x" % x
112 112 for x in capitals + [ord(e)]:
113 113 cmap[xchr(x)] = e + xchr(x).lower()
114 114
115 115 dmap = {}
116 116 for k, v in cmap.iteritems():
117 117 dmap[v] = k
118 118 def decode(s):
119 119 i = 0
120 120 while i < len(s):
121 121 for l in pycompat.xrange(1, 4):
122 122 try:
123 123 yield dmap[s[i:i + l]]
124 124 i += l
125 125 break
126 126 except KeyError:
127 127 pass
128 128 else:
129 129 raise KeyError
130 130 return (lambda s: ''.join([cmap[s[c:c + 1]]
131 131 for c in pycompat.xrange(len(s))]),
132 132 lambda s: ''.join(list(decode(s))))
133 133
134 134 _encodefname, _decodefname = _buildencodefun()
135 135
136 136 def encodefilename(s):
137 137 '''
138 138 >>> encodefilename(b'foo.i/bar.d/bla.hg/hi:world?/HELLO')
139 139 'foo.i.hg/bar.d.hg/bla.hg.hg/hi~3aworld~3f/_h_e_l_l_o'
140 140 '''
141 141 return _encodefname(encodedir(s))
142 142
143 143 def decodefilename(s):
144 144 '''
145 145 >>> decodefilename(b'foo.i.hg/bar.d.hg/bla.hg.hg/hi~3aworld~3f/_h_e_l_l_o')
146 146 'foo.i/bar.d/bla.hg/hi:world?/HELLO'
147 147 '''
148 148 return decodedir(_decodefname(s))
149 149
150 150 def _buildlowerencodefun():
151 151 '''
152 152 >>> f = _buildlowerencodefun()
153 153 >>> f(b'nothing/special.txt')
154 154 'nothing/special.txt'
155 155 >>> f(b'HELLO')
156 156 'hello'
157 157 >>> f(b'hello:world?')
158 158 'hello~3aworld~3f'
159 159 >>> f(b'the\\x07quick\\xADshot')
160 160 'the~07quick~adshot'
161 161 '''
162 162 xchr = pycompat.bytechr
163 163 cmap = dict([(xchr(x), xchr(x)) for x in pycompat.xrange(127)])
164 164 for x in _reserved():
165 165 cmap[xchr(x)] = "~%02x" % x
166 166 for x in range(ord("A"), ord("Z") + 1):
167 167 cmap[xchr(x)] = xchr(x).lower()
168 168 def lowerencode(s):
169 169 return "".join([cmap[c] for c in pycompat.iterbytestr(s)])
170 170 return lowerencode
171 171
172 172 lowerencode = getattr(parsers, 'lowerencode', None) or _buildlowerencodefun()
173 173
174 174 # Windows reserved names: con, prn, aux, nul, com1..com9, lpt1..lpt9
175 175 _winres3 = ('aux', 'con', 'prn', 'nul') # length 3
176 176 _winres4 = ('com', 'lpt') # length 4 (with trailing 1..9)
177 177 def _auxencode(path, dotencode):
178 178 '''
179 179 Encodes filenames containing names reserved by Windows or which end in
180 180 period or space. Does not touch other single reserved characters c.
181 181 Specifically, c in '\\:*?"<>|' or ord(c) <= 31 are *not* encoded here.
182 182 Additionally encodes space or period at the beginning, if dotencode is
183 183 True. Parameter path is assumed to be all lowercase.
184 184 A segment only needs encoding if a reserved name appears as a
185 185 basename (e.g. "aux", "aux.foo"). A directory or file named "foo.aux"
186 186 doesn't need encoding.
187 187
188 188 >>> s = b'.foo/aux.txt/txt.aux/con/prn/nul/foo.'
189 189 >>> _auxencode(s.split(b'/'), True)
190 190 ['~2efoo', 'au~78.txt', 'txt.aux', 'co~6e', 'pr~6e', 'nu~6c', 'foo~2e']
191 191 >>> s = b'.com1com2/lpt9.lpt4.lpt1/conprn/com0/lpt0/foo.'
192 192 >>> _auxencode(s.split(b'/'), False)
193 193 ['.com1com2', 'lp~749.lpt4.lpt1', 'conprn', 'com0', 'lpt0', 'foo~2e']
194 194 >>> _auxencode([b'foo. '], True)
195 195 ['foo.~20']
196 196 >>> _auxencode([b' .foo'], True)
197 197 ['~20.foo']
198 198 '''
199 199 for i, n in enumerate(path):
200 200 if not n:
201 201 continue
202 202 if dotencode and n[0] in '. ':
203 203 n = "~%02x" % ord(n[0:1]) + n[1:]
204 204 path[i] = n
205 205 else:
206 206 l = n.find('.')
207 207 if l == -1:
208 208 l = len(n)
209 209 if ((l == 3 and n[:3] in _winres3) or
210 210 (l == 4 and n[3:4] <= '9' and n[3:4] >= '1'
211 211 and n[:3] in _winres4)):
212 212 # encode third letter ('aux' -> 'au~78')
213 213 ec = "~%02x" % ord(n[2:3])
214 214 n = n[0:2] + ec + n[3:]
215 215 path[i] = n
216 216 if n[-1] in '. ':
217 217 # encode last period or space ('foo...' -> 'foo..~2e')
218 218 path[i] = n[:-1] + "~%02x" % ord(n[-1:])
219 219 return path
220 220
221 221 _maxstorepathlen = 120
222 222 _dirprefixlen = 8
223 223 _maxshortdirslen = 8 * (_dirprefixlen + 1) - 4
224 224
225 225 def _hashencode(path, dotencode):
226 226 digest = node.hex(hashlib.sha1(path).digest())
227 227 le = lowerencode(path[5:]).split('/') # skips prefix 'data/' or 'meta/'
228 228 parts = _auxencode(le, dotencode)
229 229 basename = parts[-1]
230 230 _root, ext = os.path.splitext(basename)
231 231 sdirs = []
232 232 sdirslen = 0
233 233 for p in parts[:-1]:
234 234 d = p[:_dirprefixlen]
235 235 if d[-1] in '. ':
236 236 # Windows can't access dirs ending in period or space
237 237 d = d[:-1] + '_'
238 238 if sdirslen == 0:
239 239 t = len(d)
240 240 else:
241 241 t = sdirslen + 1 + len(d)
242 242 if t > _maxshortdirslen:
243 243 break
244 244 sdirs.append(d)
245 245 sdirslen = t
246 246 dirs = '/'.join(sdirs)
247 247 if len(dirs) > 0:
248 248 dirs += '/'
249 249 res = 'dh/' + dirs + digest + ext
250 250 spaceleft = _maxstorepathlen - len(res)
251 251 if spaceleft > 0:
252 252 filler = basename[:spaceleft]
253 253 res = 'dh/' + dirs + filler + digest + ext
254 254 return res
255 255
256 256 def _hybridencode(path, dotencode):
257 257 '''encodes path with a length limit
258 258
259 259 Encodes all paths that begin with 'data/', according to the following.
260 260
261 261 Default encoding (reversible):
262 262
263 263 Encodes all uppercase letters 'X' as '_x'. All reserved or illegal
264 264 characters are encoded as '~xx', where xx is the two digit hex code
265 265 of the character (see encodefilename).
266 266 Relevant path components consisting of Windows reserved filenames are
267 267 masked by encoding the third character ('aux' -> 'au~78', see _auxencode).
268 268
269 269 Hashed encoding (not reversible):
270 270
271 271 If the default-encoded path is longer than _maxstorepathlen, a
272 272 non-reversible hybrid hashing of the path is done instead.
273 273 This encoding uses up to _dirprefixlen characters of all directory
274 274 levels of the lowerencoded path, but not more levels than can fit into
275 275 _maxshortdirslen.
276 276 Then follows the filler followed by the sha digest of the full path.
277 277 The filler is the beginning of the basename of the lowerencoded path
278 278 (the basename is everything after the last path separator). The filler
279 279 is as long as possible, filling in characters from the basename until
280 280 the encoded path has _maxstorepathlen characters (or all chars of the
281 281 basename have been taken).
282 282 The extension (e.g. '.i' or '.d') is preserved.
283 283
284 284 The string 'data/' at the beginning is replaced with 'dh/', if the hashed
285 285 encoding was used.
286 286 '''
287 287 path = encodedir(path)
288 288 ef = _encodefname(path).split('/')
289 289 res = '/'.join(_auxencode(ef, dotencode))
290 290 if len(res) > _maxstorepathlen:
291 291 res = _hashencode(path, dotencode)
292 292 return res
293 293
294 294 def _pathencode(path):
295 295 de = encodedir(path)
296 296 if len(path) > _maxstorepathlen:
297 297 return _hashencode(de, True)
298 298 ef = _encodefname(de).split('/')
299 299 res = '/'.join(_auxencode(ef, True))
300 300 if len(res) > _maxstorepathlen:
301 301 return _hashencode(de, True)
302 302 return res
303 303
304 304 _pathencode = getattr(parsers, 'pathencode', _pathencode)
305 305
306 306 def _plainhybridencode(f):
307 307 return _hybridencode(f, False)
308 308
309 309 def _calcmode(vfs):
310 310 try:
311 311 # files in .hg/ will be created using this mode
312 312 mode = vfs.stat().st_mode
313 313 # avoid some useless chmods
314 314 if (0o777 & ~util.umask) == (0o777 & mode):
315 315 mode = None
316 316 except OSError:
317 317 mode = None
318 318 return mode
319 319
320 _data = ('data meta 00manifest.d 00manifest.i 00changelog.d 00changelog.i'
321 ' phaseroots obsstore')
320 _data = ('narrowspec data meta 00manifest.d 00manifest.i'
321 ' 00changelog.d 00changelog.i phaseroots obsstore')
322 322
323 323 def isrevlog(f, kind, st):
324 324 return kind == stat.S_IFREG and f[-2:] in ('.i', '.d')
325 325
326 326 class basicstore(object):
327 327 '''base class for local repository stores'''
328 328 def __init__(self, path, vfstype):
329 329 vfs = vfstype(path)
330 330 self.path = vfs.base
331 331 self.createmode = _calcmode(vfs)
332 332 vfs.createmode = self.createmode
333 333 self.rawvfs = vfs
334 334 self.vfs = vfsmod.filtervfs(vfs, encodedir)
335 335 self.opener = self.vfs
336 336
337 337 def join(self, f):
338 338 return self.path + '/' + encodedir(f)
339 339
340 340 def _walk(self, relpath, recurse, filefilter=isrevlog):
341 341 '''yields (unencoded, encoded, size)'''
342 342 path = self.path
343 343 if relpath:
344 344 path += '/' + relpath
345 345 striplen = len(self.path) + 1
346 346 l = []
347 347 if self.rawvfs.isdir(path):
348 348 visit = [path]
349 349 readdir = self.rawvfs.readdir
350 350 while visit:
351 351 p = visit.pop()
352 352 for f, kind, st in readdir(p, stat=True):
353 353 fp = p + '/' + f
354 354 if filefilter(f, kind, st):
355 355 n = util.pconvert(fp[striplen:])
356 356 l.append((decodedir(n), n, st.st_size))
357 357 elif kind == stat.S_IFDIR and recurse:
358 358 visit.append(fp)
359 359 l.sort()
360 360 return l
361 361
362 362 def datafiles(self):
363 363 return self._walk('data', True) + self._walk('meta', True)
364 364
365 365 def topfiles(self):
366 366 # yield manifest before changelog
367 367 return reversed(self._walk('', False))
368 368
369 369 def walk(self):
370 370 '''yields (unencoded, encoded, size)'''
371 371 # yield data files first
372 372 for x in self.datafiles():
373 373 yield x
374 374 for x in self.topfiles():
375 375 yield x
376 376
377 377 def copylist(self):
378 378 return ['requires'] + _data.split()
379 379
380 380 def write(self, tr):
381 381 pass
382 382
383 383 def invalidatecaches(self):
384 384 pass
385 385
386 386 def markremoved(self, fn):
387 387 pass
388 388
389 389 def __contains__(self, path):
390 390 '''Checks if the store contains path'''
391 391 path = "/".join(("data", path))
392 392 # file?
393 393 if self.vfs.exists(path + ".i"):
394 394 return True
395 395 # dir?
396 396 if not path.endswith("/"):
397 397 path = path + "/"
398 398 return self.vfs.exists(path)
399 399
400 400 class encodedstore(basicstore):
401 401 def __init__(self, path, vfstype):
402 402 vfs = vfstype(path + '/store')
403 403 self.path = vfs.base
404 404 self.createmode = _calcmode(vfs)
405 405 vfs.createmode = self.createmode
406 406 self.rawvfs = vfs
407 407 self.vfs = vfsmod.filtervfs(vfs, encodefilename)
408 408 self.opener = self.vfs
409 409
410 410 def datafiles(self):
411 411 for a, b, size in super(encodedstore, self).datafiles():
412 412 try:
413 413 a = decodefilename(a)
414 414 except KeyError:
415 415 a = None
416 416 yield a, b, size
417 417
418 418 def join(self, f):
419 419 return self.path + '/' + encodefilename(f)
420 420
421 421 def copylist(self):
422 422 return (['requires', '00changelog.i'] +
423 423 ['store/' + f for f in _data.split()])
424 424
425 425 class fncache(object):
426 426 # the filename used to be partially encoded
427 427 # hence the encodedir/decodedir dance
428 428 def __init__(self, vfs):
429 429 self.vfs = vfs
430 430 self.entries = None
431 431 self._dirty = False
432 432
433 433 def _load(self):
434 434 '''fill the entries from the fncache file'''
435 435 self._dirty = False
436 436 try:
437 437 fp = self.vfs('fncache', mode='rb')
438 438 except IOError:
439 439 # skip nonexistent file
440 440 self.entries = set()
441 441 return
442 442 self.entries = set(decodedir(fp.read()).splitlines())
443 443 if '' in self.entries:
444 444 fp.seek(0)
445 445 for n, line in enumerate(util.iterfile(fp)):
446 446 if not line.rstrip('\n'):
447 447 t = _('invalid entry in fncache, line %d') % (n + 1)
448 448 raise error.Abort(t)
449 449 fp.close()
450 450
451 451 def write(self, tr):
452 452 if self._dirty:
453 453 assert self.entries is not None
454 454 tr.addbackup('fncache')
455 455 fp = self.vfs('fncache', mode='wb', atomictemp=True)
456 456 if self.entries:
457 457 fp.write(encodedir('\n'.join(self.entries) + '\n'))
458 458 fp.close()
459 459 self._dirty = False
460 460
461 461 def add(self, fn):
462 462 if self.entries is None:
463 463 self._load()
464 464 if fn not in self.entries:
465 465 self._dirty = True
466 466 self.entries.add(fn)
467 467
468 468 def remove(self, fn):
469 469 if self.entries is None:
470 470 self._load()
471 471 try:
472 472 self.entries.remove(fn)
473 473 self._dirty = True
474 474 except KeyError:
475 475 pass
476 476
477 477 def __contains__(self, fn):
478 478 if self.entries is None:
479 479 self._load()
480 480 return fn in self.entries
481 481
482 482 def __iter__(self):
483 483 if self.entries is None:
484 484 self._load()
485 485 return iter(self.entries)
486 486
487 487 class _fncachevfs(vfsmod.abstractvfs, vfsmod.proxyvfs):
488 488 def __init__(self, vfs, fnc, encode):
489 489 vfsmod.proxyvfs.__init__(self, vfs)
490 490 self.fncache = fnc
491 491 self.encode = encode
492 492
493 493 def __call__(self, path, mode='r', *args, **kw):
494 494 encoded = self.encode(path)
495 495 if mode not in ('r', 'rb') and (path.startswith('data/') or
496 496 path.startswith('meta/')):
497 497 # do not trigger a fncache load when adding a file that already is
498 498 # known to exist.
499 499 notload = self.fncache.entries is None and self.vfs.exists(encoded)
500 500 if notload and 'a' in mode and not self.vfs.stat(encoded).st_size:
501 501 # when appending to an existing file, if the file has size zero,
502 502 # it should be considered as missing. Such zero-size files are
503 503 # the result of truncation when a transaction is aborted.
504 504 notload = False
505 505 if not notload:
506 506 self.fncache.add(path)
507 507 return self.vfs(encoded, mode, *args, **kw)
508 508
509 509 def join(self, path):
510 510 if path:
511 511 return self.vfs.join(self.encode(path))
512 512 else:
513 513 return self.vfs.join(path)
514 514
515 515 class fncachestore(basicstore):
516 516 def __init__(self, path, vfstype, dotencode):
517 517 if dotencode:
518 518 encode = _pathencode
519 519 else:
520 520 encode = _plainhybridencode
521 521 self.encode = encode
522 522 vfs = vfstype(path + '/store')
523 523 self.path = vfs.base
524 524 self.pathsep = self.path + '/'
525 525 self.createmode = _calcmode(vfs)
526 526 vfs.createmode = self.createmode
527 527 self.rawvfs = vfs
528 528 fnc = fncache(vfs)
529 529 self.fncache = fnc
530 530 self.vfs = _fncachevfs(vfs, fnc, encode)
531 531 self.opener = self.vfs
532 532
533 533 def join(self, f):
534 534 return self.pathsep + self.encode(f)
535 535
536 536 def getsize(self, path):
537 537 return self.rawvfs.stat(path).st_size
538 538
539 539 def datafiles(self):
540 540 for f in sorted(self.fncache):
541 541 ef = self.encode(f)
542 542 try:
543 543 yield f, ef, self.getsize(ef)
544 544 except OSError as err:
545 545 if err.errno != errno.ENOENT:
546 546 raise
547 547
548 548 def copylist(self):
549 d = ('data meta dh fncache phaseroots obsstore'
549 d = ('narrowspec data meta dh fncache phaseroots obsstore'
550 550 ' 00manifest.d 00manifest.i 00changelog.d 00changelog.i')
551 551 return (['requires', '00changelog.i'] +
552 552 ['store/' + f for f in d.split()])
553 553
554 554 def write(self, tr):
555 555 self.fncache.write(tr)
556 556
557 557 def invalidatecaches(self):
558 558 self.fncache.entries = None
559 559
560 560 def markremoved(self, fn):
561 561 self.fncache.remove(fn)
562 562
563 563 def _exists(self, f):
564 564 ef = self.encode(f)
565 565 try:
566 566 self.getsize(ef)
567 567 return True
568 568 except OSError as err:
569 569 if err.errno != errno.ENOENT:
570 570 raise
571 571 # nonexistent entry
572 572 return False
573 573
574 574 def __contains__(self, path):
575 575 '''Checks if the store contains path'''
576 576 path = "/".join(("data", path))
577 577 # check for files (exact match)
578 578 e = path + '.i'
579 579 if e in self.fncache and self._exists(e):
580 580 return True
581 581 # now check for directories (prefix match)
582 582 if not path.endswith('/'):
583 583 path += '/'
584 584 for e in self.fncache:
585 585 if e.startswith(path) and self._exists(e):
586 586 return True
587 587 return False
588 588
589 589 def store(requirements, path, vfstype):
590 590 if 'store' in requirements:
591 591 if 'fncache' in requirements:
592 592 return fncachestore(path, vfstype, 'dotencode' in requirements)
593 593 return encodedstore(path, vfstype)
594 594 return basicstore(path, vfstype)
@@ -1,43 +1,43 b''
1 1 $ . "$TESTDIR/narrow-library.sh"
2 2 $ hg init repo
3 3 $ cd repo
4 $ cat << EOF > .hg/narrowspec
4 $ cat << EOF > .hg/store/narrowspec
5 5 > [include]
6 6 > path:foo
7 7 > [exclude]
8 8 > EOF
9 9 $ echo treemanifest >> .hg/requires
10 10 $ echo narrowhg-experimental >> .hg/requires
11 11 $ mkdir -p foo/bar
12 12 $ echo b > foo/f
13 13 $ echo c > foo/bar/f
14 14 $ hg commit -Am hi
15 15 adding foo/bar/f
16 16 adding foo/f
17 17 $ hg debugindex -m
18 18 rev linkrev nodeid p1 p2
19 19 0 0 14a5d056d75a 000000000000 000000000000
20 20 $ hg debugindex --dir foo
21 21 rev linkrev nodeid p1 p2
22 22 0 0 e635c7857aef 000000000000 000000000000
23 23 $ hg debugindex --dir foo/
24 24 rev linkrev nodeid p1 p2
25 25 0 0 e635c7857aef 000000000000 000000000000
26 26 $ hg debugindex --dir foo/bar
27 27 rev linkrev nodeid p1 p2
28 28 0 0 e091d4224761 000000000000 000000000000
29 29 $ hg debugindex --dir foo/bar/
30 30 rev linkrev nodeid p1 p2
31 31 0 0 e091d4224761 000000000000 000000000000
32 32 $ hg debugdata -m 0
33 33 foo\x00e635c7857aef92ac761ce5741a99da159abbbb24t (esc)
34 34 $ hg debugdata --dir foo 0
35 35 bar\x00e091d42247613adff5d41b67f15fe7189ee97b39t (esc)
36 36 f\x001e88685f5ddec574a34c70af492f95b6debc8741 (esc)
37 37 $ hg debugdata --dir foo/ 0
38 38 bar\x00e091d42247613adff5d41b67f15fe7189ee97b39t (esc)
39 39 f\x001e88685f5ddec574a34c70af492f95b6debc8741 (esc)
40 40 $ hg debugdata --dir foo/bar 0
41 41 f\x00149da44f2a4e14f488b7bd4157945a9837408c00 (esc)
42 42 $ hg debugdata --dir foo/bar/ 0
43 43 f\x00149da44f2a4e14f488b7bd4157945a9837408c00 (esc)
@@ -1,175 +1,174 b''
1 1 $ . "$TESTDIR/narrow-library.sh"
2 2
3 3 $ hg init master
4 4 $ cd master
5 5 $ cat >> .hg/hgrc <<EOF
6 6 > [narrow]
7 7 > serveellipses=True
8 8 > EOF
9 9 $ for x in `$TESTDIR/seq.py 10`
10 10 > do
11 11 > echo $x > "f$x"
12 12 > hg add "f$x"
13 13 > hg commit -m "Commit f$x"
14 14 > done
15 15 $ cd ..
16 16
17 17 narrow clone a couple files, f2 and f8
18 18
19 19 $ hg clone --narrow ssh://user@dummy/master narrow --include "f2" --include "f8"
20 20 requesting all changes
21 21 adding changesets
22 22 adding manifests
23 23 adding file changes
24 24 added 5 changesets with 2 changes to 2 files
25 25 new changesets *:* (glob)
26 26 updating to branch default
27 27 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
28 28 $ cd narrow
29 29 $ ls
30 30 f2
31 31 f8
32 32 $ cat f2 f8
33 33 2
34 34 8
35 35
36 36 $ cd ..
37 37
38 38 change every upstream file twice
39 39
40 40 $ cd master
41 41 $ for x in `$TESTDIR/seq.py 10`
42 42 > do
43 43 > echo "update#1 $x" >> "f$x"
44 44 > hg commit -m "Update#1 to f$x" "f$x"
45 45 > done
46 46 $ for x in `$TESTDIR/seq.py 10`
47 47 > do
48 48 > echo "update#2 $x" >> "f$x"
49 49 > hg commit -m "Update#2 to f$x" "f$x"
50 50 > done
51 51 $ cd ..
52 52
53 53 look for incoming changes
54 54
55 55 $ cd narrow
56 56 $ hg incoming --limit 3
57 57 comparing with ssh://user@dummy/master
58 58 searching for changes
59 59 changeset: 5:ddc055582556
60 60 user: test
61 61 date: Thu Jan 01 00:00:00 1970 +0000
62 62 summary: Update#1 to f1
63 63
64 64 changeset: 6:f66eb5ad621d
65 65 user: test
66 66 date: Thu Jan 01 00:00:00 1970 +0000
67 67 summary: Update#1 to f2
68 68
69 69 changeset: 7:c42ecff04e99
70 70 user: test
71 71 date: Thu Jan 01 00:00:00 1970 +0000
72 72 summary: Update#1 to f3
73 73
74 74
75 75 Interrupting the pull is safe
76 76 $ hg --config hooks.pretxnchangegroup.bad=false pull -q
77 77 transaction abort!
78 78 rollback completed
79 79 abort: pretxnchangegroup.bad hook exited with status 1
80 80 [255]
81 81 $ hg id
82 82 223311e70a6f tip
83 83
84 84 pull new changes down to the narrow clone. Should get 8 new changesets: 4
85 85 relevant to the narrow spec, and 4 ellipsis nodes gluing them all together.
86 86
87 87 $ hg pull
88 88 pulling from ssh://user@dummy/master
89 89 searching for changes
90 90 adding changesets
91 91 adding manifests
92 92 adding file changes
93 93 added 9 changesets with 4 changes to 2 files
94 94 new changesets *:* (glob)
95 95 (run 'hg update' to get a working copy)
96 96 $ hg log -T '{rev}: {desc}\n'
97 97 13: Update#2 to f10
98 98 12: Update#2 to f8
99 99 11: Update#2 to f7
100 100 10: Update#2 to f2
101 101 9: Update#2 to f1
102 102 8: Update#1 to f8
103 103 7: Update#1 to f7
104 104 6: Update#1 to f2
105 105 5: Update#1 to f1
106 106 4: Commit f10
107 107 3: Commit f8
108 108 2: Commit f7
109 109 1: Commit f2
110 110 0: Commit f1
111 111 $ hg update tip
112 112 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
113 113
114 114 add a change and push it
115 115
116 116 $ echo "update#3 2" >> f2
117 117 $ hg commit -m "Update#3 to f2" f2
118 118 $ hg log f2 -T '{rev}: {desc}\n'
119 119 14: Update#3 to f2
120 120 10: Update#2 to f2
121 121 6: Update#1 to f2
122 122 1: Commit f2
123 123 $ hg push
124 124 pushing to ssh://user@dummy/master
125 125 searching for changes
126 126 remote: adding changesets
127 127 remote: adding manifests
128 128 remote: adding file changes
129 129 remote: added 1 changesets with 1 changes to 1 files
130 130 $ cd ..
131 131
132 132 $ cd master
133 133 $ hg log f2 -T '{rev}: {desc}\n'
134 134 30: Update#3 to f2
135 135 21: Update#2 to f2
136 136 11: Update#1 to f2
137 137 1: Commit f2
138 138 $ hg log -l 3 -T '{rev}: {desc}\n'
139 139 30: Update#3 to f2
140 140 29: Update#2 to f10
141 141 28: Update#2 to f9
142 142
143 143 Can pull into repo with a single commit
144 144
145 145 $ cd ..
146 146 $ hg clone -q --narrow ssh://user@dummy/master narrow2 --include "f1" -r 0
147 147 $ cd narrow2
148 148 $ hg pull -q -r 1
149 149 transaction abort!
150 150 rollback completed
151 151 abort: pull failed on remote
152 152 [255]
153 153
154 154 Can use 'hg share':
155 155 $ cat >> $HGRCPATH <<EOF
156 156 > [extensions]
157 157 > share=
158 158 > EOF
159 159
160 160 $ cd ..
161 161 $ hg share narrow2 narrow2-share
162 162 updating working directory
163 163 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
164 164 $ cd narrow2-share
165 165 $ hg status
166 166
167 167 We should also be able to unshare without breaking everything:
168 168 $ hg unshare
169 devel-warn: write with no wlock: "narrowspec" at: */hgext/narrow/narrowrepo.py:* (unsharenarrowspec) (glob)
170 169 $ hg verify
171 170 checking changesets
172 171 checking manifests
173 172 crosschecking files in changesets and manifests
174 173 checking files
175 174 1 files, 1 changesets, 1 total revisions
General Comments 0
You need to be logged in to leave comments. Login now