##// END OF EJS Templates
lock: add internal config to not replace signal handlers while locking...
Yuya Nishihara -
r38157:8c828beb stable
parent child Browse files
Show More
@@ -1,1344 +1,1347 b''
1 1 # configitems.py - centralized declaration of configuration option
2 2 #
3 3 # Copyright 2017 Pierre-Yves David <pierre-yves.david@octobus.net>
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 functools
11 11 import re
12 12
13 13 from . import (
14 14 encoding,
15 15 error,
16 16 )
17 17
18 18 def loadconfigtable(ui, extname, configtable):
19 19 """update config item known to the ui with the extension ones"""
20 20 for section, items in sorted(configtable.items()):
21 21 knownitems = ui._knownconfig.setdefault(section, itemregister())
22 22 knownkeys = set(knownitems)
23 23 newkeys = set(items)
24 24 for key in sorted(knownkeys & newkeys):
25 25 msg = "extension '%s' overwrite config item '%s.%s'"
26 26 msg %= (extname, section, key)
27 27 ui.develwarn(msg, config='warn-config')
28 28
29 29 knownitems.update(items)
30 30
31 31 class configitem(object):
32 32 """represent a known config item
33 33
34 34 :section: the official config section where to find this item,
35 35 :name: the official name within the section,
36 36 :default: default value for this item,
37 37 :alias: optional list of tuples as alternatives,
38 38 :generic: this is a generic definition, match name using regular expression.
39 39 """
40 40
41 41 def __init__(self, section, name, default=None, alias=(),
42 42 generic=False, priority=0):
43 43 self.section = section
44 44 self.name = name
45 45 self.default = default
46 46 self.alias = list(alias)
47 47 self.generic = generic
48 48 self.priority = priority
49 49 self._re = None
50 50 if generic:
51 51 self._re = re.compile(self.name)
52 52
53 53 class itemregister(dict):
54 54 """A specialized dictionary that can handle wild-card selection"""
55 55
56 56 def __init__(self):
57 57 super(itemregister, self).__init__()
58 58 self._generics = set()
59 59
60 60 def update(self, other):
61 61 super(itemregister, self).update(other)
62 62 self._generics.update(other._generics)
63 63
64 64 def __setitem__(self, key, item):
65 65 super(itemregister, self).__setitem__(key, item)
66 66 if item.generic:
67 67 self._generics.add(item)
68 68
69 69 def get(self, key):
70 70 baseitem = super(itemregister, self).get(key)
71 71 if baseitem is not None and not baseitem.generic:
72 72 return baseitem
73 73
74 74 # search for a matching generic item
75 75 generics = sorted(self._generics, key=(lambda x: (x.priority, x.name)))
76 76 for item in generics:
77 77 # we use 'match' instead of 'search' to make the matching simpler
78 78 # for people unfamiliar with regular expression. Having the match
79 79 # rooted to the start of the string will produce less surprising
80 80 # result for user writing simple regex for sub-attribute.
81 81 #
82 82 # For example using "color\..*" match produces an unsurprising
83 83 # result, while using search could suddenly match apparently
84 84 # unrelated configuration that happens to contains "color."
85 85 # anywhere. This is a tradeoff where we favor requiring ".*" on
86 86 # some match to avoid the need to prefix most pattern with "^".
87 87 # The "^" seems more error prone.
88 88 if item._re.match(key):
89 89 return item
90 90
91 91 return None
92 92
93 93 coreitems = {}
94 94
95 95 def _register(configtable, *args, **kwargs):
96 96 item = configitem(*args, **kwargs)
97 97 section = configtable.setdefault(item.section, itemregister())
98 98 if item.name in section:
99 99 msg = "duplicated config item registration for '%s.%s'"
100 100 raise error.ProgrammingError(msg % (item.section, item.name))
101 101 section[item.name] = item
102 102
103 103 # special value for case where the default is derived from other values
104 104 dynamicdefault = object()
105 105
106 106 # Registering actual config items
107 107
108 108 def getitemregister(configtable):
109 109 f = functools.partial(_register, configtable)
110 110 # export pseudo enum as configitem.*
111 111 f.dynamicdefault = dynamicdefault
112 112 return f
113 113
114 114 coreconfigitem = getitemregister(coreitems)
115 115
116 116 coreconfigitem('alias', '.*',
117 117 default=dynamicdefault,
118 118 generic=True,
119 119 )
120 120 coreconfigitem('annotate', 'nodates',
121 121 default=False,
122 122 )
123 123 coreconfigitem('annotate', 'showfunc',
124 124 default=False,
125 125 )
126 126 coreconfigitem('annotate', 'unified',
127 127 default=None,
128 128 )
129 129 coreconfigitem('annotate', 'git',
130 130 default=False,
131 131 )
132 132 coreconfigitem('annotate', 'ignorews',
133 133 default=False,
134 134 )
135 135 coreconfigitem('annotate', 'ignorewsamount',
136 136 default=False,
137 137 )
138 138 coreconfigitem('annotate', 'ignoreblanklines',
139 139 default=False,
140 140 )
141 141 coreconfigitem('annotate', 'ignorewseol',
142 142 default=False,
143 143 )
144 144 coreconfigitem('annotate', 'nobinary',
145 145 default=False,
146 146 )
147 147 coreconfigitem('annotate', 'noprefix',
148 148 default=False,
149 149 )
150 150 coreconfigitem('auth', 'cookiefile',
151 151 default=None,
152 152 )
153 153 # bookmarks.pushing: internal hack for discovery
154 154 coreconfigitem('bookmarks', 'pushing',
155 155 default=list,
156 156 )
157 157 # bundle.mainreporoot: internal hack for bundlerepo
158 158 coreconfigitem('bundle', 'mainreporoot',
159 159 default='',
160 160 )
161 161 # bundle.reorder: experimental config
162 162 coreconfigitem('bundle', 'reorder',
163 163 default='auto',
164 164 )
165 165 coreconfigitem('censor', 'policy',
166 166 default='abort',
167 167 )
168 168 coreconfigitem('chgserver', 'idletimeout',
169 169 default=3600,
170 170 )
171 171 coreconfigitem('chgserver', 'skiphash',
172 172 default=False,
173 173 )
174 174 coreconfigitem('cmdserver', 'log',
175 175 default=None,
176 176 )
177 177 coreconfigitem('color', '.*',
178 178 default=None,
179 179 generic=True,
180 180 )
181 181 coreconfigitem('color', 'mode',
182 182 default='auto',
183 183 )
184 184 coreconfigitem('color', 'pagermode',
185 185 default=dynamicdefault,
186 186 )
187 187 coreconfigitem('commands', 'show.aliasprefix',
188 188 default=list,
189 189 )
190 190 coreconfigitem('commands', 'status.relative',
191 191 default=False,
192 192 )
193 193 coreconfigitem('commands', 'status.skipstates',
194 194 default=[],
195 195 )
196 196 coreconfigitem('commands', 'status.verbose',
197 197 default=False,
198 198 )
199 199 coreconfigitem('commands', 'update.check',
200 200 default=None,
201 201 # Deprecated, remove after 4.4 release
202 202 alias=[('experimental', 'updatecheck')]
203 203 )
204 204 coreconfigitem('commands', 'update.requiredest',
205 205 default=False,
206 206 )
207 207 coreconfigitem('committemplate', '.*',
208 208 default=None,
209 209 generic=True,
210 210 )
211 211 coreconfigitem('convert', 'cvsps.cache',
212 212 default=True,
213 213 )
214 214 coreconfigitem('convert', 'cvsps.fuzz',
215 215 default=60,
216 216 )
217 217 coreconfigitem('convert', 'cvsps.logencoding',
218 218 default=None,
219 219 )
220 220 coreconfigitem('convert', 'cvsps.mergefrom',
221 221 default=None,
222 222 )
223 223 coreconfigitem('convert', 'cvsps.mergeto',
224 224 default=None,
225 225 )
226 226 coreconfigitem('convert', 'git.committeractions',
227 227 default=lambda: ['messagedifferent'],
228 228 )
229 229 coreconfigitem('convert', 'git.extrakeys',
230 230 default=list,
231 231 )
232 232 coreconfigitem('convert', 'git.findcopiesharder',
233 233 default=False,
234 234 )
235 235 coreconfigitem('convert', 'git.remoteprefix',
236 236 default='remote',
237 237 )
238 238 coreconfigitem('convert', 'git.renamelimit',
239 239 default=400,
240 240 )
241 241 coreconfigitem('convert', 'git.saverev',
242 242 default=True,
243 243 )
244 244 coreconfigitem('convert', 'git.similarity',
245 245 default=50,
246 246 )
247 247 coreconfigitem('convert', 'git.skipsubmodules',
248 248 default=False,
249 249 )
250 250 coreconfigitem('convert', 'hg.clonebranches',
251 251 default=False,
252 252 )
253 253 coreconfigitem('convert', 'hg.ignoreerrors',
254 254 default=False,
255 255 )
256 256 coreconfigitem('convert', 'hg.revs',
257 257 default=None,
258 258 )
259 259 coreconfigitem('convert', 'hg.saverev',
260 260 default=False,
261 261 )
262 262 coreconfigitem('convert', 'hg.sourcename',
263 263 default=None,
264 264 )
265 265 coreconfigitem('convert', 'hg.startrev',
266 266 default=None,
267 267 )
268 268 coreconfigitem('convert', 'hg.tagsbranch',
269 269 default='default',
270 270 )
271 271 coreconfigitem('convert', 'hg.usebranchnames',
272 272 default=True,
273 273 )
274 274 coreconfigitem('convert', 'ignoreancestorcheck',
275 275 default=False,
276 276 )
277 277 coreconfigitem('convert', 'localtimezone',
278 278 default=False,
279 279 )
280 280 coreconfigitem('convert', 'p4.encoding',
281 281 default=dynamicdefault,
282 282 )
283 283 coreconfigitem('convert', 'p4.startrev',
284 284 default=0,
285 285 )
286 286 coreconfigitem('convert', 'skiptags',
287 287 default=False,
288 288 )
289 289 coreconfigitem('convert', 'svn.debugsvnlog',
290 290 default=True,
291 291 )
292 292 coreconfigitem('convert', 'svn.trunk',
293 293 default=None,
294 294 )
295 295 coreconfigitem('convert', 'svn.tags',
296 296 default=None,
297 297 )
298 298 coreconfigitem('convert', 'svn.branches',
299 299 default=None,
300 300 )
301 301 coreconfigitem('convert', 'svn.startrev',
302 302 default=0,
303 303 )
304 304 coreconfigitem('debug', 'dirstate.delaywrite',
305 305 default=0,
306 306 )
307 307 coreconfigitem('defaults', '.*',
308 308 default=None,
309 309 generic=True,
310 310 )
311 311 coreconfigitem('devel', 'all-warnings',
312 312 default=False,
313 313 )
314 314 coreconfigitem('devel', 'bundle2.debug',
315 315 default=False,
316 316 )
317 317 coreconfigitem('devel', 'cache-vfs',
318 318 default=None,
319 319 )
320 320 coreconfigitem('devel', 'check-locks',
321 321 default=False,
322 322 )
323 323 coreconfigitem('devel', 'check-relroot',
324 324 default=False,
325 325 )
326 326 coreconfigitem('devel', 'default-date',
327 327 default=None,
328 328 )
329 329 coreconfigitem('devel', 'deprec-warn',
330 330 default=False,
331 331 )
332 332 coreconfigitem('devel', 'disableloaddefaultcerts',
333 333 default=False,
334 334 )
335 335 coreconfigitem('devel', 'warn-empty-changegroup',
336 336 default=False,
337 337 )
338 338 coreconfigitem('devel', 'legacy.exchange',
339 339 default=list,
340 340 )
341 341 coreconfigitem('devel', 'servercafile',
342 342 default='',
343 343 )
344 344 coreconfigitem('devel', 'serverexactprotocol',
345 345 default='',
346 346 )
347 347 coreconfigitem('devel', 'serverrequirecert',
348 348 default=False,
349 349 )
350 350 coreconfigitem('devel', 'strip-obsmarkers',
351 351 default=True,
352 352 )
353 353 coreconfigitem('devel', 'warn-config',
354 354 default=None,
355 355 )
356 356 coreconfigitem('devel', 'warn-config-default',
357 357 default=None,
358 358 )
359 359 coreconfigitem('devel', 'user.obsmarker',
360 360 default=None,
361 361 )
362 362 coreconfigitem('devel', 'warn-config-unknown',
363 363 default=None,
364 364 )
365 365 coreconfigitem('devel', 'debug.peer-request',
366 366 default=False,
367 367 )
368 368 coreconfigitem('diff', 'nodates',
369 369 default=False,
370 370 )
371 371 coreconfigitem('diff', 'showfunc',
372 372 default=False,
373 373 )
374 374 coreconfigitem('diff', 'unified',
375 375 default=None,
376 376 )
377 377 coreconfigitem('diff', 'git',
378 378 default=False,
379 379 )
380 380 coreconfigitem('diff', 'ignorews',
381 381 default=False,
382 382 )
383 383 coreconfigitem('diff', 'ignorewsamount',
384 384 default=False,
385 385 )
386 386 coreconfigitem('diff', 'ignoreblanklines',
387 387 default=False,
388 388 )
389 389 coreconfigitem('diff', 'ignorewseol',
390 390 default=False,
391 391 )
392 392 coreconfigitem('diff', 'nobinary',
393 393 default=False,
394 394 )
395 395 coreconfigitem('diff', 'noprefix',
396 396 default=False,
397 397 )
398 398 coreconfigitem('email', 'bcc',
399 399 default=None,
400 400 )
401 401 coreconfigitem('email', 'cc',
402 402 default=None,
403 403 )
404 404 coreconfigitem('email', 'charsets',
405 405 default=list,
406 406 )
407 407 coreconfigitem('email', 'from',
408 408 default=None,
409 409 )
410 410 coreconfigitem('email', 'method',
411 411 default='smtp',
412 412 )
413 413 coreconfigitem('email', 'reply-to',
414 414 default=None,
415 415 )
416 416 coreconfigitem('email', 'to',
417 417 default=None,
418 418 )
419 419 coreconfigitem('experimental', 'archivemetatemplate',
420 420 default=dynamicdefault,
421 421 )
422 422 coreconfigitem('experimental', 'bundle-phases',
423 423 default=False,
424 424 )
425 425 coreconfigitem('experimental', 'bundle2-advertise',
426 426 default=True,
427 427 )
428 428 coreconfigitem('experimental', 'bundle2-output-capture',
429 429 default=False,
430 430 )
431 431 coreconfigitem('experimental', 'bundle2.pushback',
432 432 default=False,
433 433 )
434 434 coreconfigitem('experimental', 'bundle2.stream',
435 435 default=False,
436 436 )
437 437 coreconfigitem('experimental', 'bundle2lazylocking',
438 438 default=False,
439 439 )
440 440 coreconfigitem('experimental', 'bundlecomplevel',
441 441 default=None,
442 442 )
443 443 coreconfigitem('experimental', 'bundlecomplevel.bzip2',
444 444 default=None,
445 445 )
446 446 coreconfigitem('experimental', 'bundlecomplevel.gzip',
447 447 default=None,
448 448 )
449 449 coreconfigitem('experimental', 'bundlecomplevel.none',
450 450 default=None,
451 451 )
452 452 coreconfigitem('experimental', 'bundlecomplevel.zstd',
453 453 default=None,
454 454 )
455 455 coreconfigitem('experimental', 'changegroup3',
456 456 default=False,
457 457 )
458 458 coreconfigitem('experimental', 'clientcompressionengines',
459 459 default=list,
460 460 )
461 461 coreconfigitem('experimental', 'copytrace',
462 462 default='on',
463 463 )
464 464 coreconfigitem('experimental', 'copytrace.movecandidateslimit',
465 465 default=100,
466 466 )
467 467 coreconfigitem('experimental', 'copytrace.sourcecommitlimit',
468 468 default=100,
469 469 )
470 470 coreconfigitem('experimental', 'crecordtest',
471 471 default=None,
472 472 )
473 473 coreconfigitem('experimental', 'directaccess',
474 474 default=False,
475 475 )
476 476 coreconfigitem('experimental', 'directaccess.revnums',
477 477 default=False,
478 478 )
479 479 coreconfigitem('experimental', 'editortmpinhg',
480 480 default=False,
481 481 )
482 482 coreconfigitem('experimental', 'evolution',
483 483 default=list,
484 484 )
485 485 coreconfigitem('experimental', 'evolution.allowdivergence',
486 486 default=False,
487 487 alias=[('experimental', 'allowdivergence')]
488 488 )
489 489 coreconfigitem('experimental', 'evolution.allowunstable',
490 490 default=None,
491 491 )
492 492 coreconfigitem('experimental', 'evolution.createmarkers',
493 493 default=None,
494 494 )
495 495 coreconfigitem('experimental', 'evolution.effect-flags',
496 496 default=True,
497 497 alias=[('experimental', 'effect-flags')]
498 498 )
499 499 coreconfigitem('experimental', 'evolution.exchange',
500 500 default=None,
501 501 )
502 502 coreconfigitem('experimental', 'evolution.bundle-obsmarker',
503 503 default=False,
504 504 )
505 505 coreconfigitem('experimental', 'evolution.report-instabilities',
506 506 default=True,
507 507 )
508 508 coreconfigitem('experimental', 'evolution.track-operation',
509 509 default=True,
510 510 )
511 511 coreconfigitem('experimental', 'worddiff',
512 512 default=False,
513 513 )
514 514 coreconfigitem('experimental', 'maxdeltachainspan',
515 515 default=-1,
516 516 )
517 517 coreconfigitem('experimental', 'mergetempdirprefix',
518 518 default=None,
519 519 )
520 520 coreconfigitem('experimental', 'mmapindexthreshold',
521 521 default=None,
522 522 )
523 523 coreconfigitem('experimental', 'nonnormalparanoidcheck',
524 524 default=False,
525 525 )
526 526 coreconfigitem('experimental', 'exportableenviron',
527 527 default=list,
528 528 )
529 529 coreconfigitem('experimental', 'extendedheader.index',
530 530 default=None,
531 531 )
532 532 coreconfigitem('experimental', 'extendedheader.similarity',
533 533 default=False,
534 534 )
535 535 coreconfigitem('experimental', 'format.compression',
536 536 default='zlib',
537 537 )
538 538 coreconfigitem('experimental', 'graphshorten',
539 539 default=False,
540 540 )
541 541 coreconfigitem('experimental', 'graphstyle.parent',
542 542 default=dynamicdefault,
543 543 )
544 544 coreconfigitem('experimental', 'graphstyle.missing',
545 545 default=dynamicdefault,
546 546 )
547 547 coreconfigitem('experimental', 'graphstyle.grandparent',
548 548 default=dynamicdefault,
549 549 )
550 550 coreconfigitem('experimental', 'hook-track-tags',
551 551 default=False,
552 552 )
553 553 coreconfigitem('experimental', 'httppeer.advertise-v2',
554 554 default=False,
555 555 )
556 556 coreconfigitem('experimental', 'httppostargs',
557 557 default=False,
558 558 )
559 559 coreconfigitem('experimental', 'mergedriver',
560 560 default=None,
561 561 )
562 562 coreconfigitem('experimental', 'obsmarkers-exchange-debug',
563 563 default=False,
564 564 )
565 565 coreconfigitem('experimental', 'remotenames',
566 566 default=False,
567 567 )
568 568 coreconfigitem('experimental', 'revlogv2',
569 569 default=None,
570 570 )
571 571 coreconfigitem('experimental', 'single-head-per-branch',
572 572 default=False,
573 573 )
574 574 coreconfigitem('experimental', 'sshserver.support-v2',
575 575 default=False,
576 576 )
577 577 coreconfigitem('experimental', 'spacemovesdown',
578 578 default=False,
579 579 )
580 580 coreconfigitem('experimental', 'sparse-read',
581 581 default=False,
582 582 )
583 583 coreconfigitem('experimental', 'sparse-read.density-threshold',
584 584 default=0.25,
585 585 )
586 586 coreconfigitem('experimental', 'sparse-read.min-gap-size',
587 587 default='256K',
588 588 )
589 589 coreconfigitem('experimental', 'treemanifest',
590 590 default=False,
591 591 )
592 592 coreconfigitem('experimental', 'update.atomic-file',
593 593 default=False,
594 594 )
595 595 coreconfigitem('experimental', 'sshpeer.advertise-v2',
596 596 default=False,
597 597 )
598 598 coreconfigitem('experimental', 'web.apiserver',
599 599 default=False,
600 600 )
601 601 coreconfigitem('experimental', 'web.api.http-v2',
602 602 default=False,
603 603 )
604 604 coreconfigitem('experimental', 'web.api.debugreflect',
605 605 default=False,
606 606 )
607 607 coreconfigitem('experimental', 'xdiff',
608 608 default=False,
609 609 )
610 610 coreconfigitem('extensions', '.*',
611 611 default=None,
612 612 generic=True,
613 613 )
614 614 coreconfigitem('extdata', '.*',
615 615 default=None,
616 616 generic=True,
617 617 )
618 618 coreconfigitem('format', 'aggressivemergedeltas',
619 619 default=False,
620 620 )
621 621 coreconfigitem('format', 'chunkcachesize',
622 622 default=None,
623 623 )
624 624 coreconfigitem('format', 'dotencode',
625 625 default=True,
626 626 )
627 627 coreconfigitem('format', 'generaldelta',
628 628 default=False,
629 629 )
630 630 coreconfigitem('format', 'manifestcachesize',
631 631 default=None,
632 632 )
633 633 coreconfigitem('format', 'maxchainlen',
634 634 default=None,
635 635 )
636 636 coreconfigitem('format', 'obsstore-version',
637 637 default=None,
638 638 )
639 639 coreconfigitem('format', 'usefncache',
640 640 default=True,
641 641 )
642 642 coreconfigitem('format', 'usegeneraldelta',
643 643 default=True,
644 644 )
645 645 coreconfigitem('format', 'usestore',
646 646 default=True,
647 647 )
648 648 coreconfigitem('fsmonitor', 'warn_when_unused',
649 649 default=True,
650 650 )
651 651 coreconfigitem('fsmonitor', 'warn_update_file_count',
652 652 default=50000,
653 653 )
654 654 coreconfigitem('hooks', '.*',
655 655 default=dynamicdefault,
656 656 generic=True,
657 657 )
658 658 coreconfigitem('hgweb-paths', '.*',
659 659 default=list,
660 660 generic=True,
661 661 )
662 662 coreconfigitem('hostfingerprints', '.*',
663 663 default=list,
664 664 generic=True,
665 665 )
666 666 coreconfigitem('hostsecurity', 'ciphers',
667 667 default=None,
668 668 )
669 669 coreconfigitem('hostsecurity', 'disabletls10warning',
670 670 default=False,
671 671 )
672 672 coreconfigitem('hostsecurity', 'minimumprotocol',
673 673 default=dynamicdefault,
674 674 )
675 675 coreconfigitem('hostsecurity', '.*:minimumprotocol$',
676 676 default=dynamicdefault,
677 677 generic=True,
678 678 )
679 679 coreconfigitem('hostsecurity', '.*:ciphers$',
680 680 default=dynamicdefault,
681 681 generic=True,
682 682 )
683 683 coreconfigitem('hostsecurity', '.*:fingerprints$',
684 684 default=list,
685 685 generic=True,
686 686 )
687 687 coreconfigitem('hostsecurity', '.*:verifycertsfile$',
688 688 default=None,
689 689 generic=True,
690 690 )
691 691
692 692 coreconfigitem('http_proxy', 'always',
693 693 default=False,
694 694 )
695 695 coreconfigitem('http_proxy', 'host',
696 696 default=None,
697 697 )
698 698 coreconfigitem('http_proxy', 'no',
699 699 default=list,
700 700 )
701 701 coreconfigitem('http_proxy', 'passwd',
702 702 default=None,
703 703 )
704 704 coreconfigitem('http_proxy', 'user',
705 705 default=None,
706 706 )
707 707 coreconfigitem('logtoprocess', 'commandexception',
708 708 default=None,
709 709 )
710 710 coreconfigitem('logtoprocess', 'commandfinish',
711 711 default=None,
712 712 )
713 713 coreconfigitem('logtoprocess', 'command',
714 714 default=None,
715 715 )
716 716 coreconfigitem('logtoprocess', 'develwarn',
717 717 default=None,
718 718 )
719 719 coreconfigitem('logtoprocess', 'uiblocked',
720 720 default=None,
721 721 )
722 722 coreconfigitem('merge', 'checkunknown',
723 723 default='abort',
724 724 )
725 725 coreconfigitem('merge', 'checkignored',
726 726 default='abort',
727 727 )
728 728 coreconfigitem('experimental', 'merge.checkpathconflicts',
729 729 default=False,
730 730 )
731 731 coreconfigitem('merge', 'followcopies',
732 732 default=True,
733 733 )
734 734 coreconfigitem('merge', 'on-failure',
735 735 default='continue',
736 736 )
737 737 coreconfigitem('merge', 'preferancestor',
738 738 default=lambda: ['*'],
739 739 )
740 740 coreconfigitem('merge-tools', '.*',
741 741 default=None,
742 742 generic=True,
743 743 )
744 744 coreconfigitem('merge-tools', br'.*\.args$',
745 745 default="$local $base $other",
746 746 generic=True,
747 747 priority=-1,
748 748 )
749 749 coreconfigitem('merge-tools', br'.*\.binary$',
750 750 default=False,
751 751 generic=True,
752 752 priority=-1,
753 753 )
754 754 coreconfigitem('merge-tools', br'.*\.check$',
755 755 default=list,
756 756 generic=True,
757 757 priority=-1,
758 758 )
759 759 coreconfigitem('merge-tools', br'.*\.checkchanged$',
760 760 default=False,
761 761 generic=True,
762 762 priority=-1,
763 763 )
764 764 coreconfigitem('merge-tools', br'.*\.executable$',
765 765 default=dynamicdefault,
766 766 generic=True,
767 767 priority=-1,
768 768 )
769 769 coreconfigitem('merge-tools', br'.*\.fixeol$',
770 770 default=False,
771 771 generic=True,
772 772 priority=-1,
773 773 )
774 774 coreconfigitem('merge-tools', br'.*\.gui$',
775 775 default=False,
776 776 generic=True,
777 777 priority=-1,
778 778 )
779 779 coreconfigitem('merge-tools', br'.*\.mergemarkers$',
780 780 default='basic',
781 781 generic=True,
782 782 priority=-1,
783 783 )
784 784 coreconfigitem('merge-tools', br'.*\.mergemarkertemplate$',
785 785 default=dynamicdefault, # take from ui.mergemarkertemplate
786 786 generic=True,
787 787 priority=-1,
788 788 )
789 789 coreconfigitem('merge-tools', br'.*\.priority$',
790 790 default=0,
791 791 generic=True,
792 792 priority=-1,
793 793 )
794 794 coreconfigitem('merge-tools', br'.*\.premerge$',
795 795 default=dynamicdefault,
796 796 generic=True,
797 797 priority=-1,
798 798 )
799 799 coreconfigitem('merge-tools', br'.*\.symlink$',
800 800 default=False,
801 801 generic=True,
802 802 priority=-1,
803 803 )
804 804 coreconfigitem('pager', 'attend-.*',
805 805 default=dynamicdefault,
806 806 generic=True,
807 807 )
808 808 coreconfigitem('pager', 'ignore',
809 809 default=list,
810 810 )
811 811 coreconfigitem('pager', 'pager',
812 812 default=dynamicdefault,
813 813 )
814 814 coreconfigitem('patch', 'eol',
815 815 default='strict',
816 816 )
817 817 coreconfigitem('patch', 'fuzz',
818 818 default=2,
819 819 )
820 820 coreconfigitem('paths', 'default',
821 821 default=None,
822 822 )
823 823 coreconfigitem('paths', 'default-push',
824 824 default=None,
825 825 )
826 826 coreconfigitem('paths', '.*',
827 827 default=None,
828 828 generic=True,
829 829 )
830 830 coreconfigitem('phases', 'checksubrepos',
831 831 default='follow',
832 832 )
833 833 coreconfigitem('phases', 'new-commit',
834 834 default='draft',
835 835 )
836 836 coreconfigitem('phases', 'publish',
837 837 default=True,
838 838 )
839 839 coreconfigitem('profiling', 'enabled',
840 840 default=False,
841 841 )
842 842 coreconfigitem('profiling', 'format',
843 843 default='text',
844 844 )
845 845 coreconfigitem('profiling', 'freq',
846 846 default=1000,
847 847 )
848 848 coreconfigitem('profiling', 'limit',
849 849 default=30,
850 850 )
851 851 coreconfigitem('profiling', 'nested',
852 852 default=0,
853 853 )
854 854 coreconfigitem('profiling', 'output',
855 855 default=None,
856 856 )
857 857 coreconfigitem('profiling', 'showmax',
858 858 default=0.999,
859 859 )
860 860 coreconfigitem('profiling', 'showmin',
861 861 default=dynamicdefault,
862 862 )
863 863 coreconfigitem('profiling', 'sort',
864 864 default='inlinetime',
865 865 )
866 866 coreconfigitem('profiling', 'statformat',
867 867 default='hotpath',
868 868 )
869 869 coreconfigitem('profiling', 'type',
870 870 default='stat',
871 871 )
872 872 coreconfigitem('progress', 'assume-tty',
873 873 default=False,
874 874 )
875 875 coreconfigitem('progress', 'changedelay',
876 876 default=1,
877 877 )
878 878 coreconfigitem('progress', 'clear-complete',
879 879 default=True,
880 880 )
881 881 coreconfigitem('progress', 'debug',
882 882 default=False,
883 883 )
884 884 coreconfigitem('progress', 'delay',
885 885 default=3,
886 886 )
887 887 coreconfigitem('progress', 'disable',
888 888 default=False,
889 889 )
890 890 coreconfigitem('progress', 'estimateinterval',
891 891 default=60.0,
892 892 )
893 893 coreconfigitem('progress', 'format',
894 894 default=lambda: ['topic', 'bar', 'number', 'estimate'],
895 895 )
896 896 coreconfigitem('progress', 'refresh',
897 897 default=0.1,
898 898 )
899 899 coreconfigitem('progress', 'width',
900 900 default=dynamicdefault,
901 901 )
902 902 coreconfigitem('push', 'pushvars.server',
903 903 default=False,
904 904 )
905 905 coreconfigitem('server', 'bookmarks-pushkey-compat',
906 906 default=True,
907 907 )
908 908 coreconfigitem('server', 'bundle1',
909 909 default=True,
910 910 )
911 911 coreconfigitem('server', 'bundle1gd',
912 912 default=None,
913 913 )
914 914 coreconfigitem('server', 'bundle1.pull',
915 915 default=None,
916 916 )
917 917 coreconfigitem('server', 'bundle1gd.pull',
918 918 default=None,
919 919 )
920 920 coreconfigitem('server', 'bundle1.push',
921 921 default=None,
922 922 )
923 923 coreconfigitem('server', 'bundle1gd.push',
924 924 default=None,
925 925 )
926 926 coreconfigitem('server', 'compressionengines',
927 927 default=list,
928 928 )
929 929 coreconfigitem('server', 'concurrent-push-mode',
930 930 default='strict',
931 931 )
932 932 coreconfigitem('server', 'disablefullbundle',
933 933 default=False,
934 934 )
935 935 coreconfigitem('server', 'streamunbundle',
936 936 default=False,
937 937 )
938 938 coreconfigitem('server', 'pullbundle',
939 939 default=False,
940 940 )
941 941 coreconfigitem('server', 'maxhttpheaderlen',
942 942 default=1024,
943 943 )
944 944 coreconfigitem('server', 'preferuncompressed',
945 945 default=False,
946 946 )
947 947 coreconfigitem('server', 'uncompressed',
948 948 default=True,
949 949 )
950 950 coreconfigitem('server', 'uncompressedallowsecret',
951 951 default=False,
952 952 )
953 953 coreconfigitem('server', 'validate',
954 954 default=False,
955 955 )
956 956 coreconfigitem('server', 'zliblevel',
957 957 default=-1,
958 958 )
959 959 coreconfigitem('server', 'zstdlevel',
960 960 default=3,
961 961 )
962 962 coreconfigitem('share', 'pool',
963 963 default=None,
964 964 )
965 965 coreconfigitem('share', 'poolnaming',
966 966 default='identity',
967 967 )
968 968 coreconfigitem('smtp', 'host',
969 969 default=None,
970 970 )
971 971 coreconfigitem('smtp', 'local_hostname',
972 972 default=None,
973 973 )
974 974 coreconfigitem('smtp', 'password',
975 975 default=None,
976 976 )
977 977 coreconfigitem('smtp', 'port',
978 978 default=dynamicdefault,
979 979 )
980 980 coreconfigitem('smtp', 'tls',
981 981 default='none',
982 982 )
983 983 coreconfigitem('smtp', 'username',
984 984 default=None,
985 985 )
986 986 coreconfigitem('sparse', 'missingwarning',
987 987 default=True,
988 988 )
989 989 coreconfigitem('subrepos', 'allowed',
990 990 default=dynamicdefault, # to make backporting simpler
991 991 )
992 992 coreconfigitem('subrepos', 'hg:allowed',
993 993 default=dynamicdefault,
994 994 )
995 995 coreconfigitem('subrepos', 'git:allowed',
996 996 default=dynamicdefault,
997 997 )
998 998 coreconfigitem('subrepos', 'svn:allowed',
999 999 default=dynamicdefault,
1000 1000 )
1001 1001 coreconfigitem('templates', '.*',
1002 1002 default=None,
1003 1003 generic=True,
1004 1004 )
1005 1005 coreconfigitem('trusted', 'groups',
1006 1006 default=list,
1007 1007 )
1008 1008 coreconfigitem('trusted', 'users',
1009 1009 default=list,
1010 1010 )
1011 1011 coreconfigitem('ui', '_usedassubrepo',
1012 1012 default=False,
1013 1013 )
1014 1014 coreconfigitem('ui', 'allowemptycommit',
1015 1015 default=False,
1016 1016 )
1017 1017 coreconfigitem('ui', 'archivemeta',
1018 1018 default=True,
1019 1019 )
1020 1020 coreconfigitem('ui', 'askusername',
1021 1021 default=False,
1022 1022 )
1023 1023 coreconfigitem('ui', 'clonebundlefallback',
1024 1024 default=False,
1025 1025 )
1026 1026 coreconfigitem('ui', 'clonebundleprefers',
1027 1027 default=list,
1028 1028 )
1029 1029 coreconfigitem('ui', 'clonebundles',
1030 1030 default=True,
1031 1031 )
1032 1032 coreconfigitem('ui', 'color',
1033 1033 default='auto',
1034 1034 )
1035 1035 coreconfigitem('ui', 'commitsubrepos',
1036 1036 default=False,
1037 1037 )
1038 1038 coreconfigitem('ui', 'debug',
1039 1039 default=False,
1040 1040 )
1041 1041 coreconfigitem('ui', 'debugger',
1042 1042 default=None,
1043 1043 )
1044 1044 coreconfigitem('ui', 'editor',
1045 1045 default=dynamicdefault,
1046 1046 )
1047 1047 coreconfigitem('ui', 'fallbackencoding',
1048 1048 default=None,
1049 1049 )
1050 1050 coreconfigitem('ui', 'forcecwd',
1051 1051 default=None,
1052 1052 )
1053 1053 coreconfigitem('ui', 'forcemerge',
1054 1054 default=None,
1055 1055 )
1056 1056 coreconfigitem('ui', 'formatdebug',
1057 1057 default=False,
1058 1058 )
1059 1059 coreconfigitem('ui', 'formatjson',
1060 1060 default=False,
1061 1061 )
1062 1062 coreconfigitem('ui', 'formatted',
1063 1063 default=None,
1064 1064 )
1065 1065 coreconfigitem('ui', 'graphnodetemplate',
1066 1066 default=None,
1067 1067 )
1068 1068 coreconfigitem('ui', 'interactive',
1069 1069 default=None,
1070 1070 )
1071 1071 coreconfigitem('ui', 'interface',
1072 1072 default=None,
1073 1073 )
1074 1074 coreconfigitem('ui', 'interface.chunkselector',
1075 1075 default=None,
1076 1076 )
1077 1077 coreconfigitem('ui', 'logblockedtimes',
1078 1078 default=False,
1079 1079 )
1080 1080 coreconfigitem('ui', 'logtemplate',
1081 1081 default=None,
1082 1082 )
1083 1083 coreconfigitem('ui', 'merge',
1084 1084 default=None,
1085 1085 )
1086 1086 coreconfigitem('ui', 'mergemarkers',
1087 1087 default='basic',
1088 1088 )
1089 1089 coreconfigitem('ui', 'mergemarkertemplate',
1090 1090 default=('{node|short} '
1091 1091 '{ifeq(tags, "tip", "", '
1092 1092 'ifeq(tags, "", "", "{tags} "))}'
1093 1093 '{if(bookmarks, "{bookmarks} ")}'
1094 1094 '{ifeq(branch, "default", "", "{branch} ")}'
1095 1095 '- {author|user}: {desc|firstline}')
1096 1096 )
1097 1097 coreconfigitem('ui', 'nontty',
1098 1098 default=False,
1099 1099 )
1100 1100 coreconfigitem('ui', 'origbackuppath',
1101 1101 default=None,
1102 1102 )
1103 1103 coreconfigitem('ui', 'paginate',
1104 1104 default=True,
1105 1105 )
1106 1106 coreconfigitem('ui', 'patch',
1107 1107 default=None,
1108 1108 )
1109 1109 coreconfigitem('ui', 'portablefilenames',
1110 1110 default='warn',
1111 1111 )
1112 1112 coreconfigitem('ui', 'promptecho',
1113 1113 default=False,
1114 1114 )
1115 1115 coreconfigitem('ui', 'quiet',
1116 1116 default=False,
1117 1117 )
1118 1118 coreconfigitem('ui', 'quietbookmarkmove',
1119 1119 default=False,
1120 1120 )
1121 1121 coreconfigitem('ui', 'remotecmd',
1122 1122 default='hg',
1123 1123 )
1124 1124 coreconfigitem('ui', 'report_untrusted',
1125 1125 default=True,
1126 1126 )
1127 1127 coreconfigitem('ui', 'rollback',
1128 1128 default=True,
1129 1129 )
1130 coreconfigitem('ui', 'signal-safe-lock',
1131 default=True,
1132 )
1130 1133 coreconfigitem('ui', 'slash',
1131 1134 default=False,
1132 1135 )
1133 1136 coreconfigitem('ui', 'ssh',
1134 1137 default='ssh',
1135 1138 )
1136 1139 coreconfigitem('ui', 'ssherrorhint',
1137 1140 default=None,
1138 1141 )
1139 1142 coreconfigitem('ui', 'statuscopies',
1140 1143 default=False,
1141 1144 )
1142 1145 coreconfigitem('ui', 'strict',
1143 1146 default=False,
1144 1147 )
1145 1148 coreconfigitem('ui', 'style',
1146 1149 default='',
1147 1150 )
1148 1151 coreconfigitem('ui', 'supportcontact',
1149 1152 default=None,
1150 1153 )
1151 1154 coreconfigitem('ui', 'textwidth',
1152 1155 default=78,
1153 1156 )
1154 1157 coreconfigitem('ui', 'timeout',
1155 1158 default='600',
1156 1159 )
1157 1160 coreconfigitem('ui', 'timeout.warn',
1158 1161 default=0,
1159 1162 )
1160 1163 coreconfigitem('ui', 'traceback',
1161 1164 default=False,
1162 1165 )
1163 1166 coreconfigitem('ui', 'tweakdefaults',
1164 1167 default=False,
1165 1168 )
1166 1169 coreconfigitem('ui', 'username',
1167 1170 alias=[('ui', 'user')]
1168 1171 )
1169 1172 coreconfigitem('ui', 'verbose',
1170 1173 default=False,
1171 1174 )
1172 1175 coreconfigitem('verify', 'skipflags',
1173 1176 default=None,
1174 1177 )
1175 1178 coreconfigitem('web', 'allowbz2',
1176 1179 default=False,
1177 1180 )
1178 1181 coreconfigitem('web', 'allowgz',
1179 1182 default=False,
1180 1183 )
1181 1184 coreconfigitem('web', 'allow-pull',
1182 1185 alias=[('web', 'allowpull')],
1183 1186 default=True,
1184 1187 )
1185 1188 coreconfigitem('web', 'allow-push',
1186 1189 alias=[('web', 'allow_push')],
1187 1190 default=list,
1188 1191 )
1189 1192 coreconfigitem('web', 'allowzip',
1190 1193 default=False,
1191 1194 )
1192 1195 coreconfigitem('web', 'archivesubrepos',
1193 1196 default=False,
1194 1197 )
1195 1198 coreconfigitem('web', 'cache',
1196 1199 default=True,
1197 1200 )
1198 1201 coreconfigitem('web', 'contact',
1199 1202 default=None,
1200 1203 )
1201 1204 coreconfigitem('web', 'deny_push',
1202 1205 default=list,
1203 1206 )
1204 1207 coreconfigitem('web', 'guessmime',
1205 1208 default=False,
1206 1209 )
1207 1210 coreconfigitem('web', 'hidden',
1208 1211 default=False,
1209 1212 )
1210 1213 coreconfigitem('web', 'labels',
1211 1214 default=list,
1212 1215 )
1213 1216 coreconfigitem('web', 'logoimg',
1214 1217 default='hglogo.png',
1215 1218 )
1216 1219 coreconfigitem('web', 'logourl',
1217 1220 default='https://mercurial-scm.org/',
1218 1221 )
1219 1222 coreconfigitem('web', 'accesslog',
1220 1223 default='-',
1221 1224 )
1222 1225 coreconfigitem('web', 'address',
1223 1226 default='',
1224 1227 )
1225 1228 coreconfigitem('web', 'allow_archive',
1226 1229 default=list,
1227 1230 )
1228 1231 coreconfigitem('web', 'allow_read',
1229 1232 default=list,
1230 1233 )
1231 1234 coreconfigitem('web', 'baseurl',
1232 1235 default=None,
1233 1236 )
1234 1237 coreconfigitem('web', 'cacerts',
1235 1238 default=None,
1236 1239 )
1237 1240 coreconfigitem('web', 'certificate',
1238 1241 default=None,
1239 1242 )
1240 1243 coreconfigitem('web', 'collapse',
1241 1244 default=False,
1242 1245 )
1243 1246 coreconfigitem('web', 'csp',
1244 1247 default=None,
1245 1248 )
1246 1249 coreconfigitem('web', 'deny_read',
1247 1250 default=list,
1248 1251 )
1249 1252 coreconfigitem('web', 'descend',
1250 1253 default=True,
1251 1254 )
1252 1255 coreconfigitem('web', 'description',
1253 1256 default="",
1254 1257 )
1255 1258 coreconfigitem('web', 'encoding',
1256 1259 default=lambda: encoding.encoding,
1257 1260 )
1258 1261 coreconfigitem('web', 'errorlog',
1259 1262 default='-',
1260 1263 )
1261 1264 coreconfigitem('web', 'ipv6',
1262 1265 default=False,
1263 1266 )
1264 1267 coreconfigitem('web', 'maxchanges',
1265 1268 default=10,
1266 1269 )
1267 1270 coreconfigitem('web', 'maxfiles',
1268 1271 default=10,
1269 1272 )
1270 1273 coreconfigitem('web', 'maxshortchanges',
1271 1274 default=60,
1272 1275 )
1273 1276 coreconfigitem('web', 'motd',
1274 1277 default='',
1275 1278 )
1276 1279 coreconfigitem('web', 'name',
1277 1280 default=dynamicdefault,
1278 1281 )
1279 1282 coreconfigitem('web', 'port',
1280 1283 default=8000,
1281 1284 )
1282 1285 coreconfigitem('web', 'prefix',
1283 1286 default='',
1284 1287 )
1285 1288 coreconfigitem('web', 'push_ssl',
1286 1289 default=True,
1287 1290 )
1288 1291 coreconfigitem('web', 'refreshinterval',
1289 1292 default=20,
1290 1293 )
1291 1294 coreconfigitem('web', 'server-header',
1292 1295 default=None,
1293 1296 )
1294 1297 coreconfigitem('web', 'staticurl',
1295 1298 default=None,
1296 1299 )
1297 1300 coreconfigitem('web', 'stripes',
1298 1301 default=1,
1299 1302 )
1300 1303 coreconfigitem('web', 'style',
1301 1304 default='paper',
1302 1305 )
1303 1306 coreconfigitem('web', 'templates',
1304 1307 default=None,
1305 1308 )
1306 1309 coreconfigitem('web', 'view',
1307 1310 default='served',
1308 1311 )
1309 1312 coreconfigitem('worker', 'backgroundclose',
1310 1313 default=dynamicdefault,
1311 1314 )
1312 1315 # Windows defaults to a limit of 512 open files. A buffer of 128
1313 1316 # should give us enough headway.
1314 1317 coreconfigitem('worker', 'backgroundclosemaxqueue',
1315 1318 default=384,
1316 1319 )
1317 1320 coreconfigitem('worker', 'backgroundcloseminfilecount',
1318 1321 default=2048,
1319 1322 )
1320 1323 coreconfigitem('worker', 'backgroundclosethreadcount',
1321 1324 default=4,
1322 1325 )
1323 1326 coreconfigitem('worker', 'enabled',
1324 1327 default=True,
1325 1328 )
1326 1329 coreconfigitem('worker', 'numcpus',
1327 1330 default=None,
1328 1331 )
1329 1332
1330 1333 # Rebase related configuration moved to core because other extension are doing
1331 1334 # strange things. For example, shelve import the extensions to reuse some bit
1332 1335 # without formally loading it.
1333 1336 coreconfigitem('commands', 'rebase.requiredest',
1334 1337 default=False,
1335 1338 )
1336 1339 coreconfigitem('experimental', 'rebaseskipobsolete',
1337 1340 default=True,
1338 1341 )
1339 1342 coreconfigitem('rebase', 'singletransaction',
1340 1343 default=False,
1341 1344 )
1342 1345 coreconfigitem('rebase', 'experimental.inmemory',
1343 1346 default=False,
1344 1347 )
@@ -1,2378 +1,2381 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 # Functions receiving (ui, features) that extensions can register to impact
358 358 # the ability to load repositories with custom requirements. Only
359 359 # functions defined in loaded extensions are called.
360 360 #
361 361 # The function receives a set of requirement strings that the repository
362 362 # is capable of opening. Functions will typically add elements to the
363 363 # set to reflect that the extension knows how to handle that requirements.
364 364 featuresetupfuncs = set()
365 365
366 366 @interfaceutil.implementer(repository.completelocalrepository)
367 367 class localrepository(object):
368 368
369 369 # obsolete experimental requirements:
370 370 # - manifestv2: An experimental new manifest format that allowed
371 371 # for stem compression of long paths. Experiment ended up not
372 372 # being successful (repository sizes went up due to worse delta
373 373 # chains), and the code was deleted in 4.6.
374 374 supportedformats = {
375 375 'revlogv1',
376 376 'generaldelta',
377 377 'treemanifest',
378 378 REVLOGV2_REQUIREMENT,
379 379 }
380 380 _basesupported = supportedformats | {
381 381 'store',
382 382 'fncache',
383 383 'shared',
384 384 'relshared',
385 385 'dotencode',
386 386 'exp-sparse',
387 387 }
388 388 openerreqs = {
389 389 'revlogv1',
390 390 'generaldelta',
391 391 'treemanifest',
392 392 }
393 393
394 394 # list of prefix for file which can be written without 'wlock'
395 395 # Extensions should extend this list when needed
396 396 _wlockfreeprefix = {
397 397 # We migh consider requiring 'wlock' for the next
398 398 # two, but pretty much all the existing code assume
399 399 # wlock is not needed so we keep them excluded for
400 400 # now.
401 401 'hgrc',
402 402 'requires',
403 403 # XXX cache is a complicatged business someone
404 404 # should investigate this in depth at some point
405 405 'cache/',
406 406 # XXX shouldn't be dirstate covered by the wlock?
407 407 'dirstate',
408 408 # XXX bisect was still a bit too messy at the time
409 409 # this changeset was introduced. Someone should fix
410 410 # the remainig bit and drop this line
411 411 'bisect.state',
412 412 }
413 413
414 414 def __init__(self, baseui, path, create=False, intents=None):
415 415 self.requirements = set()
416 416 self.filtername = None
417 417 # wvfs: rooted at the repository root, used to access the working copy
418 418 self.wvfs = vfsmod.vfs(path, expandpath=True, realpath=True)
419 419 # vfs: rooted at .hg, used to access repo files outside of .hg/store
420 420 self.vfs = None
421 421 # svfs: usually rooted at .hg/store, used to access repository history
422 422 # If this is a shared repository, this vfs may point to another
423 423 # repository's .hg/store directory.
424 424 self.svfs = None
425 425 self.root = self.wvfs.base
426 426 self.path = self.wvfs.join(".hg")
427 427 self.origroot = path
428 428 # This is only used by context.workingctx.match in order to
429 429 # detect files in subrepos.
430 430 self.auditor = pathutil.pathauditor(
431 431 self.root, callback=self._checknested)
432 432 # This is only used by context.basectx.match in order to detect
433 433 # files in subrepos.
434 434 self.nofsauditor = pathutil.pathauditor(
435 435 self.root, callback=self._checknested, realfs=False, cached=True)
436 436 self.baseui = baseui
437 437 self.ui = baseui.copy()
438 438 self.ui.copy = baseui.copy # prevent copying repo configuration
439 439 self.vfs = vfsmod.vfs(self.path, cacheaudited=True)
440 440 if (self.ui.configbool('devel', 'all-warnings') or
441 441 self.ui.configbool('devel', 'check-locks')):
442 442 self.vfs.audit = self._getvfsward(self.vfs.audit)
443 443 # A list of callback to shape the phase if no data were found.
444 444 # Callback are in the form: func(repo, roots) --> processed root.
445 445 # This list it to be filled by extension during repo setup
446 446 self._phasedefaults = []
447 447 try:
448 448 self.ui.readconfig(self.vfs.join("hgrc"), self.root)
449 449 self._loadextensions()
450 450 except IOError:
451 451 pass
452 452
453 453 if featuresetupfuncs:
454 454 self.supported = set(self._basesupported) # use private copy
455 455 extmods = set(m.__name__ for n, m
456 456 in extensions.extensions(self.ui))
457 457 for setupfunc in featuresetupfuncs:
458 458 if setupfunc.__module__ in extmods:
459 459 setupfunc(self.ui, self.supported)
460 460 else:
461 461 self.supported = self._basesupported
462 462 color.setup(self.ui)
463 463
464 464 # Add compression engines.
465 465 for name in util.compengines:
466 466 engine = util.compengines[name]
467 467 if engine.revlogheader():
468 468 self.supported.add('exp-compression-%s' % name)
469 469
470 470 if not self.vfs.isdir():
471 471 if create:
472 472 self.requirements = newreporequirements(self)
473 473
474 474 if not self.wvfs.exists():
475 475 self.wvfs.makedirs()
476 476 self.vfs.makedir(notindexed=True)
477 477
478 478 if 'store' in self.requirements:
479 479 self.vfs.mkdir("store")
480 480
481 481 # create an invalid changelog
482 482 self.vfs.append(
483 483 "00changelog.i",
484 484 '\0\0\0\2' # represents revlogv2
485 485 ' dummy changelog to prevent using the old repo layout'
486 486 )
487 487 else:
488 488 raise error.RepoError(_("repository %s not found") % path)
489 489 elif create:
490 490 raise error.RepoError(_("repository %s already exists") % path)
491 491 else:
492 492 try:
493 493 self.requirements = scmutil.readrequires(
494 494 self.vfs, self.supported)
495 495 except IOError as inst:
496 496 if inst.errno != errno.ENOENT:
497 497 raise
498 498
499 499 cachepath = self.vfs.join('cache')
500 500 self.sharedpath = self.path
501 501 try:
502 502 sharedpath = self.vfs.read("sharedpath").rstrip('\n')
503 503 if 'relshared' in self.requirements:
504 504 sharedpath = self.vfs.join(sharedpath)
505 505 vfs = vfsmod.vfs(sharedpath, realpath=True)
506 506 cachepath = vfs.join('cache')
507 507 s = vfs.base
508 508 if not vfs.exists():
509 509 raise error.RepoError(
510 510 _('.hg/sharedpath points to nonexistent directory %s') % s)
511 511 self.sharedpath = s
512 512 except IOError as inst:
513 513 if inst.errno != errno.ENOENT:
514 514 raise
515 515
516 516 if 'exp-sparse' in self.requirements and not sparse.enabled:
517 517 raise error.RepoError(_('repository is using sparse feature but '
518 518 'sparse is not enabled; enable the '
519 519 '"sparse" extensions to access'))
520 520
521 521 self.store = store.store(
522 522 self.requirements, self.sharedpath,
523 523 lambda base: vfsmod.vfs(base, cacheaudited=True))
524 524 self.spath = self.store.path
525 525 self.svfs = self.store.vfs
526 526 self.sjoin = self.store.join
527 527 self.vfs.createmode = self.store.createmode
528 528 self.cachevfs = vfsmod.vfs(cachepath, cacheaudited=True)
529 529 self.cachevfs.createmode = self.store.createmode
530 530 if (self.ui.configbool('devel', 'all-warnings') or
531 531 self.ui.configbool('devel', 'check-locks')):
532 532 if util.safehasattr(self.svfs, 'vfs'): # this is filtervfs
533 533 self.svfs.vfs.audit = self._getsvfsward(self.svfs.vfs.audit)
534 534 else: # standard vfs
535 535 self.svfs.audit = self._getsvfsward(self.svfs.audit)
536 536 self._applyopenerreqs()
537 537 if create:
538 538 self._writerequirements()
539 539
540 540 self._dirstatevalidatewarned = False
541 541
542 542 self._branchcaches = {}
543 543 self._revbranchcache = None
544 544 self._filterpats = {}
545 545 self._datafilters = {}
546 546 self._transref = self._lockref = self._wlockref = None
547 547
548 548 # A cache for various files under .hg/ that tracks file changes,
549 549 # (used by the filecache decorator)
550 550 #
551 551 # Maps a property name to its util.filecacheentry
552 552 self._filecache = {}
553 553
554 554 # hold sets of revision to be filtered
555 555 # should be cleared when something might have changed the filter value:
556 556 # - new changesets,
557 557 # - phase change,
558 558 # - new obsolescence marker,
559 559 # - working directory parent change,
560 560 # - bookmark changes
561 561 self.filteredrevcache = {}
562 562
563 563 # post-dirstate-status hooks
564 564 self._postdsstatus = []
565 565
566 566 # generic mapping between names and nodes
567 567 self.names = namespaces.namespaces()
568 568
569 569 # Key to signature value.
570 570 self._sparsesignaturecache = {}
571 571 # Signature to cached matcher instance.
572 572 self._sparsematchercache = {}
573 573
574 574 def _getvfsward(self, origfunc):
575 575 """build a ward for self.vfs"""
576 576 rref = weakref.ref(self)
577 577 def checkvfs(path, mode=None):
578 578 ret = origfunc(path, mode=mode)
579 579 repo = rref()
580 580 if (repo is None
581 581 or not util.safehasattr(repo, '_wlockref')
582 582 or not util.safehasattr(repo, '_lockref')):
583 583 return
584 584 if mode in (None, 'r', 'rb'):
585 585 return
586 586 if path.startswith(repo.path):
587 587 # truncate name relative to the repository (.hg)
588 588 path = path[len(repo.path) + 1:]
589 589 if path.startswith('cache/'):
590 590 msg = 'accessing cache with vfs instead of cachevfs: "%s"'
591 591 repo.ui.develwarn(msg % path, stacklevel=2, config="cache-vfs")
592 592 if path.startswith('journal.'):
593 593 # journal is covered by 'lock'
594 594 if repo._currentlock(repo._lockref) is None:
595 595 repo.ui.develwarn('write with no lock: "%s"' % path,
596 596 stacklevel=2, config='check-locks')
597 597 elif repo._currentlock(repo._wlockref) is None:
598 598 # rest of vfs files are covered by 'wlock'
599 599 #
600 600 # exclude special files
601 601 for prefix in self._wlockfreeprefix:
602 602 if path.startswith(prefix):
603 603 return
604 604 repo.ui.develwarn('write with no wlock: "%s"' % path,
605 605 stacklevel=2, config='check-locks')
606 606 return ret
607 607 return checkvfs
608 608
609 609 def _getsvfsward(self, origfunc):
610 610 """build a ward for self.svfs"""
611 611 rref = weakref.ref(self)
612 612 def checksvfs(path, mode=None):
613 613 ret = origfunc(path, mode=mode)
614 614 repo = rref()
615 615 if repo is None or not util.safehasattr(repo, '_lockref'):
616 616 return
617 617 if mode in (None, 'r', 'rb'):
618 618 return
619 619 if path.startswith(repo.sharedpath):
620 620 # truncate name relative to the repository (.hg)
621 621 path = path[len(repo.sharedpath) + 1:]
622 622 if repo._currentlock(repo._lockref) is None:
623 623 repo.ui.develwarn('write with no lock: "%s"' % path,
624 624 stacklevel=3)
625 625 return ret
626 626 return checksvfs
627 627
628 628 def close(self):
629 629 self._writecaches()
630 630
631 631 def _loadextensions(self):
632 632 extensions.loadall(self.ui)
633 633
634 634 def _writecaches(self):
635 635 if self._revbranchcache:
636 636 self._revbranchcache.write()
637 637
638 638 def _restrictcapabilities(self, caps):
639 639 if self.ui.configbool('experimental', 'bundle2-advertise'):
640 640 caps = set(caps)
641 641 capsblob = bundle2.encodecaps(bundle2.getrepocaps(self,
642 642 role='client'))
643 643 caps.add('bundle2=' + urlreq.quote(capsblob))
644 644 return caps
645 645
646 646 def _applyopenerreqs(self):
647 647 self.svfs.options = dict((r, 1) for r in self.requirements
648 648 if r in self.openerreqs)
649 649 # experimental config: format.chunkcachesize
650 650 chunkcachesize = self.ui.configint('format', 'chunkcachesize')
651 651 if chunkcachesize is not None:
652 652 self.svfs.options['chunkcachesize'] = chunkcachesize
653 653 # experimental config: format.maxchainlen
654 654 maxchainlen = self.ui.configint('format', 'maxchainlen')
655 655 if maxchainlen is not None:
656 656 self.svfs.options['maxchainlen'] = maxchainlen
657 657 # experimental config: format.manifestcachesize
658 658 manifestcachesize = self.ui.configint('format', 'manifestcachesize')
659 659 if manifestcachesize is not None:
660 660 self.svfs.options['manifestcachesize'] = manifestcachesize
661 661 # experimental config: format.aggressivemergedeltas
662 662 aggressivemergedeltas = self.ui.configbool('format',
663 663 'aggressivemergedeltas')
664 664 self.svfs.options['aggressivemergedeltas'] = aggressivemergedeltas
665 665 self.svfs.options['lazydeltabase'] = not scmutil.gddeltaconfig(self.ui)
666 666 chainspan = self.ui.configbytes('experimental', 'maxdeltachainspan')
667 667 if 0 <= chainspan:
668 668 self.svfs.options['maxdeltachainspan'] = chainspan
669 669 mmapindexthreshold = self.ui.configbytes('experimental',
670 670 'mmapindexthreshold')
671 671 if mmapindexthreshold is not None:
672 672 self.svfs.options['mmapindexthreshold'] = mmapindexthreshold
673 673 withsparseread = self.ui.configbool('experimental', 'sparse-read')
674 674 srdensitythres = float(self.ui.config('experimental',
675 675 'sparse-read.density-threshold'))
676 676 srmingapsize = self.ui.configbytes('experimental',
677 677 'sparse-read.min-gap-size')
678 678 self.svfs.options['with-sparse-read'] = withsparseread
679 679 self.svfs.options['sparse-read-density-threshold'] = srdensitythres
680 680 self.svfs.options['sparse-read-min-gap-size'] = srmingapsize
681 681
682 682 for r in self.requirements:
683 683 if r.startswith('exp-compression-'):
684 684 self.svfs.options['compengine'] = r[len('exp-compression-'):]
685 685
686 686 # TODO move "revlogv2" to openerreqs once finalized.
687 687 if REVLOGV2_REQUIREMENT in self.requirements:
688 688 self.svfs.options['revlogv2'] = True
689 689
690 690 def _writerequirements(self):
691 691 scmutil.writerequires(self.vfs, self.requirements)
692 692
693 693 def _checknested(self, path):
694 694 """Determine if path is a legal nested repository."""
695 695 if not path.startswith(self.root):
696 696 return False
697 697 subpath = path[len(self.root) + 1:]
698 698 normsubpath = util.pconvert(subpath)
699 699
700 700 # XXX: Checking against the current working copy is wrong in
701 701 # the sense that it can reject things like
702 702 #
703 703 # $ hg cat -r 10 sub/x.txt
704 704 #
705 705 # if sub/ is no longer a subrepository in the working copy
706 706 # parent revision.
707 707 #
708 708 # However, it can of course also allow things that would have
709 709 # been rejected before, such as the above cat command if sub/
710 710 # is a subrepository now, but was a normal directory before.
711 711 # The old path auditor would have rejected by mistake since it
712 712 # panics when it sees sub/.hg/.
713 713 #
714 714 # All in all, checking against the working copy seems sensible
715 715 # since we want to prevent access to nested repositories on
716 716 # the filesystem *now*.
717 717 ctx = self[None]
718 718 parts = util.splitpath(subpath)
719 719 while parts:
720 720 prefix = '/'.join(parts)
721 721 if prefix in ctx.substate:
722 722 if prefix == normsubpath:
723 723 return True
724 724 else:
725 725 sub = ctx.sub(prefix)
726 726 return sub.checknested(subpath[len(prefix) + 1:])
727 727 else:
728 728 parts.pop()
729 729 return False
730 730
731 731 def peer(self):
732 732 return localpeer(self) # not cached to avoid reference cycle
733 733
734 734 def unfiltered(self):
735 735 """Return unfiltered version of the repository
736 736
737 737 Intended to be overwritten by filtered repo."""
738 738 return self
739 739
740 740 def filtered(self, name, visibilityexceptions=None):
741 741 """Return a filtered version of a repository"""
742 742 cls = repoview.newtype(self.unfiltered().__class__)
743 743 return cls(self, name, visibilityexceptions)
744 744
745 745 @repofilecache('bookmarks', 'bookmarks.current')
746 746 def _bookmarks(self):
747 747 return bookmarks.bmstore(self)
748 748
749 749 @property
750 750 def _activebookmark(self):
751 751 return self._bookmarks.active
752 752
753 753 # _phasesets depend on changelog. what we need is to call
754 754 # _phasecache.invalidate() if '00changelog.i' was changed, but it
755 755 # can't be easily expressed in filecache mechanism.
756 756 @storecache('phaseroots', '00changelog.i')
757 757 def _phasecache(self):
758 758 return phases.phasecache(self, self._phasedefaults)
759 759
760 760 @storecache('obsstore')
761 761 def obsstore(self):
762 762 return obsolete.makestore(self.ui, self)
763 763
764 764 @storecache('00changelog.i')
765 765 def changelog(self):
766 766 return changelog.changelog(self.svfs,
767 767 trypending=txnutil.mayhavepending(self.root))
768 768
769 769 def _constructmanifest(self):
770 770 # This is a temporary function while we migrate from manifest to
771 771 # manifestlog. It allows bundlerepo and unionrepo to intercept the
772 772 # manifest creation.
773 773 return manifest.manifestrevlog(self.svfs)
774 774
775 775 @storecache('00manifest.i')
776 776 def manifestlog(self):
777 777 return manifest.manifestlog(self.svfs, self)
778 778
779 779 @repofilecache('dirstate')
780 780 def dirstate(self):
781 781 sparsematchfn = lambda: sparse.matcher(self)
782 782
783 783 return dirstate.dirstate(self.vfs, self.ui, self.root,
784 784 self._dirstatevalidate, sparsematchfn)
785 785
786 786 def _dirstatevalidate(self, node):
787 787 try:
788 788 self.changelog.rev(node)
789 789 return node
790 790 except error.LookupError:
791 791 if not self._dirstatevalidatewarned:
792 792 self._dirstatevalidatewarned = True
793 793 self.ui.warn(_("warning: ignoring unknown"
794 794 " working parent %s!\n") % short(node))
795 795 return nullid
796 796
797 797 @repofilecache(narrowspec.FILENAME)
798 798 def narrowpats(self):
799 799 """matcher patterns for this repository's narrowspec
800 800
801 801 A tuple of (includes, excludes).
802 802 """
803 803 source = self
804 804 if self.shared():
805 805 from . import hg
806 806 source = hg.sharedreposource(self)
807 807 return narrowspec.load(source)
808 808
809 809 @repofilecache(narrowspec.FILENAME)
810 810 def _narrowmatch(self):
811 811 if changegroup.NARROW_REQUIREMENT not in self.requirements:
812 812 return matchmod.always(self.root, '')
813 813 include, exclude = self.narrowpats
814 814 return narrowspec.match(self.root, include=include, exclude=exclude)
815 815
816 816 # TODO(martinvonz): make this property-like instead?
817 817 def narrowmatch(self):
818 818 return self._narrowmatch
819 819
820 820 def setnarrowpats(self, newincludes, newexcludes):
821 821 target = self
822 822 if self.shared():
823 823 from . import hg
824 824 target = hg.sharedreposource(self)
825 825 narrowspec.save(target, newincludes, newexcludes)
826 826 self.invalidate(clearfilecache=True)
827 827
828 828 def __getitem__(self, changeid):
829 829 if changeid is None:
830 830 return context.workingctx(self)
831 831 if isinstance(changeid, context.basectx):
832 832 return changeid
833 833 if isinstance(changeid, slice):
834 834 # wdirrev isn't contiguous so the slice shouldn't include it
835 835 return [context.changectx(self, i)
836 836 for i in xrange(*changeid.indices(len(self)))
837 837 if i not in self.changelog.filteredrevs]
838 838 try:
839 839 return context.changectx(self, changeid)
840 840 except error.WdirUnsupported:
841 841 return context.workingctx(self)
842 842
843 843 def __contains__(self, changeid):
844 844 """True if the given changeid exists
845 845
846 846 error.LookupError is raised if an ambiguous node specified.
847 847 """
848 848 try:
849 849 self[changeid]
850 850 return True
851 851 except error.RepoLookupError:
852 852 return False
853 853
854 854 def __nonzero__(self):
855 855 return True
856 856
857 857 __bool__ = __nonzero__
858 858
859 859 def __len__(self):
860 860 # no need to pay the cost of repoview.changelog
861 861 unfi = self.unfiltered()
862 862 return len(unfi.changelog)
863 863
864 864 def __iter__(self):
865 865 return iter(self.changelog)
866 866
867 867 def revs(self, expr, *args):
868 868 '''Find revisions matching a revset.
869 869
870 870 The revset is specified as a string ``expr`` that may contain
871 871 %-formatting to escape certain types. See ``revsetlang.formatspec``.
872 872
873 873 Revset aliases from the configuration are not expanded. To expand
874 874 user aliases, consider calling ``scmutil.revrange()`` or
875 875 ``repo.anyrevs([expr], user=True)``.
876 876
877 877 Returns a revset.abstractsmartset, which is a list-like interface
878 878 that contains integer revisions.
879 879 '''
880 880 expr = revsetlang.formatspec(expr, *args)
881 881 m = revset.match(None, expr)
882 882 return m(self)
883 883
884 884 def set(self, expr, *args):
885 885 '''Find revisions matching a revset and emit changectx instances.
886 886
887 887 This is a convenience wrapper around ``revs()`` that iterates the
888 888 result and is a generator of changectx instances.
889 889
890 890 Revset aliases from the configuration are not expanded. To expand
891 891 user aliases, consider calling ``scmutil.revrange()``.
892 892 '''
893 893 for r in self.revs(expr, *args):
894 894 yield self[r]
895 895
896 896 def anyrevs(self, specs, user=False, localalias=None):
897 897 '''Find revisions matching one of the given revsets.
898 898
899 899 Revset aliases from the configuration are not expanded by default. To
900 900 expand user aliases, specify ``user=True``. To provide some local
901 901 definitions overriding user aliases, set ``localalias`` to
902 902 ``{name: definitionstring}``.
903 903 '''
904 904 if user:
905 905 m = revset.matchany(self.ui, specs,
906 906 lookup=revset.lookupfn(self),
907 907 localalias=localalias)
908 908 else:
909 909 m = revset.matchany(None, specs, localalias=localalias)
910 910 return m(self)
911 911
912 912 def url(self):
913 913 return 'file:' + self.root
914 914
915 915 def hook(self, name, throw=False, **args):
916 916 """Call a hook, passing this repo instance.
917 917
918 918 This a convenience method to aid invoking hooks. Extensions likely
919 919 won't call this unless they have registered a custom hook or are
920 920 replacing code that is expected to call a hook.
921 921 """
922 922 return hook.hook(self.ui, self, name, throw, **args)
923 923
924 924 @filteredpropertycache
925 925 def _tagscache(self):
926 926 '''Returns a tagscache object that contains various tags related
927 927 caches.'''
928 928
929 929 # This simplifies its cache management by having one decorated
930 930 # function (this one) and the rest simply fetch things from it.
931 931 class tagscache(object):
932 932 def __init__(self):
933 933 # These two define the set of tags for this repository. tags
934 934 # maps tag name to node; tagtypes maps tag name to 'global' or
935 935 # 'local'. (Global tags are defined by .hgtags across all
936 936 # heads, and local tags are defined in .hg/localtags.)
937 937 # They constitute the in-memory cache of tags.
938 938 self.tags = self.tagtypes = None
939 939
940 940 self.nodetagscache = self.tagslist = None
941 941
942 942 cache = tagscache()
943 943 cache.tags, cache.tagtypes = self._findtags()
944 944
945 945 return cache
946 946
947 947 def tags(self):
948 948 '''return a mapping of tag to node'''
949 949 t = {}
950 950 if self.changelog.filteredrevs:
951 951 tags, tt = self._findtags()
952 952 else:
953 953 tags = self._tagscache.tags
954 954 for k, v in tags.iteritems():
955 955 try:
956 956 # ignore tags to unknown nodes
957 957 self.changelog.rev(v)
958 958 t[k] = v
959 959 except (error.LookupError, ValueError):
960 960 pass
961 961 return t
962 962
963 963 def _findtags(self):
964 964 '''Do the hard work of finding tags. Return a pair of dicts
965 965 (tags, tagtypes) where tags maps tag name to node, and tagtypes
966 966 maps tag name to a string like \'global\' or \'local\'.
967 967 Subclasses or extensions are free to add their own tags, but
968 968 should be aware that the returned dicts will be retained for the
969 969 duration of the localrepo object.'''
970 970
971 971 # XXX what tagtype should subclasses/extensions use? Currently
972 972 # mq and bookmarks add tags, but do not set the tagtype at all.
973 973 # Should each extension invent its own tag type? Should there
974 974 # be one tagtype for all such "virtual" tags? Or is the status
975 975 # quo fine?
976 976
977 977
978 978 # map tag name to (node, hist)
979 979 alltags = tagsmod.findglobaltags(self.ui, self)
980 980 # map tag name to tag type
981 981 tagtypes = dict((tag, 'global') for tag in alltags)
982 982
983 983 tagsmod.readlocaltags(self.ui, self, alltags, tagtypes)
984 984
985 985 # Build the return dicts. Have to re-encode tag names because
986 986 # the tags module always uses UTF-8 (in order not to lose info
987 987 # writing to the cache), but the rest of Mercurial wants them in
988 988 # local encoding.
989 989 tags = {}
990 990 for (name, (node, hist)) in alltags.iteritems():
991 991 if node != nullid:
992 992 tags[encoding.tolocal(name)] = node
993 993 tags['tip'] = self.changelog.tip()
994 994 tagtypes = dict([(encoding.tolocal(name), value)
995 995 for (name, value) in tagtypes.iteritems()])
996 996 return (tags, tagtypes)
997 997
998 998 def tagtype(self, tagname):
999 999 '''
1000 1000 return the type of the given tag. result can be:
1001 1001
1002 1002 'local' : a local tag
1003 1003 'global' : a global tag
1004 1004 None : tag does not exist
1005 1005 '''
1006 1006
1007 1007 return self._tagscache.tagtypes.get(tagname)
1008 1008
1009 1009 def tagslist(self):
1010 1010 '''return a list of tags ordered by revision'''
1011 1011 if not self._tagscache.tagslist:
1012 1012 l = []
1013 1013 for t, n in self.tags().iteritems():
1014 1014 l.append((self.changelog.rev(n), t, n))
1015 1015 self._tagscache.tagslist = [(t, n) for r, t, n in sorted(l)]
1016 1016
1017 1017 return self._tagscache.tagslist
1018 1018
1019 1019 def nodetags(self, node):
1020 1020 '''return the tags associated with a node'''
1021 1021 if not self._tagscache.nodetagscache:
1022 1022 nodetagscache = {}
1023 1023 for t, n in self._tagscache.tags.iteritems():
1024 1024 nodetagscache.setdefault(n, []).append(t)
1025 1025 for tags in nodetagscache.itervalues():
1026 1026 tags.sort()
1027 1027 self._tagscache.nodetagscache = nodetagscache
1028 1028 return self._tagscache.nodetagscache.get(node, [])
1029 1029
1030 1030 def nodebookmarks(self, node):
1031 1031 """return the list of bookmarks pointing to the specified node"""
1032 1032 marks = []
1033 1033 for bookmark, n in self._bookmarks.iteritems():
1034 1034 if n == node:
1035 1035 marks.append(bookmark)
1036 1036 return sorted(marks)
1037 1037
1038 1038 def branchmap(self):
1039 1039 '''returns a dictionary {branch: [branchheads]} with branchheads
1040 1040 ordered by increasing revision number'''
1041 1041 branchmap.updatecache(self)
1042 1042 return self._branchcaches[self.filtername]
1043 1043
1044 1044 @unfilteredmethod
1045 1045 def revbranchcache(self):
1046 1046 if not self._revbranchcache:
1047 1047 self._revbranchcache = branchmap.revbranchcache(self.unfiltered())
1048 1048 return self._revbranchcache
1049 1049
1050 1050 def branchtip(self, branch, ignoremissing=False):
1051 1051 '''return the tip node for a given branch
1052 1052
1053 1053 If ignoremissing is True, then this method will not raise an error.
1054 1054 This is helpful for callers that only expect None for a missing branch
1055 1055 (e.g. namespace).
1056 1056
1057 1057 '''
1058 1058 try:
1059 1059 return self.branchmap().branchtip(branch)
1060 1060 except KeyError:
1061 1061 if not ignoremissing:
1062 1062 raise error.RepoLookupError(_("unknown branch '%s'") % branch)
1063 1063 else:
1064 1064 pass
1065 1065
1066 1066 def lookup(self, key):
1067 1067 return scmutil.revsymbol(self, key).node()
1068 1068
1069 1069 def lookupbranch(self, key):
1070 1070 if key in self.branchmap():
1071 1071 return key
1072 1072
1073 1073 return scmutil.revsymbol(self, key).branch()
1074 1074
1075 1075 def known(self, nodes):
1076 1076 cl = self.changelog
1077 1077 nm = cl.nodemap
1078 1078 filtered = cl.filteredrevs
1079 1079 result = []
1080 1080 for n in nodes:
1081 1081 r = nm.get(n)
1082 1082 resp = not (r is None or r in filtered)
1083 1083 result.append(resp)
1084 1084 return result
1085 1085
1086 1086 def local(self):
1087 1087 return self
1088 1088
1089 1089 def publishing(self):
1090 1090 # it's safe (and desirable) to trust the publish flag unconditionally
1091 1091 # so that we don't finalize changes shared between users via ssh or nfs
1092 1092 return self.ui.configbool('phases', 'publish', untrusted=True)
1093 1093
1094 1094 def cancopy(self):
1095 1095 # so statichttprepo's override of local() works
1096 1096 if not self.local():
1097 1097 return False
1098 1098 if not self.publishing():
1099 1099 return True
1100 1100 # if publishing we can't copy if there is filtered content
1101 1101 return not self.filtered('visible').changelog.filteredrevs
1102 1102
1103 1103 def shared(self):
1104 1104 '''the type of shared repository (None if not shared)'''
1105 1105 if self.sharedpath != self.path:
1106 1106 return 'store'
1107 1107 return None
1108 1108
1109 1109 def wjoin(self, f, *insidef):
1110 1110 return self.vfs.reljoin(self.root, f, *insidef)
1111 1111
1112 1112 def file(self, f):
1113 1113 if f[0] == '/':
1114 1114 f = f[1:]
1115 1115 return filelog.filelog(self.svfs, f)
1116 1116
1117 1117 def setparents(self, p1, p2=nullid):
1118 1118 with self.dirstate.parentchange():
1119 1119 copies = self.dirstate.setparents(p1, p2)
1120 1120 pctx = self[p1]
1121 1121 if copies:
1122 1122 # Adjust copy records, the dirstate cannot do it, it
1123 1123 # requires access to parents manifests. Preserve them
1124 1124 # only for entries added to first parent.
1125 1125 for f in copies:
1126 1126 if f not in pctx and copies[f] in pctx:
1127 1127 self.dirstate.copy(copies[f], f)
1128 1128 if p2 == nullid:
1129 1129 for f, s in sorted(self.dirstate.copies().items()):
1130 1130 if f not in pctx and s not in pctx:
1131 1131 self.dirstate.copy(None, f)
1132 1132
1133 1133 def filectx(self, path, changeid=None, fileid=None, changectx=None):
1134 1134 """changeid can be a changeset revision, node, or tag.
1135 1135 fileid can be a file revision or node."""
1136 1136 return context.filectx(self, path, changeid, fileid,
1137 1137 changectx=changectx)
1138 1138
1139 1139 def getcwd(self):
1140 1140 return self.dirstate.getcwd()
1141 1141
1142 1142 def pathto(self, f, cwd=None):
1143 1143 return self.dirstate.pathto(f, cwd)
1144 1144
1145 1145 def _loadfilter(self, filter):
1146 1146 if filter not in self._filterpats:
1147 1147 l = []
1148 1148 for pat, cmd in self.ui.configitems(filter):
1149 1149 if cmd == '!':
1150 1150 continue
1151 1151 mf = matchmod.match(self.root, '', [pat])
1152 1152 fn = None
1153 1153 params = cmd
1154 1154 for name, filterfn in self._datafilters.iteritems():
1155 1155 if cmd.startswith(name):
1156 1156 fn = filterfn
1157 1157 params = cmd[len(name):].lstrip()
1158 1158 break
1159 1159 if not fn:
1160 1160 fn = lambda s, c, **kwargs: procutil.filter(s, c)
1161 1161 # Wrap old filters not supporting keyword arguments
1162 1162 if not pycompat.getargspec(fn)[2]:
1163 1163 oldfn = fn
1164 1164 fn = lambda s, c, **kwargs: oldfn(s, c)
1165 1165 l.append((mf, fn, params))
1166 1166 self._filterpats[filter] = l
1167 1167 return self._filterpats[filter]
1168 1168
1169 1169 def _filter(self, filterpats, filename, data):
1170 1170 for mf, fn, cmd in filterpats:
1171 1171 if mf(filename):
1172 1172 self.ui.debug("filtering %s through %s\n" % (filename, cmd))
1173 1173 data = fn(data, cmd, ui=self.ui, repo=self, filename=filename)
1174 1174 break
1175 1175
1176 1176 return data
1177 1177
1178 1178 @unfilteredpropertycache
1179 1179 def _encodefilterpats(self):
1180 1180 return self._loadfilter('encode')
1181 1181
1182 1182 @unfilteredpropertycache
1183 1183 def _decodefilterpats(self):
1184 1184 return self._loadfilter('decode')
1185 1185
1186 1186 def adddatafilter(self, name, filter):
1187 1187 self._datafilters[name] = filter
1188 1188
1189 1189 def wread(self, filename):
1190 1190 if self.wvfs.islink(filename):
1191 1191 data = self.wvfs.readlink(filename)
1192 1192 else:
1193 1193 data = self.wvfs.read(filename)
1194 1194 return self._filter(self._encodefilterpats, filename, data)
1195 1195
1196 1196 def wwrite(self, filename, data, flags, backgroundclose=False, **kwargs):
1197 1197 """write ``data`` into ``filename`` in the working directory
1198 1198
1199 1199 This returns length of written (maybe decoded) data.
1200 1200 """
1201 1201 data = self._filter(self._decodefilterpats, filename, data)
1202 1202 if 'l' in flags:
1203 1203 self.wvfs.symlink(data, filename)
1204 1204 else:
1205 1205 self.wvfs.write(filename, data, backgroundclose=backgroundclose,
1206 1206 **kwargs)
1207 1207 if 'x' in flags:
1208 1208 self.wvfs.setflags(filename, False, True)
1209 1209 else:
1210 1210 self.wvfs.setflags(filename, False, False)
1211 1211 return len(data)
1212 1212
1213 1213 def wwritedata(self, filename, data):
1214 1214 return self._filter(self._decodefilterpats, filename, data)
1215 1215
1216 1216 def currenttransaction(self):
1217 1217 """return the current transaction or None if non exists"""
1218 1218 if self._transref:
1219 1219 tr = self._transref()
1220 1220 else:
1221 1221 tr = None
1222 1222
1223 1223 if tr and tr.running():
1224 1224 return tr
1225 1225 return None
1226 1226
1227 1227 def transaction(self, desc, report=None):
1228 1228 if (self.ui.configbool('devel', 'all-warnings')
1229 1229 or self.ui.configbool('devel', 'check-locks')):
1230 1230 if self._currentlock(self._lockref) is None:
1231 1231 raise error.ProgrammingError('transaction requires locking')
1232 1232 tr = self.currenttransaction()
1233 1233 if tr is not None:
1234 1234 return tr.nest(name=desc)
1235 1235
1236 1236 # abort here if the journal already exists
1237 1237 if self.svfs.exists("journal"):
1238 1238 raise error.RepoError(
1239 1239 _("abandoned transaction found"),
1240 1240 hint=_("run 'hg recover' to clean up transaction"))
1241 1241
1242 1242 idbase = "%.40f#%f" % (random.random(), time.time())
1243 1243 ha = hex(hashlib.sha1(idbase).digest())
1244 1244 txnid = 'TXN:' + ha
1245 1245 self.hook('pretxnopen', throw=True, txnname=desc, txnid=txnid)
1246 1246
1247 1247 self._writejournal(desc)
1248 1248 renames = [(vfs, x, undoname(x)) for vfs, x in self._journalfiles()]
1249 1249 if report:
1250 1250 rp = report
1251 1251 else:
1252 1252 rp = self.ui.warn
1253 1253 vfsmap = {'plain': self.vfs} # root of .hg/
1254 1254 # we must avoid cyclic reference between repo and transaction.
1255 1255 reporef = weakref.ref(self)
1256 1256 # Code to track tag movement
1257 1257 #
1258 1258 # Since tags are all handled as file content, it is actually quite hard
1259 1259 # to track these movement from a code perspective. So we fallback to a
1260 1260 # tracking at the repository level. One could envision to track changes
1261 1261 # to the '.hgtags' file through changegroup apply but that fails to
1262 1262 # cope with case where transaction expose new heads without changegroup
1263 1263 # being involved (eg: phase movement).
1264 1264 #
1265 1265 # For now, We gate the feature behind a flag since this likely comes
1266 1266 # with performance impacts. The current code run more often than needed
1267 1267 # and do not use caches as much as it could. The current focus is on
1268 1268 # the behavior of the feature so we disable it by default. The flag
1269 1269 # will be removed when we are happy with the performance impact.
1270 1270 #
1271 1271 # Once this feature is no longer experimental move the following
1272 1272 # documentation to the appropriate help section:
1273 1273 #
1274 1274 # The ``HG_TAG_MOVED`` variable will be set if the transaction touched
1275 1275 # tags (new or changed or deleted tags). In addition the details of
1276 1276 # these changes are made available in a file at:
1277 1277 # ``REPOROOT/.hg/changes/tags.changes``.
1278 1278 # Make sure you check for HG_TAG_MOVED before reading that file as it
1279 1279 # might exist from a previous transaction even if no tag were touched
1280 1280 # in this one. Changes are recorded in a line base format::
1281 1281 #
1282 1282 # <action> <hex-node> <tag-name>\n
1283 1283 #
1284 1284 # Actions are defined as follow:
1285 1285 # "-R": tag is removed,
1286 1286 # "+A": tag is added,
1287 1287 # "-M": tag is moved (old value),
1288 1288 # "+M": tag is moved (new value),
1289 1289 tracktags = lambda x: None
1290 1290 # experimental config: experimental.hook-track-tags
1291 1291 shouldtracktags = self.ui.configbool('experimental', 'hook-track-tags')
1292 1292 if desc != 'strip' and shouldtracktags:
1293 1293 oldheads = self.changelog.headrevs()
1294 1294 def tracktags(tr2):
1295 1295 repo = reporef()
1296 1296 oldfnodes = tagsmod.fnoderevs(repo.ui, repo, oldheads)
1297 1297 newheads = repo.changelog.headrevs()
1298 1298 newfnodes = tagsmod.fnoderevs(repo.ui, repo, newheads)
1299 1299 # notes: we compare lists here.
1300 1300 # As we do it only once buiding set would not be cheaper
1301 1301 changes = tagsmod.difftags(repo.ui, repo, oldfnodes, newfnodes)
1302 1302 if changes:
1303 1303 tr2.hookargs['tag_moved'] = '1'
1304 1304 with repo.vfs('changes/tags.changes', 'w',
1305 1305 atomictemp=True) as changesfile:
1306 1306 # note: we do not register the file to the transaction
1307 1307 # because we needs it to still exist on the transaction
1308 1308 # is close (for txnclose hooks)
1309 1309 tagsmod.writediff(changesfile, changes)
1310 1310 def validate(tr2):
1311 1311 """will run pre-closing hooks"""
1312 1312 # XXX the transaction API is a bit lacking here so we take a hacky
1313 1313 # path for now
1314 1314 #
1315 1315 # We cannot add this as a "pending" hooks since the 'tr.hookargs'
1316 1316 # dict is copied before these run. In addition we needs the data
1317 1317 # available to in memory hooks too.
1318 1318 #
1319 1319 # Moreover, we also need to make sure this runs before txnclose
1320 1320 # hooks and there is no "pending" mechanism that would execute
1321 1321 # logic only if hooks are about to run.
1322 1322 #
1323 1323 # Fixing this limitation of the transaction is also needed to track
1324 1324 # other families of changes (bookmarks, phases, obsolescence).
1325 1325 #
1326 1326 # This will have to be fixed before we remove the experimental
1327 1327 # gating.
1328 1328 tracktags(tr2)
1329 1329 repo = reporef()
1330 1330 if repo.ui.configbool('experimental', 'single-head-per-branch'):
1331 1331 scmutil.enforcesinglehead(repo, tr2, desc)
1332 1332 if hook.hashook(repo.ui, 'pretxnclose-bookmark'):
1333 1333 for name, (old, new) in sorted(tr.changes['bookmarks'].items()):
1334 1334 args = tr.hookargs.copy()
1335 1335 args.update(bookmarks.preparehookargs(name, old, new))
1336 1336 repo.hook('pretxnclose-bookmark', throw=True,
1337 1337 txnname=desc,
1338 1338 **pycompat.strkwargs(args))
1339 1339 if hook.hashook(repo.ui, 'pretxnclose-phase'):
1340 1340 cl = repo.unfiltered().changelog
1341 1341 for rev, (old, new) in tr.changes['phases'].items():
1342 1342 args = tr.hookargs.copy()
1343 1343 node = hex(cl.node(rev))
1344 1344 args.update(phases.preparehookargs(node, old, new))
1345 1345 repo.hook('pretxnclose-phase', throw=True, txnname=desc,
1346 1346 **pycompat.strkwargs(args))
1347 1347
1348 1348 repo.hook('pretxnclose', throw=True,
1349 1349 txnname=desc, **pycompat.strkwargs(tr.hookargs))
1350 1350 def releasefn(tr, success):
1351 1351 repo = reporef()
1352 1352 if success:
1353 1353 # this should be explicitly invoked here, because
1354 1354 # in-memory changes aren't written out at closing
1355 1355 # transaction, if tr.addfilegenerator (via
1356 1356 # dirstate.write or so) isn't invoked while
1357 1357 # transaction running
1358 1358 repo.dirstate.write(None)
1359 1359 else:
1360 1360 # discard all changes (including ones already written
1361 1361 # out) in this transaction
1362 1362 repo.dirstate.restorebackup(None, 'journal.dirstate')
1363 1363
1364 1364 repo.invalidate(clearfilecache=True)
1365 1365
1366 1366 tr = transaction.transaction(rp, self.svfs, vfsmap,
1367 1367 "journal",
1368 1368 "undo",
1369 1369 aftertrans(renames),
1370 1370 self.store.createmode,
1371 1371 validator=validate,
1372 1372 releasefn=releasefn,
1373 1373 checkambigfiles=_cachedfiles,
1374 1374 name=desc)
1375 1375 tr.changes['revs'] = xrange(0, 0)
1376 1376 tr.changes['obsmarkers'] = set()
1377 1377 tr.changes['phases'] = {}
1378 1378 tr.changes['bookmarks'] = {}
1379 1379
1380 1380 tr.hookargs['txnid'] = txnid
1381 1381 # note: writing the fncache only during finalize mean that the file is
1382 1382 # outdated when running hooks. As fncache is used for streaming clone,
1383 1383 # this is not expected to break anything that happen during the hooks.
1384 1384 tr.addfinalize('flush-fncache', self.store.write)
1385 1385 def txnclosehook(tr2):
1386 1386 """To be run if transaction is successful, will schedule a hook run
1387 1387 """
1388 1388 # Don't reference tr2 in hook() so we don't hold a reference.
1389 1389 # This reduces memory consumption when there are multiple
1390 1390 # transactions per lock. This can likely go away if issue5045
1391 1391 # fixes the function accumulation.
1392 1392 hookargs = tr2.hookargs
1393 1393
1394 1394 def hookfunc():
1395 1395 repo = reporef()
1396 1396 if hook.hashook(repo.ui, 'txnclose-bookmark'):
1397 1397 bmchanges = sorted(tr.changes['bookmarks'].items())
1398 1398 for name, (old, new) in bmchanges:
1399 1399 args = tr.hookargs.copy()
1400 1400 args.update(bookmarks.preparehookargs(name, old, new))
1401 1401 repo.hook('txnclose-bookmark', throw=False,
1402 1402 txnname=desc, **pycompat.strkwargs(args))
1403 1403
1404 1404 if hook.hashook(repo.ui, 'txnclose-phase'):
1405 1405 cl = repo.unfiltered().changelog
1406 1406 phasemv = sorted(tr.changes['phases'].items())
1407 1407 for rev, (old, new) in phasemv:
1408 1408 args = tr.hookargs.copy()
1409 1409 node = hex(cl.node(rev))
1410 1410 args.update(phases.preparehookargs(node, old, new))
1411 1411 repo.hook('txnclose-phase', throw=False, txnname=desc,
1412 1412 **pycompat.strkwargs(args))
1413 1413
1414 1414 repo.hook('txnclose', throw=False, txnname=desc,
1415 1415 **pycompat.strkwargs(hookargs))
1416 1416 reporef()._afterlock(hookfunc)
1417 1417 tr.addfinalize('txnclose-hook', txnclosehook)
1418 1418 # Include a leading "-" to make it happen before the transaction summary
1419 1419 # reports registered via scmutil.registersummarycallback() whose names
1420 1420 # are 00-txnreport etc. That way, the caches will be warm when the
1421 1421 # callbacks run.
1422 1422 tr.addpostclose('-warm-cache', self._buildcacheupdater(tr))
1423 1423 def txnaborthook(tr2):
1424 1424 """To be run if transaction is aborted
1425 1425 """
1426 1426 reporef().hook('txnabort', throw=False, txnname=desc,
1427 1427 **pycompat.strkwargs(tr2.hookargs))
1428 1428 tr.addabort('txnabort-hook', txnaborthook)
1429 1429 # avoid eager cache invalidation. in-memory data should be identical
1430 1430 # to stored data if transaction has no error.
1431 1431 tr.addpostclose('refresh-filecachestats', self._refreshfilecachestats)
1432 1432 self._transref = weakref.ref(tr)
1433 1433 scmutil.registersummarycallback(self, tr, desc)
1434 1434 return tr
1435 1435
1436 1436 def _journalfiles(self):
1437 1437 return ((self.svfs, 'journal'),
1438 1438 (self.vfs, 'journal.dirstate'),
1439 1439 (self.vfs, 'journal.branch'),
1440 1440 (self.vfs, 'journal.desc'),
1441 1441 (self.vfs, 'journal.bookmarks'),
1442 1442 (self.svfs, 'journal.phaseroots'))
1443 1443
1444 1444 def undofiles(self):
1445 1445 return [(vfs, undoname(x)) for vfs, x in self._journalfiles()]
1446 1446
1447 1447 @unfilteredmethod
1448 1448 def _writejournal(self, desc):
1449 1449 self.dirstate.savebackup(None, 'journal.dirstate')
1450 1450 self.vfs.write("journal.branch",
1451 1451 encoding.fromlocal(self.dirstate.branch()))
1452 1452 self.vfs.write("journal.desc",
1453 1453 "%d\n%s\n" % (len(self), desc))
1454 1454 self.vfs.write("journal.bookmarks",
1455 1455 self.vfs.tryread("bookmarks"))
1456 1456 self.svfs.write("journal.phaseroots",
1457 1457 self.svfs.tryread("phaseroots"))
1458 1458
1459 1459 def recover(self):
1460 1460 with self.lock():
1461 1461 if self.svfs.exists("journal"):
1462 1462 self.ui.status(_("rolling back interrupted transaction\n"))
1463 1463 vfsmap = {'': self.svfs,
1464 1464 'plain': self.vfs,}
1465 1465 transaction.rollback(self.svfs, vfsmap, "journal",
1466 1466 self.ui.warn,
1467 1467 checkambigfiles=_cachedfiles)
1468 1468 self.invalidate()
1469 1469 return True
1470 1470 else:
1471 1471 self.ui.warn(_("no interrupted transaction available\n"))
1472 1472 return False
1473 1473
1474 1474 def rollback(self, dryrun=False, force=False):
1475 1475 wlock = lock = dsguard = None
1476 1476 try:
1477 1477 wlock = self.wlock()
1478 1478 lock = self.lock()
1479 1479 if self.svfs.exists("undo"):
1480 1480 dsguard = dirstateguard.dirstateguard(self, 'rollback')
1481 1481
1482 1482 return self._rollback(dryrun, force, dsguard)
1483 1483 else:
1484 1484 self.ui.warn(_("no rollback information available\n"))
1485 1485 return 1
1486 1486 finally:
1487 1487 release(dsguard, lock, wlock)
1488 1488
1489 1489 @unfilteredmethod # Until we get smarter cache management
1490 1490 def _rollback(self, dryrun, force, dsguard):
1491 1491 ui = self.ui
1492 1492 try:
1493 1493 args = self.vfs.read('undo.desc').splitlines()
1494 1494 (oldlen, desc, detail) = (int(args[0]), args[1], None)
1495 1495 if len(args) >= 3:
1496 1496 detail = args[2]
1497 1497 oldtip = oldlen - 1
1498 1498
1499 1499 if detail and ui.verbose:
1500 1500 msg = (_('repository tip rolled back to revision %d'
1501 1501 ' (undo %s: %s)\n')
1502 1502 % (oldtip, desc, detail))
1503 1503 else:
1504 1504 msg = (_('repository tip rolled back to revision %d'
1505 1505 ' (undo %s)\n')
1506 1506 % (oldtip, desc))
1507 1507 except IOError:
1508 1508 msg = _('rolling back unknown transaction\n')
1509 1509 desc = None
1510 1510
1511 1511 if not force and self['.'] != self['tip'] and desc == 'commit':
1512 1512 raise error.Abort(
1513 1513 _('rollback of last commit while not checked out '
1514 1514 'may lose data'), hint=_('use -f to force'))
1515 1515
1516 1516 ui.status(msg)
1517 1517 if dryrun:
1518 1518 return 0
1519 1519
1520 1520 parents = self.dirstate.parents()
1521 1521 self.destroying()
1522 1522 vfsmap = {'plain': self.vfs, '': self.svfs}
1523 1523 transaction.rollback(self.svfs, vfsmap, 'undo', ui.warn,
1524 1524 checkambigfiles=_cachedfiles)
1525 1525 if self.vfs.exists('undo.bookmarks'):
1526 1526 self.vfs.rename('undo.bookmarks', 'bookmarks', checkambig=True)
1527 1527 if self.svfs.exists('undo.phaseroots'):
1528 1528 self.svfs.rename('undo.phaseroots', 'phaseroots', checkambig=True)
1529 1529 self.invalidate()
1530 1530
1531 1531 parentgone = (parents[0] not in self.changelog.nodemap or
1532 1532 parents[1] not in self.changelog.nodemap)
1533 1533 if parentgone:
1534 1534 # prevent dirstateguard from overwriting already restored one
1535 1535 dsguard.close()
1536 1536
1537 1537 self.dirstate.restorebackup(None, 'undo.dirstate')
1538 1538 try:
1539 1539 branch = self.vfs.read('undo.branch')
1540 1540 self.dirstate.setbranch(encoding.tolocal(branch))
1541 1541 except IOError:
1542 1542 ui.warn(_('named branch could not be reset: '
1543 1543 'current branch is still \'%s\'\n')
1544 1544 % self.dirstate.branch())
1545 1545
1546 1546 parents = tuple([p.rev() for p in self[None].parents()])
1547 1547 if len(parents) > 1:
1548 1548 ui.status(_('working directory now based on '
1549 1549 'revisions %d and %d\n') % parents)
1550 1550 else:
1551 1551 ui.status(_('working directory now based on '
1552 1552 'revision %d\n') % parents)
1553 1553 mergemod.mergestate.clean(self, self['.'].node())
1554 1554
1555 1555 # TODO: if we know which new heads may result from this rollback, pass
1556 1556 # them to destroy(), which will prevent the branchhead cache from being
1557 1557 # invalidated.
1558 1558 self.destroyed()
1559 1559 return 0
1560 1560
1561 1561 def _buildcacheupdater(self, newtransaction):
1562 1562 """called during transaction to build the callback updating cache
1563 1563
1564 1564 Lives on the repository to help extension who might want to augment
1565 1565 this logic. For this purpose, the created transaction is passed to the
1566 1566 method.
1567 1567 """
1568 1568 # we must avoid cyclic reference between repo and transaction.
1569 1569 reporef = weakref.ref(self)
1570 1570 def updater(tr):
1571 1571 repo = reporef()
1572 1572 repo.updatecaches(tr)
1573 1573 return updater
1574 1574
1575 1575 @unfilteredmethod
1576 1576 def updatecaches(self, tr=None, full=False):
1577 1577 """warm appropriate caches
1578 1578
1579 1579 If this function is called after a transaction closed. The transaction
1580 1580 will be available in the 'tr' argument. This can be used to selectively
1581 1581 update caches relevant to the changes in that transaction.
1582 1582
1583 1583 If 'full' is set, make sure all caches the function knows about have
1584 1584 up-to-date data. Even the ones usually loaded more lazily.
1585 1585 """
1586 1586 if tr is not None and tr.hookargs.get('source') == 'strip':
1587 1587 # During strip, many caches are invalid but
1588 1588 # later call to `destroyed` will refresh them.
1589 1589 return
1590 1590
1591 1591 if tr is None or tr.changes['revs']:
1592 1592 # updating the unfiltered branchmap should refresh all the others,
1593 1593 self.ui.debug('updating the branch cache\n')
1594 1594 branchmap.updatecache(self.filtered('served'))
1595 1595
1596 1596 if full:
1597 1597 rbc = self.revbranchcache()
1598 1598 for r in self.changelog:
1599 1599 rbc.branchinfo(r)
1600 1600 rbc.write()
1601 1601
1602 1602 def invalidatecaches(self):
1603 1603
1604 1604 if '_tagscache' in vars(self):
1605 1605 # can't use delattr on proxy
1606 1606 del self.__dict__['_tagscache']
1607 1607
1608 1608 self.unfiltered()._branchcaches.clear()
1609 1609 self.invalidatevolatilesets()
1610 1610 self._sparsesignaturecache.clear()
1611 1611
1612 1612 def invalidatevolatilesets(self):
1613 1613 self.filteredrevcache.clear()
1614 1614 obsolete.clearobscaches(self)
1615 1615
1616 1616 def invalidatedirstate(self):
1617 1617 '''Invalidates the dirstate, causing the next call to dirstate
1618 1618 to check if it was modified since the last time it was read,
1619 1619 rereading it if it has.
1620 1620
1621 1621 This is different to dirstate.invalidate() that it doesn't always
1622 1622 rereads the dirstate. Use dirstate.invalidate() if you want to
1623 1623 explicitly read the dirstate again (i.e. restoring it to a previous
1624 1624 known good state).'''
1625 1625 if hasunfilteredcache(self, 'dirstate'):
1626 1626 for k in self.dirstate._filecache:
1627 1627 try:
1628 1628 delattr(self.dirstate, k)
1629 1629 except AttributeError:
1630 1630 pass
1631 1631 delattr(self.unfiltered(), 'dirstate')
1632 1632
1633 1633 def invalidate(self, clearfilecache=False):
1634 1634 '''Invalidates both store and non-store parts other than dirstate
1635 1635
1636 1636 If a transaction is running, invalidation of store is omitted,
1637 1637 because discarding in-memory changes might cause inconsistency
1638 1638 (e.g. incomplete fncache causes unintentional failure, but
1639 1639 redundant one doesn't).
1640 1640 '''
1641 1641 unfiltered = self.unfiltered() # all file caches are stored unfiltered
1642 1642 for k in list(self._filecache.keys()):
1643 1643 # dirstate is invalidated separately in invalidatedirstate()
1644 1644 if k == 'dirstate':
1645 1645 continue
1646 1646 if (k == 'changelog' and
1647 1647 self.currenttransaction() and
1648 1648 self.changelog._delayed):
1649 1649 # The changelog object may store unwritten revisions. We don't
1650 1650 # want to lose them.
1651 1651 # TODO: Solve the problem instead of working around it.
1652 1652 continue
1653 1653
1654 1654 if clearfilecache:
1655 1655 del self._filecache[k]
1656 1656 try:
1657 1657 delattr(unfiltered, k)
1658 1658 except AttributeError:
1659 1659 pass
1660 1660 self.invalidatecaches()
1661 1661 if not self.currenttransaction():
1662 1662 # TODO: Changing contents of store outside transaction
1663 1663 # causes inconsistency. We should make in-memory store
1664 1664 # changes detectable, and abort if changed.
1665 1665 self.store.invalidatecaches()
1666 1666
1667 1667 def invalidateall(self):
1668 1668 '''Fully invalidates both store and non-store parts, causing the
1669 1669 subsequent operation to reread any outside changes.'''
1670 1670 # extension should hook this to invalidate its caches
1671 1671 self.invalidate()
1672 1672 self.invalidatedirstate()
1673 1673
1674 1674 @unfilteredmethod
1675 1675 def _refreshfilecachestats(self, tr):
1676 1676 """Reload stats of cached files so that they are flagged as valid"""
1677 1677 for k, ce in self._filecache.items():
1678 1678 k = pycompat.sysstr(k)
1679 1679 if k == r'dirstate' or k not in self.__dict__:
1680 1680 continue
1681 1681 ce.refresh()
1682 1682
1683 1683 def _lock(self, vfs, lockname, wait, releasefn, acquirefn, desc,
1684 1684 inheritchecker=None, parentenvvar=None):
1685 1685 parentlock = None
1686 1686 # the contents of parentenvvar are used by the underlying lock to
1687 1687 # determine whether it can be inherited
1688 1688 if parentenvvar is not None:
1689 1689 parentlock = encoding.environ.get(parentenvvar)
1690 1690
1691 1691 timeout = 0
1692 1692 warntimeout = 0
1693 1693 if wait:
1694 1694 timeout = self.ui.configint("ui", "timeout")
1695 1695 warntimeout = self.ui.configint("ui", "timeout.warn")
1696 # internal config: ui.signal-safe-lock
1697 signalsafe = self.ui.configbool('ui', 'signal-safe-lock')
1696 1698
1697 1699 l = lockmod.trylock(self.ui, vfs, lockname, timeout, warntimeout,
1698 1700 releasefn=releasefn,
1699 1701 acquirefn=acquirefn, desc=desc,
1700 1702 inheritchecker=inheritchecker,
1701 parentlock=parentlock)
1703 parentlock=parentlock,
1704 signalsafe=signalsafe)
1702 1705 return l
1703 1706
1704 1707 def _afterlock(self, callback):
1705 1708 """add a callback to be run when the repository is fully unlocked
1706 1709
1707 1710 The callback will be executed when the outermost lock is released
1708 1711 (with wlock being higher level than 'lock')."""
1709 1712 for ref in (self._wlockref, self._lockref):
1710 1713 l = ref and ref()
1711 1714 if l and l.held:
1712 1715 l.postrelease.append(callback)
1713 1716 break
1714 1717 else: # no lock have been found.
1715 1718 callback()
1716 1719
1717 1720 def lock(self, wait=True):
1718 1721 '''Lock the repository store (.hg/store) and return a weak reference
1719 1722 to the lock. Use this before modifying the store (e.g. committing or
1720 1723 stripping). If you are opening a transaction, get a lock as well.)
1721 1724
1722 1725 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1723 1726 'wlock' first to avoid a dead-lock hazard.'''
1724 1727 l = self._currentlock(self._lockref)
1725 1728 if l is not None:
1726 1729 l.lock()
1727 1730 return l
1728 1731
1729 1732 l = self._lock(self.svfs, "lock", wait, None,
1730 1733 self.invalidate, _('repository %s') % self.origroot)
1731 1734 self._lockref = weakref.ref(l)
1732 1735 return l
1733 1736
1734 1737 def _wlockchecktransaction(self):
1735 1738 if self.currenttransaction() is not None:
1736 1739 raise error.LockInheritanceContractViolation(
1737 1740 'wlock cannot be inherited in the middle of a transaction')
1738 1741
1739 1742 def wlock(self, wait=True):
1740 1743 '''Lock the non-store parts of the repository (everything under
1741 1744 .hg except .hg/store) and return a weak reference to the lock.
1742 1745
1743 1746 Use this before modifying files in .hg.
1744 1747
1745 1748 If both 'lock' and 'wlock' must be acquired, ensure you always acquires
1746 1749 'wlock' first to avoid a dead-lock hazard.'''
1747 1750 l = self._wlockref and self._wlockref()
1748 1751 if l is not None and l.held:
1749 1752 l.lock()
1750 1753 return l
1751 1754
1752 1755 # We do not need to check for non-waiting lock acquisition. Such
1753 1756 # acquisition would not cause dead-lock as they would just fail.
1754 1757 if wait and (self.ui.configbool('devel', 'all-warnings')
1755 1758 or self.ui.configbool('devel', 'check-locks')):
1756 1759 if self._currentlock(self._lockref) is not None:
1757 1760 self.ui.develwarn('"wlock" acquired after "lock"')
1758 1761
1759 1762 def unlock():
1760 1763 if self.dirstate.pendingparentchange():
1761 1764 self.dirstate.invalidate()
1762 1765 else:
1763 1766 self.dirstate.write(None)
1764 1767
1765 1768 self._filecache['dirstate'].refresh()
1766 1769
1767 1770 l = self._lock(self.vfs, "wlock", wait, unlock,
1768 1771 self.invalidatedirstate, _('working directory of %s') %
1769 1772 self.origroot,
1770 1773 inheritchecker=self._wlockchecktransaction,
1771 1774 parentenvvar='HG_WLOCK_LOCKER')
1772 1775 self._wlockref = weakref.ref(l)
1773 1776 return l
1774 1777
1775 1778 def _currentlock(self, lockref):
1776 1779 """Returns the lock if it's held, or None if it's not."""
1777 1780 if lockref is None:
1778 1781 return None
1779 1782 l = lockref()
1780 1783 if l is None or not l.held:
1781 1784 return None
1782 1785 return l
1783 1786
1784 1787 def currentwlock(self):
1785 1788 """Returns the wlock if it's held, or None if it's not."""
1786 1789 return self._currentlock(self._wlockref)
1787 1790
1788 1791 def _filecommit(self, fctx, manifest1, manifest2, linkrev, tr, changelist):
1789 1792 """
1790 1793 commit an individual file as part of a larger transaction
1791 1794 """
1792 1795
1793 1796 fname = fctx.path()
1794 1797 fparent1 = manifest1.get(fname, nullid)
1795 1798 fparent2 = manifest2.get(fname, nullid)
1796 1799 if isinstance(fctx, context.filectx):
1797 1800 node = fctx.filenode()
1798 1801 if node in [fparent1, fparent2]:
1799 1802 self.ui.debug('reusing %s filelog entry\n' % fname)
1800 1803 if manifest1.flags(fname) != fctx.flags():
1801 1804 changelist.append(fname)
1802 1805 return node
1803 1806
1804 1807 flog = self.file(fname)
1805 1808 meta = {}
1806 1809 copy = fctx.renamed()
1807 1810 if copy and copy[0] != fname:
1808 1811 # Mark the new revision of this file as a copy of another
1809 1812 # file. This copy data will effectively act as a parent
1810 1813 # of this new revision. If this is a merge, the first
1811 1814 # parent will be the nullid (meaning "look up the copy data")
1812 1815 # and the second one will be the other parent. For example:
1813 1816 #
1814 1817 # 0 --- 1 --- 3 rev1 changes file foo
1815 1818 # \ / rev2 renames foo to bar and changes it
1816 1819 # \- 2 -/ rev3 should have bar with all changes and
1817 1820 # should record that bar descends from
1818 1821 # bar in rev2 and foo in rev1
1819 1822 #
1820 1823 # this allows this merge to succeed:
1821 1824 #
1822 1825 # 0 --- 1 --- 3 rev4 reverts the content change from rev2
1823 1826 # \ / merging rev3 and rev4 should use bar@rev2
1824 1827 # \- 2 --- 4 as the merge base
1825 1828 #
1826 1829
1827 1830 cfname = copy[0]
1828 1831 crev = manifest1.get(cfname)
1829 1832 newfparent = fparent2
1830 1833
1831 1834 if manifest2: # branch merge
1832 1835 if fparent2 == nullid or crev is None: # copied on remote side
1833 1836 if cfname in manifest2:
1834 1837 crev = manifest2[cfname]
1835 1838 newfparent = fparent1
1836 1839
1837 1840 # Here, we used to search backwards through history to try to find
1838 1841 # where the file copy came from if the source of a copy was not in
1839 1842 # the parent directory. However, this doesn't actually make sense to
1840 1843 # do (what does a copy from something not in your working copy even
1841 1844 # mean?) and it causes bugs (eg, issue4476). Instead, we will warn
1842 1845 # the user that copy information was dropped, so if they didn't
1843 1846 # expect this outcome it can be fixed, but this is the correct
1844 1847 # behavior in this circumstance.
1845 1848
1846 1849 if crev:
1847 1850 self.ui.debug(" %s: copy %s:%s\n" % (fname, cfname, hex(crev)))
1848 1851 meta["copy"] = cfname
1849 1852 meta["copyrev"] = hex(crev)
1850 1853 fparent1, fparent2 = nullid, newfparent
1851 1854 else:
1852 1855 self.ui.warn(_("warning: can't find ancestor for '%s' "
1853 1856 "copied from '%s'!\n") % (fname, cfname))
1854 1857
1855 1858 elif fparent1 == nullid:
1856 1859 fparent1, fparent2 = fparent2, nullid
1857 1860 elif fparent2 != nullid:
1858 1861 # is one parent an ancestor of the other?
1859 1862 fparentancestors = flog.commonancestorsheads(fparent1, fparent2)
1860 1863 if fparent1 in fparentancestors:
1861 1864 fparent1, fparent2 = fparent2, nullid
1862 1865 elif fparent2 in fparentancestors:
1863 1866 fparent2 = nullid
1864 1867
1865 1868 # is the file changed?
1866 1869 text = fctx.data()
1867 1870 if fparent2 != nullid or flog.cmp(fparent1, text) or meta:
1868 1871 changelist.append(fname)
1869 1872 return flog.add(text, meta, tr, linkrev, fparent1, fparent2)
1870 1873 # are just the flags changed during merge?
1871 1874 elif fname in manifest1 and manifest1.flags(fname) != fctx.flags():
1872 1875 changelist.append(fname)
1873 1876
1874 1877 return fparent1
1875 1878
1876 1879 def checkcommitpatterns(self, wctx, vdirs, match, status, fail):
1877 1880 """check for commit arguments that aren't committable"""
1878 1881 if match.isexact() or match.prefix():
1879 1882 matched = set(status.modified + status.added + status.removed)
1880 1883
1881 1884 for f in match.files():
1882 1885 f = self.dirstate.normalize(f)
1883 1886 if f == '.' or f in matched or f in wctx.substate:
1884 1887 continue
1885 1888 if f in status.deleted:
1886 1889 fail(f, _('file not found!'))
1887 1890 if f in vdirs: # visited directory
1888 1891 d = f + '/'
1889 1892 for mf in matched:
1890 1893 if mf.startswith(d):
1891 1894 break
1892 1895 else:
1893 1896 fail(f, _("no match under directory!"))
1894 1897 elif f not in self.dirstate:
1895 1898 fail(f, _("file not tracked!"))
1896 1899
1897 1900 @unfilteredmethod
1898 1901 def commit(self, text="", user=None, date=None, match=None, force=False,
1899 1902 editor=False, extra=None):
1900 1903 """Add a new revision to current repository.
1901 1904
1902 1905 Revision information is gathered from the working directory,
1903 1906 match can be used to filter the committed files. If editor is
1904 1907 supplied, it is called to get a commit message.
1905 1908 """
1906 1909 if extra is None:
1907 1910 extra = {}
1908 1911
1909 1912 def fail(f, msg):
1910 1913 raise error.Abort('%s: %s' % (f, msg))
1911 1914
1912 1915 if not match:
1913 1916 match = matchmod.always(self.root, '')
1914 1917
1915 1918 if not force:
1916 1919 vdirs = []
1917 1920 match.explicitdir = vdirs.append
1918 1921 match.bad = fail
1919 1922
1920 1923 wlock = lock = tr = None
1921 1924 try:
1922 1925 wlock = self.wlock()
1923 1926 lock = self.lock() # for recent changelog (see issue4368)
1924 1927
1925 1928 wctx = self[None]
1926 1929 merge = len(wctx.parents()) > 1
1927 1930
1928 1931 if not force and merge and not match.always():
1929 1932 raise error.Abort(_('cannot partially commit a merge '
1930 1933 '(do not specify files or patterns)'))
1931 1934
1932 1935 status = self.status(match=match, clean=force)
1933 1936 if force:
1934 1937 status.modified.extend(status.clean) # mq may commit clean files
1935 1938
1936 1939 # check subrepos
1937 1940 subs, commitsubs, newstate = subrepoutil.precommit(
1938 1941 self.ui, wctx, status, match, force=force)
1939 1942
1940 1943 # make sure all explicit patterns are matched
1941 1944 if not force:
1942 1945 self.checkcommitpatterns(wctx, vdirs, match, status, fail)
1943 1946
1944 1947 cctx = context.workingcommitctx(self, status,
1945 1948 text, user, date, extra)
1946 1949
1947 1950 # internal config: ui.allowemptycommit
1948 1951 allowemptycommit = (wctx.branch() != wctx.p1().branch()
1949 1952 or extra.get('close') or merge or cctx.files()
1950 1953 or self.ui.configbool('ui', 'allowemptycommit'))
1951 1954 if not allowemptycommit:
1952 1955 return None
1953 1956
1954 1957 if merge and cctx.deleted():
1955 1958 raise error.Abort(_("cannot commit merge with missing files"))
1956 1959
1957 1960 ms = mergemod.mergestate.read(self)
1958 1961 mergeutil.checkunresolved(ms)
1959 1962
1960 1963 if editor:
1961 1964 cctx._text = editor(self, cctx, subs)
1962 1965 edited = (text != cctx._text)
1963 1966
1964 1967 # Save commit message in case this transaction gets rolled back
1965 1968 # (e.g. by a pretxncommit hook). Leave the content alone on
1966 1969 # the assumption that the user will use the same editor again.
1967 1970 msgfn = self.savecommitmessage(cctx._text)
1968 1971
1969 1972 # commit subs and write new state
1970 1973 if subs:
1971 1974 for s in sorted(commitsubs):
1972 1975 sub = wctx.sub(s)
1973 1976 self.ui.status(_('committing subrepository %s\n') %
1974 1977 subrepoutil.subrelpath(sub))
1975 1978 sr = sub.commit(cctx._text, user, date)
1976 1979 newstate[s] = (newstate[s][0], sr)
1977 1980 subrepoutil.writestate(self, newstate)
1978 1981
1979 1982 p1, p2 = self.dirstate.parents()
1980 1983 hookp1, hookp2 = hex(p1), (p2 != nullid and hex(p2) or '')
1981 1984 try:
1982 1985 self.hook("precommit", throw=True, parent1=hookp1,
1983 1986 parent2=hookp2)
1984 1987 tr = self.transaction('commit')
1985 1988 ret = self.commitctx(cctx, True)
1986 1989 except: # re-raises
1987 1990 if edited:
1988 1991 self.ui.write(
1989 1992 _('note: commit message saved in %s\n') % msgfn)
1990 1993 raise
1991 1994 # update bookmarks, dirstate and mergestate
1992 1995 bookmarks.update(self, [p1, p2], ret)
1993 1996 cctx.markcommitted(ret)
1994 1997 ms.reset()
1995 1998 tr.close()
1996 1999
1997 2000 finally:
1998 2001 lockmod.release(tr, lock, wlock)
1999 2002
2000 2003 def commithook(node=hex(ret), parent1=hookp1, parent2=hookp2):
2001 2004 # hack for command that use a temporary commit (eg: histedit)
2002 2005 # temporary commit got stripped before hook release
2003 2006 if self.changelog.hasnode(ret):
2004 2007 self.hook("commit", node=node, parent1=parent1,
2005 2008 parent2=parent2)
2006 2009 self._afterlock(commithook)
2007 2010 return ret
2008 2011
2009 2012 @unfilteredmethod
2010 2013 def commitctx(self, ctx, error=False):
2011 2014 """Add a new revision to current repository.
2012 2015 Revision information is passed via the context argument.
2013 2016 """
2014 2017
2015 2018 tr = None
2016 2019 p1, p2 = ctx.p1(), ctx.p2()
2017 2020 user = ctx.user()
2018 2021
2019 2022 lock = self.lock()
2020 2023 try:
2021 2024 tr = self.transaction("commit")
2022 2025 trp = weakref.proxy(tr)
2023 2026
2024 2027 if ctx.manifestnode():
2025 2028 # reuse an existing manifest revision
2026 2029 mn = ctx.manifestnode()
2027 2030 files = ctx.files()
2028 2031 elif ctx.files():
2029 2032 m1ctx = p1.manifestctx()
2030 2033 m2ctx = p2.manifestctx()
2031 2034 mctx = m1ctx.copy()
2032 2035
2033 2036 m = mctx.read()
2034 2037 m1 = m1ctx.read()
2035 2038 m2 = m2ctx.read()
2036 2039
2037 2040 # check in files
2038 2041 added = []
2039 2042 changed = []
2040 2043 removed = list(ctx.removed())
2041 2044 linkrev = len(self)
2042 2045 self.ui.note(_("committing files:\n"))
2043 2046 for f in sorted(ctx.modified() + ctx.added()):
2044 2047 self.ui.note(f + "\n")
2045 2048 try:
2046 2049 fctx = ctx[f]
2047 2050 if fctx is None:
2048 2051 removed.append(f)
2049 2052 else:
2050 2053 added.append(f)
2051 2054 m[f] = self._filecommit(fctx, m1, m2, linkrev,
2052 2055 trp, changed)
2053 2056 m.setflag(f, fctx.flags())
2054 2057 except OSError as inst:
2055 2058 self.ui.warn(_("trouble committing %s!\n") % f)
2056 2059 raise
2057 2060 except IOError as inst:
2058 2061 errcode = getattr(inst, 'errno', errno.ENOENT)
2059 2062 if error or errcode and errcode != errno.ENOENT:
2060 2063 self.ui.warn(_("trouble committing %s!\n") % f)
2061 2064 raise
2062 2065
2063 2066 # update manifest
2064 2067 self.ui.note(_("committing manifest\n"))
2065 2068 removed = [f for f in sorted(removed) if f in m1 or f in m2]
2066 2069 drop = [f for f in removed if f in m]
2067 2070 for f in drop:
2068 2071 del m[f]
2069 2072 mn = mctx.write(trp, linkrev,
2070 2073 p1.manifestnode(), p2.manifestnode(),
2071 2074 added, drop)
2072 2075 files = changed + removed
2073 2076 else:
2074 2077 mn = p1.manifestnode()
2075 2078 files = []
2076 2079
2077 2080 # update changelog
2078 2081 self.ui.note(_("committing changelog\n"))
2079 2082 self.changelog.delayupdate(tr)
2080 2083 n = self.changelog.add(mn, files, ctx.description(),
2081 2084 trp, p1.node(), p2.node(),
2082 2085 user, ctx.date(), ctx.extra().copy())
2083 2086 xp1, xp2 = p1.hex(), p2 and p2.hex() or ''
2084 2087 self.hook('pretxncommit', throw=True, node=hex(n), parent1=xp1,
2085 2088 parent2=xp2)
2086 2089 # set the new commit is proper phase
2087 2090 targetphase = subrepoutil.newcommitphase(self.ui, ctx)
2088 2091 if targetphase:
2089 2092 # retract boundary do not alter parent changeset.
2090 2093 # if a parent have higher the resulting phase will
2091 2094 # be compliant anyway
2092 2095 #
2093 2096 # if minimal phase was 0 we don't need to retract anything
2094 2097 phases.registernew(self, tr, targetphase, [n])
2095 2098 tr.close()
2096 2099 return n
2097 2100 finally:
2098 2101 if tr:
2099 2102 tr.release()
2100 2103 lock.release()
2101 2104
2102 2105 @unfilteredmethod
2103 2106 def destroying(self):
2104 2107 '''Inform the repository that nodes are about to be destroyed.
2105 2108 Intended for use by strip and rollback, so there's a common
2106 2109 place for anything that has to be done before destroying history.
2107 2110
2108 2111 This is mostly useful for saving state that is in memory and waiting
2109 2112 to be flushed when the current lock is released. Because a call to
2110 2113 destroyed is imminent, the repo will be invalidated causing those
2111 2114 changes to stay in memory (waiting for the next unlock), or vanish
2112 2115 completely.
2113 2116 '''
2114 2117 # When using the same lock to commit and strip, the phasecache is left
2115 2118 # dirty after committing. Then when we strip, the repo is invalidated,
2116 2119 # causing those changes to disappear.
2117 2120 if '_phasecache' in vars(self):
2118 2121 self._phasecache.write()
2119 2122
2120 2123 @unfilteredmethod
2121 2124 def destroyed(self):
2122 2125 '''Inform the repository that nodes have been destroyed.
2123 2126 Intended for use by strip and rollback, so there's a common
2124 2127 place for anything that has to be done after destroying history.
2125 2128 '''
2126 2129 # When one tries to:
2127 2130 # 1) destroy nodes thus calling this method (e.g. strip)
2128 2131 # 2) use phasecache somewhere (e.g. commit)
2129 2132 #
2130 2133 # then 2) will fail because the phasecache contains nodes that were
2131 2134 # removed. We can either remove phasecache from the filecache,
2132 2135 # causing it to reload next time it is accessed, or simply filter
2133 2136 # the removed nodes now and write the updated cache.
2134 2137 self._phasecache.filterunknown(self)
2135 2138 self._phasecache.write()
2136 2139
2137 2140 # refresh all repository caches
2138 2141 self.updatecaches()
2139 2142
2140 2143 # Ensure the persistent tag cache is updated. Doing it now
2141 2144 # means that the tag cache only has to worry about destroyed
2142 2145 # heads immediately after a strip/rollback. That in turn
2143 2146 # guarantees that "cachetip == currenttip" (comparing both rev
2144 2147 # and node) always means no nodes have been added or destroyed.
2145 2148
2146 2149 # XXX this is suboptimal when qrefresh'ing: we strip the current
2147 2150 # head, refresh the tag cache, then immediately add a new head.
2148 2151 # But I think doing it this way is necessary for the "instant
2149 2152 # tag cache retrieval" case to work.
2150 2153 self.invalidate()
2151 2154
2152 2155 def status(self, node1='.', node2=None, match=None,
2153 2156 ignored=False, clean=False, unknown=False,
2154 2157 listsubrepos=False):
2155 2158 '''a convenience method that calls node1.status(node2)'''
2156 2159 return self[node1].status(node2, match, ignored, clean, unknown,
2157 2160 listsubrepos)
2158 2161
2159 2162 def addpostdsstatus(self, ps):
2160 2163 """Add a callback to run within the wlock, at the point at which status
2161 2164 fixups happen.
2162 2165
2163 2166 On status completion, callback(wctx, status) will be called with the
2164 2167 wlock held, unless the dirstate has changed from underneath or the wlock
2165 2168 couldn't be grabbed.
2166 2169
2167 2170 Callbacks should not capture and use a cached copy of the dirstate --
2168 2171 it might change in the meanwhile. Instead, they should access the
2169 2172 dirstate via wctx.repo().dirstate.
2170 2173
2171 2174 This list is emptied out after each status run -- extensions should
2172 2175 make sure it adds to this list each time dirstate.status is called.
2173 2176 Extensions should also make sure they don't call this for statuses
2174 2177 that don't involve the dirstate.
2175 2178 """
2176 2179
2177 2180 # The list is located here for uniqueness reasons -- it is actually
2178 2181 # managed by the workingctx, but that isn't unique per-repo.
2179 2182 self._postdsstatus.append(ps)
2180 2183
2181 2184 def postdsstatus(self):
2182 2185 """Used by workingctx to get the list of post-dirstate-status hooks."""
2183 2186 return self._postdsstatus
2184 2187
2185 2188 def clearpostdsstatus(self):
2186 2189 """Used by workingctx to clear post-dirstate-status hooks."""
2187 2190 del self._postdsstatus[:]
2188 2191
2189 2192 def heads(self, start=None):
2190 2193 if start is None:
2191 2194 cl = self.changelog
2192 2195 headrevs = reversed(cl.headrevs())
2193 2196 return [cl.node(rev) for rev in headrevs]
2194 2197
2195 2198 heads = self.changelog.heads(start)
2196 2199 # sort the output in rev descending order
2197 2200 return sorted(heads, key=self.changelog.rev, reverse=True)
2198 2201
2199 2202 def branchheads(self, branch=None, start=None, closed=False):
2200 2203 '''return a (possibly filtered) list of heads for the given branch
2201 2204
2202 2205 Heads are returned in topological order, from newest to oldest.
2203 2206 If branch is None, use the dirstate branch.
2204 2207 If start is not None, return only heads reachable from start.
2205 2208 If closed is True, return heads that are marked as closed as well.
2206 2209 '''
2207 2210 if branch is None:
2208 2211 branch = self[None].branch()
2209 2212 branches = self.branchmap()
2210 2213 if branch not in branches:
2211 2214 return []
2212 2215 # the cache returns heads ordered lowest to highest
2213 2216 bheads = list(reversed(branches.branchheads(branch, closed=closed)))
2214 2217 if start is not None:
2215 2218 # filter out the heads that cannot be reached from startrev
2216 2219 fbheads = set(self.changelog.nodesbetween([start], bheads)[2])
2217 2220 bheads = [h for h in bheads if h in fbheads]
2218 2221 return bheads
2219 2222
2220 2223 def branches(self, nodes):
2221 2224 if not nodes:
2222 2225 nodes = [self.changelog.tip()]
2223 2226 b = []
2224 2227 for n in nodes:
2225 2228 t = n
2226 2229 while True:
2227 2230 p = self.changelog.parents(n)
2228 2231 if p[1] != nullid or p[0] == nullid:
2229 2232 b.append((t, n, p[0], p[1]))
2230 2233 break
2231 2234 n = p[0]
2232 2235 return b
2233 2236
2234 2237 def between(self, pairs):
2235 2238 r = []
2236 2239
2237 2240 for top, bottom in pairs:
2238 2241 n, l, i = top, [], 0
2239 2242 f = 1
2240 2243
2241 2244 while n != bottom and n != nullid:
2242 2245 p = self.changelog.parents(n)[0]
2243 2246 if i == f:
2244 2247 l.append(n)
2245 2248 f = f * 2
2246 2249 n = p
2247 2250 i += 1
2248 2251
2249 2252 r.append(l)
2250 2253
2251 2254 return r
2252 2255
2253 2256 def checkpush(self, pushop):
2254 2257 """Extensions can override this function if additional checks have
2255 2258 to be performed before pushing, or call it if they override push
2256 2259 command.
2257 2260 """
2258 2261
2259 2262 @unfilteredpropertycache
2260 2263 def prepushoutgoinghooks(self):
2261 2264 """Return util.hooks consists of a pushop with repo, remote, outgoing
2262 2265 methods, which are called before pushing changesets.
2263 2266 """
2264 2267 return util.hooks()
2265 2268
2266 2269 def pushkey(self, namespace, key, old, new):
2267 2270 try:
2268 2271 tr = self.currenttransaction()
2269 2272 hookargs = {}
2270 2273 if tr is not None:
2271 2274 hookargs.update(tr.hookargs)
2272 2275 hookargs = pycompat.strkwargs(hookargs)
2273 2276 hookargs[r'namespace'] = namespace
2274 2277 hookargs[r'key'] = key
2275 2278 hookargs[r'old'] = old
2276 2279 hookargs[r'new'] = new
2277 2280 self.hook('prepushkey', throw=True, **hookargs)
2278 2281 except error.HookAbort as exc:
2279 2282 self.ui.write_err(_("pushkey-abort: %s\n") % exc)
2280 2283 if exc.hint:
2281 2284 self.ui.write_err(_("(%s)\n") % exc.hint)
2282 2285 return False
2283 2286 self.ui.debug('pushing key for "%s:%s"\n' % (namespace, key))
2284 2287 ret = pushkey.push(self, namespace, key, old, new)
2285 2288 def runhook():
2286 2289 self.hook('pushkey', namespace=namespace, key=key, old=old, new=new,
2287 2290 ret=ret)
2288 2291 self._afterlock(runhook)
2289 2292 return ret
2290 2293
2291 2294 def listkeys(self, namespace):
2292 2295 self.hook('prelistkeys', throw=True, namespace=namespace)
2293 2296 self.ui.debug('listing keys for "%s"\n' % namespace)
2294 2297 values = pushkey.list(self, namespace)
2295 2298 self.hook('listkeys', namespace=namespace, values=values)
2296 2299 return values
2297 2300
2298 2301 def debugwireargs(self, one, two, three=None, four=None, five=None):
2299 2302 '''used to test argument passing over the wire'''
2300 2303 return "%s %s %s %s %s" % (one, two, pycompat.bytestr(three),
2301 2304 pycompat.bytestr(four),
2302 2305 pycompat.bytestr(five))
2303 2306
2304 2307 def savecommitmessage(self, text):
2305 2308 fp = self.vfs('last-message.txt', 'wb')
2306 2309 try:
2307 2310 fp.write(text)
2308 2311 finally:
2309 2312 fp.close()
2310 2313 return self.pathto(fp.name[len(self.root) + 1:])
2311 2314
2312 2315 # used to avoid circular references so destructors work
2313 2316 def aftertrans(files):
2314 2317 renamefiles = [tuple(t) for t in files]
2315 2318 def a():
2316 2319 for vfs, src, dest in renamefiles:
2317 2320 # if src and dest refer to a same file, vfs.rename is a no-op,
2318 2321 # leaving both src and dest on disk. delete dest to make sure
2319 2322 # the rename couldn't be such a no-op.
2320 2323 vfs.tryunlink(dest)
2321 2324 try:
2322 2325 vfs.rename(src, dest)
2323 2326 except OSError: # journal file does not yet exist
2324 2327 pass
2325 2328 return a
2326 2329
2327 2330 def undoname(fn):
2328 2331 base, name = os.path.split(fn)
2329 2332 assert name.startswith('journal')
2330 2333 return os.path.join(base, name.replace('journal', 'undo', 1))
2331 2334
2332 2335 def instance(ui, path, create, intents=None):
2333 2336 return localrepository(ui, util.urllocalpath(path), create,
2334 2337 intents=intents)
2335 2338
2336 2339 def islocal(path):
2337 2340 return True
2338 2341
2339 2342 def newreporequirements(repo):
2340 2343 """Determine the set of requirements for a new local repository.
2341 2344
2342 2345 Extensions can wrap this function to specify custom requirements for
2343 2346 new repositories.
2344 2347 """
2345 2348 ui = repo.ui
2346 2349 requirements = {'revlogv1'}
2347 2350 if ui.configbool('format', 'usestore'):
2348 2351 requirements.add('store')
2349 2352 if ui.configbool('format', 'usefncache'):
2350 2353 requirements.add('fncache')
2351 2354 if ui.configbool('format', 'dotencode'):
2352 2355 requirements.add('dotencode')
2353 2356
2354 2357 compengine = ui.config('experimental', 'format.compression')
2355 2358 if compengine not in util.compengines:
2356 2359 raise error.Abort(_('compression engine %s defined by '
2357 2360 'experimental.format.compression not available') %
2358 2361 compengine,
2359 2362 hint=_('run "hg debuginstall" to list available '
2360 2363 'compression engines'))
2361 2364
2362 2365 # zlib is the historical default and doesn't need an explicit requirement.
2363 2366 if compengine != 'zlib':
2364 2367 requirements.add('exp-compression-%s' % compengine)
2365 2368
2366 2369 if scmutil.gdinitconfig(ui):
2367 2370 requirements.add('generaldelta')
2368 2371 if ui.configbool('experimental', 'treemanifest'):
2369 2372 requirements.add('treemanifest')
2370 2373
2371 2374 revlogv2 = ui.config('experimental', 'revlogv2')
2372 2375 if revlogv2 == 'enable-unstable-format-and-corrupt-my-data':
2373 2376 requirements.remove('revlogv1')
2374 2377 # generaldelta is implied by revlogv2.
2375 2378 requirements.discard('generaldelta')
2376 2379 requirements.add(REVLOGV2_REQUIREMENT)
2377 2380
2378 2381 return requirements
@@ -1,392 +1,397 b''
1 1 # lock.py - simple advisory locking scheme for mercurial
2 2 #
3 3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import contextlib
11 11 import errno
12 12 import os
13 13 import signal
14 14 import socket
15 15 import time
16 16 import warnings
17 17
18 18 from .i18n import _
19 19
20 20 from . import (
21 21 encoding,
22 22 error,
23 23 pycompat,
24 util,
24 25 )
25 26
26 27 from .utils import (
27 28 procutil,
28 29 )
29 30
30 31 def _getlockprefix():
31 32 """Return a string which is used to differentiate pid namespaces
32 33
33 34 It's useful to detect "dead" processes and remove stale locks with
34 35 confidence. Typically it's just hostname. On modern linux, we include an
35 36 extra Linux-specific pid namespace identifier.
36 37 """
37 38 result = encoding.strtolocal(socket.gethostname())
38 39 if pycompat.sysplatform.startswith('linux'):
39 40 try:
40 41 result += '/%x' % os.stat('/proc/self/ns/pid').st_ino
41 42 except OSError as ex:
42 43 if ex.errno not in (errno.ENOENT, errno.EACCES, errno.ENOTDIR):
43 44 raise
44 45 return result
45 46
46 47 @contextlib.contextmanager
47 48 def _delayedinterrupt():
48 49 """Block signal interrupt while doing something critical
49 50
50 51 This makes sure that the code block wrapped by this context manager won't
51 52 be interrupted.
52 53
53 54 For Windows developers: It appears not possible to guard time.sleep()
54 55 from CTRL_C_EVENT, so please don't use time.sleep() to test if this is
55 56 working.
56 57 """
57 58 assertedsigs = []
58 59 blocked = False
59 60 orighandlers = {}
60 61
61 62 def raiseinterrupt(num):
62 63 if (num == getattr(signal, 'SIGINT', None) or
63 64 num == getattr(signal, 'CTRL_C_EVENT', None)):
64 65 raise KeyboardInterrupt
65 66 else:
66 67 raise error.SignalInterrupt
67 68 def catchterm(num, frame):
68 69 if blocked:
69 70 assertedsigs.append(num)
70 71 else:
71 72 raiseinterrupt(num)
72 73
73 74 try:
74 75 # save handlers first so they can be restored even if a setup is
75 76 # interrupted between signal.signal() and orighandlers[] =.
76 77 for name in ['CTRL_C_EVENT', 'SIGINT', 'SIGBREAK', 'SIGHUP', 'SIGTERM']:
77 78 num = getattr(signal, name, None)
78 79 if num and num not in orighandlers:
79 80 orighandlers[num] = signal.getsignal(num)
80 81 try:
81 82 for num in orighandlers:
82 83 signal.signal(num, catchterm)
83 84 except ValueError:
84 85 pass # in a thread? no luck
85 86
86 87 blocked = True
87 88 yield
88 89 finally:
89 90 # no simple way to reliably restore all signal handlers because
90 91 # any loops, recursive function calls, except blocks, etc. can be
91 92 # interrupted. so instead, make catchterm() raise interrupt.
92 93 blocked = False
93 94 try:
94 95 for num, handler in orighandlers.items():
95 96 signal.signal(num, handler)
96 97 except ValueError:
97 98 pass # in a thread?
98 99
99 100 # re-raise interrupt exception if any, which may be shadowed by a new
100 101 # interrupt occurred while re-raising the first one
101 102 if assertedsigs:
102 103 raiseinterrupt(assertedsigs[0])
103 104
104 105 def trylock(ui, vfs, lockname, timeout, warntimeout, *args, **kwargs):
105 106 """return an acquired lock or raise an a LockHeld exception
106 107
107 108 This function is responsible to issue warnings and or debug messages about
108 109 the held lock while trying to acquires it."""
109 110
110 111 def printwarning(printer, locker):
111 112 """issue the usual "waiting on lock" message through any channel"""
112 113 # show more details for new-style locks
113 114 if ':' in locker:
114 115 host, pid = locker.split(":", 1)
115 116 msg = (_("waiting for lock on %s held by process %r on host %r\n")
116 117 % (pycompat.bytestr(l.desc), pycompat.bytestr(pid),
117 118 pycompat.bytestr(host)))
118 119 else:
119 120 msg = (_("waiting for lock on %s held by %r\n")
120 121 % (l.desc, pycompat.bytestr(locker)))
121 122 printer(msg)
122 123
123 124 l = lock(vfs, lockname, 0, *args, dolock=False, **kwargs)
124 125
125 126 debugidx = 0 if (warntimeout and timeout) else -1
126 127 warningidx = 0
127 128 if not timeout:
128 129 warningidx = -1
129 130 elif warntimeout:
130 131 warningidx = warntimeout
131 132
132 133 delay = 0
133 134 while True:
134 135 try:
135 136 l._trylock()
136 137 break
137 138 except error.LockHeld as inst:
138 139 if delay == debugidx:
139 140 printwarning(ui.debug, inst.locker)
140 141 if delay == warningidx:
141 142 printwarning(ui.warn, inst.locker)
142 143 if timeout <= delay:
143 144 raise error.LockHeld(errno.ETIMEDOUT, inst.filename,
144 145 l.desc, inst.locker)
145 146 time.sleep(1)
146 147 delay += 1
147 148
148 149 l.delay = delay
149 150 if l.delay:
150 151 if 0 <= warningidx <= l.delay:
151 152 ui.warn(_("got lock after %d seconds\n") % l.delay)
152 153 else:
153 154 ui.debug("got lock after %d seconds\n" % l.delay)
154 155 if l.acquirefn:
155 156 l.acquirefn()
156 157 return l
157 158
158 159 class lock(object):
159 160 '''An advisory lock held by one process to control access to a set
160 161 of files. Non-cooperating processes or incorrectly written scripts
161 162 can ignore Mercurial's locking scheme and stomp all over the
162 163 repository, so don't do that.
163 164
164 165 Typically used via localrepository.lock() to lock the repository
165 166 store (.hg/store/) or localrepository.wlock() to lock everything
166 167 else under .hg/.'''
167 168
168 169 # lock is symlink on platforms that support it, file on others.
169 170
170 171 # symlink is used because create of directory entry and contents
171 172 # are atomic even over nfs.
172 173
173 174 # old-style lock: symlink to pid
174 175 # new-style lock: symlink to hostname:pid
175 176
176 177 _host = None
177 178
178 179 def __init__(self, vfs, fname, timeout=-1, releasefn=None, acquirefn=None,
179 180 desc=None, inheritchecker=None, parentlock=None,
180 dolock=True):
181 signalsafe=True, dolock=True):
181 182 self.vfs = vfs
182 183 self.f = fname
183 184 self.held = 0
184 185 self.timeout = timeout
185 186 self.releasefn = releasefn
186 187 self.acquirefn = acquirefn
187 188 self.desc = desc
188 189 self._inheritchecker = inheritchecker
189 190 self.parentlock = parentlock
190 191 self._parentheld = False
191 192 self._inherited = False
193 if signalsafe:
194 self._maybedelayedinterrupt = _delayedinterrupt
195 else:
196 self._maybedelayedinterrupt = util.nullcontextmanager
192 197 self.postrelease = []
193 198 self.pid = self._getpid()
194 199 if dolock:
195 200 self.delay = self.lock()
196 201 if self.acquirefn:
197 202 self.acquirefn()
198 203
199 204 def __enter__(self):
200 205 return self
201 206
202 207 def __exit__(self, exc_type, exc_value, exc_tb):
203 208 self.release()
204 209
205 210 def __del__(self):
206 211 if self.held:
207 212 warnings.warn("use lock.release instead of del lock",
208 213 category=DeprecationWarning,
209 214 stacklevel=2)
210 215
211 216 # ensure the lock will be removed
212 217 # even if recursive locking did occur
213 218 self.held = 1
214 219
215 220 self.release()
216 221
217 222 def _getpid(self):
218 223 # wrapper around procutil.getpid() to make testing easier
219 224 return procutil.getpid()
220 225
221 226 def lock(self):
222 227 timeout = self.timeout
223 228 while True:
224 229 try:
225 230 self._trylock()
226 231 return self.timeout - timeout
227 232 except error.LockHeld as inst:
228 233 if timeout != 0:
229 234 time.sleep(1)
230 235 if timeout > 0:
231 236 timeout -= 1
232 237 continue
233 238 raise error.LockHeld(errno.ETIMEDOUT, inst.filename, self.desc,
234 239 inst.locker)
235 240
236 241 def _trylock(self):
237 242 if self.held:
238 243 self.held += 1
239 244 return
240 245 if lock._host is None:
241 246 lock._host = _getlockprefix()
242 247 lockname = '%s:%d' % (lock._host, self.pid)
243 248 retry = 5
244 249 while not self.held and retry:
245 250 retry -= 1
246 251 try:
247 with _delayedinterrupt():
252 with self._maybedelayedinterrupt():
248 253 self.vfs.makelock(lockname, self.f)
249 254 self.held = 1
250 255 except (OSError, IOError) as why:
251 256 if why.errno == errno.EEXIST:
252 257 locker = self._readlock()
253 258 if locker is None:
254 259 continue
255 260
256 261 # special case where a parent process holds the lock -- this
257 262 # is different from the pid being different because we do
258 263 # want the unlock and postrelease functions to be called,
259 264 # but the lockfile to not be removed.
260 265 if locker == self.parentlock:
261 266 self._parentheld = True
262 267 self.held = 1
263 268 return
264 269 locker = self._testlock(locker)
265 270 if locker is not None:
266 271 raise error.LockHeld(errno.EAGAIN,
267 272 self.vfs.join(self.f), self.desc,
268 273 locker)
269 274 else:
270 275 raise error.LockUnavailable(why.errno, why.strerror,
271 276 why.filename, self.desc)
272 277
273 278 if not self.held:
274 279 # use empty locker to mean "busy for frequent lock/unlock
275 280 # by many processes"
276 281 raise error.LockHeld(errno.EAGAIN,
277 282 self.vfs.join(self.f), self.desc, "")
278 283
279 284 def _readlock(self):
280 285 """read lock and return its value
281 286
282 287 Returns None if no lock exists, pid for old-style locks, and host:pid
283 288 for new-style locks.
284 289 """
285 290 try:
286 291 return self.vfs.readlock(self.f)
287 292 except (OSError, IOError) as why:
288 293 if why.errno == errno.ENOENT:
289 294 return None
290 295 raise
291 296
292 297 def _testlock(self, locker):
293 298 if locker is None:
294 299 return None
295 300 try:
296 301 host, pid = locker.split(":", 1)
297 302 except ValueError:
298 303 return locker
299 304 if host != lock._host:
300 305 return locker
301 306 try:
302 307 pid = int(pid)
303 308 except ValueError:
304 309 return locker
305 310 if procutil.testpid(pid):
306 311 return locker
307 312 # if locker dead, break lock. must do this with another lock
308 313 # held, or can race and break valid lock.
309 314 try:
310 315 l = lock(self.vfs, self.f + '.break', timeout=0)
311 316 self.vfs.unlink(self.f)
312 317 l.release()
313 318 except error.LockError:
314 319 return locker
315 320
316 321 def testlock(self):
317 322 """return id of locker if lock is valid, else None.
318 323
319 324 If old-style lock, we cannot tell what machine locker is on.
320 325 with new-style lock, if locker is on this machine, we can
321 326 see if locker is alive. If locker is on this machine but
322 327 not alive, we can safely break lock.
323 328
324 329 The lock file is only deleted when None is returned.
325 330
326 331 """
327 332 locker = self._readlock()
328 333 return self._testlock(locker)
329 334
330 335 @contextlib.contextmanager
331 336 def inherit(self):
332 337 """context for the lock to be inherited by a Mercurial subprocess.
333 338
334 339 Yields a string that will be recognized by the lock in the subprocess.
335 340 Communicating this string to the subprocess needs to be done separately
336 341 -- typically by an environment variable.
337 342 """
338 343 if not self.held:
339 344 raise error.LockInheritanceContractViolation(
340 345 'inherit can only be called while lock is held')
341 346 if self._inherited:
342 347 raise error.LockInheritanceContractViolation(
343 348 'inherit cannot be called while lock is already inherited')
344 349 if self._inheritchecker is not None:
345 350 self._inheritchecker()
346 351 if self.releasefn:
347 352 self.releasefn()
348 353 if self._parentheld:
349 354 lockname = self.parentlock
350 355 else:
351 356 lockname = b'%s:%d' % (lock._host, self.pid)
352 357 self._inherited = True
353 358 try:
354 359 yield lockname
355 360 finally:
356 361 if self.acquirefn:
357 362 self.acquirefn()
358 363 self._inherited = False
359 364
360 365 def release(self):
361 366 """release the lock and execute callback function if any
362 367
363 368 If the lock has been acquired multiple times, the actual release is
364 369 delayed to the last release call."""
365 370 if self.held > 1:
366 371 self.held -= 1
367 372 elif self.held == 1:
368 373 self.held = 0
369 374 if self._getpid() != self.pid:
370 375 # we forked, and are not the parent
371 376 return
372 377 try:
373 378 if self.releasefn:
374 379 self.releasefn()
375 380 finally:
376 381 if not self._parentheld:
377 382 try:
378 383 self.vfs.unlink(self.f)
379 384 except OSError:
380 385 pass
381 386 # The postrelease functions typically assume the lock is not held
382 387 # at all.
383 388 if not self._parentheld:
384 389 for callback in self.postrelease:
385 390 callback()
386 391 # Prevent double usage and help clear cycles.
387 392 self.postrelease = None
388 393
389 394 def release(*locks):
390 395 for lock in locks:
391 396 if lock is not None:
392 397 lock.release()
General Comments 0
You need to be logged in to leave comments. Login now