##// END OF EJS Templates
stabletailgraph: implement stable-tail sort...
pacien -
r51288:f0d2b18f default
parent child Browse files
Show More
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
@@ -0,0 +1,110 b''
1 # stabletailsort.py - stable ordering of revisions
2 #
3 # Copyright 2021-2023 Pacien TRAN-GIRARD <pacien.trangirard@pacien.net>
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 """
9 Stable-tail sort computation.
10
11 The "stable-tail sort", or STS, is a reverse topological ordering of the
12 ancestors of a node, which tends to share large suffixes with the stable-tail
13 sort of ancestors and other nodes, giving it its name.
14
15 Its properties should make it suitable for making chunks of ancestors with high
16 reuse and incrementality for example.
17
18 This module and implementation are experimental. Most functions are not yet
19 optimised to operate on large production graphs.
20 """
21
22 import itertools
23 from ..node import nullrev
24 from .. import ancestor
25
26
27 def _sorted_parents(cl, p1, p2):
28 """
29 Chooses and returns the pair (px, pt) from (p1, p2).
30
31 Where
32 "px" denotes the parent starting the "exclusive" part, and
33 "pt" denotes the parent starting the "Tail" part.
34
35 "px" is chosen as the parent with the lowest rank with the goal of
36 minimising the size of the exclusive part and maximise the size of the
37 tail part, hopefully reducing the overall complexity of the stable sort.
38
39 In case of equal ranks, the stable node ID is used as a tie-breaker.
40 """
41 r1, r2 = cl.fast_rank(p1), cl.fast_rank(p2)
42 if r1 < r2:
43 return (p1, p2)
44 elif r1 > r2:
45 return (p2, p1)
46 elif cl.node(p1) < cl.node(p2):
47 return (p1, p2)
48 else:
49 return (p2, p1)
50
51
52 def _nonoedipal_parent_revs(cl, rev):
53 """
54 Returns the non-œdipal parent pair of the given revision.
55
56 An œdipal merge is a merge with parents p1, p2 with either
57 p1 in ancestors(p2) or p2 in ancestors(p1).
58 In the first case, p1 is the œdipal parent.
59 In the second case, p2 is the œdipal parent.
60
61 Œdipal edges start empty exclusive parts. They do not bring new ancestors.
62 As such, they can be skipped when computing any topological sort or any
63 iteration over the ancestors of a node.
64
65 The œdipal edges are eliminated here using the rank information.
66 """
67 p1, p2 = cl.parentrevs(rev)
68 if p1 == nullrev or cl.fast_rank(p2) == cl.fast_rank(rev) - 1:
69 return p2, nullrev
70 elif p2 == nullrev or cl.fast_rank(p1) == cl.fast_rank(rev) - 1:
71 return p1, nullrev
72 else:
73 return p1, p2
74
75
76 def _stable_tail_sort(cl, head_rev):
77 """
78 Naive topological iterator of the ancestors given by the stable-tail sort.
79
80 The stable-tail sort of a node "h" is defined as the sequence:
81 sts(h) := [h] + excl(h) + sts(pt(h))
82 where excl(h) := u for u in sts(px(h)) if u not in ancestors(pt(h))
83
84 This implementation uses a call-stack whose size is
85 O(number of open merges).
86
87 As such, this implementation exists mainly as a defining reference.
88 """
89 cursor_rev = head_rev
90 while cursor_rev != nullrev:
91 yield cursor_rev
92
93 p1, p2 = _nonoedipal_parent_revs(cl, cursor_rev)
94 if p1 == nullrev:
95 cursor_rev = p2
96 elif p2 == nullrev:
97 cursor_rev = p1
98 else:
99 px, pt = _sorted_parents(cl, p1, p2)
100
101 tail_ancestors = ancestor.lazyancestors(
102 cl.parentrevs, (pt,), inclusive=True
103 )
104 exclusive_ancestors = (
105 a for a in _stable_tail_sort(cl, px) if a not in tail_ancestors
106 )
107
108 excl_part_size = cl.fast_rank(cursor_rev) - cl.fast_rank(pt) - 1
109 yield from itertools.islice(exclusive_ancestors, excl_part_size)
110 cursor_rev = pt
This diff has been collapsed as it changes many lines, (710 lines changed) Show them Hide them
@@ -0,0 +1,710 b''
1 ====================================
2 Test for the stabletailgraph package
3 ====================================
4
5 This test file contains a bunch of small test graphs with some minimal yet
6 non-trivial structure, on which the various stable-tail graph and stable-tail
7 sort functions are tested.
8
9 Each case consists of the creation of the interesting graph structure, followed
10 by a check, for each noteworthy node, of:
11 - the stable-tail sort output.
12
13 In the ASCII art of the diagrams, the side of the exclusive part which is
14 followed in priority is denoted with "<" or ">" if it is on the left or right
15 respectively.
16
17 The intermediary linear parts in the example graph are there to force the
18 exclusive part choice (made on a min rank condition).
19
20
21 Setup
22 =====
23
24 Enable the rank computation to test sorting based on the rank.
25
26 $ cat << EOF >> $HGRCPATH
27 > [format]
28 > exp-use-changelog-v2=enable-unstable-format-and-corrupt-my-data
29 >
30 > [alias]
31 > test-sts = debug::stable-tail-sort -T '{tags},'
32 > test-log = log --graph -T '{tags} rank={_fast_rank}'
33 > EOF
34
35
36 Example 1: single merge node
37 ============================
38
39 A base case with one branchpoint "b" and one merge node "e".
40
41 The exclusive part, starting with the lowest-ranking parent "c" of "e",
42 appears first in stable-tail sort of "e" and "f".
43
44 # f
45 # |
46 # e
47 # |
48 # --<--
49 # | |
50 # c d
51 # | |
52 # --+-- <- at this point, the sort of "e" is done consuming its
53 # | exclusive part [c] and jumps back to its other parent "d"
54 # b
55 # |
56 # a
57
58 $ hg init example-1
59 $ cd example-1
60 $ hg debugbuilddag '.:a*a:b*b:c<b+2:d*c/d:e*e:f.'
61 $ hg test-log
62 o tip rank=8
63 |
64 o f rank=7
65 |
66 o e rank=6
67 |\
68 | o d rank=4
69 | |
70 | o rank=3
71 | |
72 o | c rank=3
73 |/
74 o b rank=2
75 |
76 o a rank=1
77
78
79 Check the sort of the base linear case.
80
81 $ hg test-sts c
82 c,b,a, (no-eol)
83
84 Check the stable-tail sort of "e": "c" should come before "d".
85
86 $ hg test-sts e
87 e,c,d,*,b,a, (no-eol) (glob)
88
89 Check that the linear descendant of the merge inherits its sort properly.
90
91 $ hg test-sts f
92 f,e,c,d,*,b,a, (no-eol) (glob)
93
94 $ cd ..
95
96
97 Example 2: nested exclusive parts, without specific leap
98 ========================================================
99
100 "g" is a merge node whose exclusive part contains a merge node "e".
101 We check that the stable-tail sort recurses properly by delegating.
102
103 Notice that parts of the sort of "e" is an infix of the sort of "g".
104 This is an expected property of the sort.
105
106 # g
107 # |
108 # ---<---
109 # | |
110 # e | <- while processing the sort in the exclusive part of "g"
111 # | | we recursively process the exclusive part of "e"
112 # --<-- f
113 # | | |
114 # c d |
115 # | | |
116 # --+-- |
117 # | |
118 # b |
119 # | |
120 # ---+--- <- done with excl(g), jump to "f"
121 # |
122 # a
123
124 $ hg init example-2
125 $ cd example-2
126 $ hg debugbuilddag '.:a*a:b*b:c<b+2:d*c/d:e<a+6:f*e/f:g.'
127 $ hg test-log
128 o tip rank=14
129 |
130 o g rank=13
131 |\
132 | o f rank=7
133 | |
134 | o rank=6
135 | |
136 | o rank=5
137 | |
138 | o rank=4
139 | |
140 | o rank=3
141 | |
142 | o rank=2
143 | |
144 o | e rank=6
145 |\ \
146 | o | d rank=4
147 | | |
148 | o | rank=3
149 | | |
150 o | | c rank=3
151 |/ /
152 o / b rank=2
153 |/
154 o a rank=1
155
156 Display the sort of "e" for reference
157
158 $ hg test-sts e
159 e,c,d,*,b,a, (no-eol) (glob)
160
161 Check the correctness of the sort of "g",
162 and that a part of the sort of "e" appears as an infix.
163
164 $ hg test-sts g
165 g,e,c,d,*,b,f,*,a, (no-eol) (glob)
166
167 $ cd ..
168
169
170 Example 3: shadowing of a final leap
171 ====================================
172
173 We have a merge "f" whose exclusive part contains a merge "d".
174
175 The inherited parent of "d" is not in the exclusive part of "f".
176 At the end of the exclusive part of "d",
177 the leap to "c" is shadowed by the leap to "e", i.e. the inherited part to "f".
178
179 Notice that emitting "c" before "e" would break the reverse topological
180 ordering.
181
182 # f
183 # |
184 # ---<---
185 # | |
186 # d |
187 # | e
188 # --<-- |
189 # | | |
190 # | +----
191 # b |
192 # | c
193 # | |
194 # --+-- <- at this point, jumping to "e", not the shadowed "c"
195 # |
196 # a
197
198 $ hg init example-3
199 $ cd example-3
200 $ hg debugbuilddag '.:a*a:b<a+2:c*b/c:d<c+3:e*d/e:f.'
201 $ hg test-log
202 o tip rank=10
203 |
204 o f rank=9
205 |\
206 | o e rank=6
207 | |
208 | o rank=5
209 | |
210 | o rank=4
211 | |
212 o | d rank=5
213 |\|
214 | o c rank=3
215 | |
216 | o rank=2
217 | |
218 o | b rank=2
219 |/
220 o a rank=1
221
222
223 Display the sort of "d" for reference:
224
225 $ hg test-sts d
226 d,b,c,*,a, (no-eol) (glob)
227
228 Check that we leap from "b" directly to "e" (shadowing the leap to "c"),
229 and that "c" is then emitted after "e" (its descendant).
230
231 $ hg test-sts f
232 f,d,b,e,*,c,*,a, (no-eol) (glob)
233
234 $ cd ..
235
236
237 Example 4: skipping over nested exclusive part (entirely)
238 =========================================================
239
240 We have a merge "f" whose exclusive part contains a merge "d".
241
242 The exclusive part of "d" is not in the exclusive part of "f".
243 However, some of the inherited part of "d" is part of the exclusive part of "f"
244 and needs to be iterated over before leaping to the inherited part of "f".
245
246 The sort of "d" is partially reused for the ordering of the exclusive part of
247 "f". However the reused part is not contiguous in the sort of "d".
248
249 # f
250 # |
251 # ---<---
252 # | |
253 # d |
254 # | e
255 # -->-- | <- in the sort of "f", we need to skip "c" and leap to the
256 # | | | inherited part of "d"
257 # | +----
258 # b |
259 # | c
260 # | |
261 # --+--
262 # |
263 # a
264
265 $ hg init example-4
266 $ cd example-4
267 $ hg debugbuilddag '.:a*a+1:b<a+1:c*b/c:d<c+4:e*d/e:f.'
268 $ hg test-log
269 o tip rank=11
270 |
271 o f rank=10
272 |\
273 | o e rank=6
274 | |
275 | o rank=5
276 | |
277 | o rank=4
278 | |
279 | o rank=3
280 | |
281 o | d rank=5
282 |\|
283 | o c rank=2
284 | |
285 o | b rank=3
286 | |
287 o | rank=2
288 |/
289 o a rank=1
290
291
292 Display the sort of "d" for reference:
293
294 $ hg test-sts d
295 d,c,b,*,a, (no-eol) (glob)
296
297 Chack that sort "f" leaps from "d" to "b":
298
299 $ hg test-sts f
300 f,d,b,*,e,*,c,a, (no-eol) (glob)
301
302 $ cd ..
303
304
305 Example 5: skipping over nested exclusive part (partially)
306 ==========================================================
307
308 We have a merge "f" whose exclusive part contains a merge "d".
309
310 Similar to example 4, but the exclusive part of "d" is only partially
311 contained in the inherited part of "f".
312 So, we need to leap in the middle of the exclusive part of "d".
313
314 # f
315 # |
316 # ---<---
317 # | |
318 # d |
319 # | e
320 # -->-- |
321 # | | |
322 # | g |
323 # | | |
324 # | +---- <- in the sort of "f", leaping from "g" to "b"
325 # b |
326 # | c
327 # | |
328 # --+--
329 # |
330 # a
331
332 $ hg init example-5
333 $ cd example-5
334 $ hg debugbuilddag '.:a*a+2:b<a+1:c+1:g*b/g:d<c+6:e*d/e:f.'
335 $ hg test-log
336 o tip rank=15
337 |
338 o f rank=14
339 |\
340 | o e rank=8
341 | |
342 | o rank=7
343 | |
344 | o rank=6
345 | |
346 | o rank=5
347 | |
348 | o rank=4
349 | |
350 | o rank=3
351 | |
352 o | d rank=7
353 |\ \
354 | o | g rank=3
355 | |/
356 | o c rank=2
357 | |
358 o | b rank=4
359 | |
360 o | rank=3
361 | |
362 o | rank=2
363 |/
364 o a rank=1
365
366
367 Display the sort of "d" for reference:
368
369 $ hg test-sts d
370 d,g,c,b,*,a, (no-eol) (glob)
371
372 Check that sort "f" leaps from "g" to "b":
373
374 $ hg test-sts f
375 f,d,g,b,*,e,*,c,a, (no-eol) (glob)
376
377 $ cd ..
378
379
380 Example 6: merge in the inherited part
381 ======================================
382
383 Variant of example 2, but with a merge ("f") in the inherited part of "g".
384
385 "g" is a merge node whose inherited part contains a merge node "f".
386 We check that the stable-tail sort delegates properly after the exclusive part.
387
388 # g
389 # |
390 # ---<---
391 # | |
392 # d f
393 # | |
394 # | ---<---
395 # | | |
396 # | e c
397 # | | |
398 # ---+ | <- at this point, we're done (for good) with the exclusive
399 # | | part of "g"
400 # b |
401 # | |
402 # ---+---
403 # |
404 # a
405
406 $ hg init example-6
407 $ cd example-6
408 $ hg debugbuilddag '.:a*a:b<a+3:c*b:d*b:e*e/c:f*d/f:g.'
409 $ hg test-log
410 o tip rank=10
411 |
412 o g rank=9
413 |\
414 | o f rank=7
415 | |\
416 | | o e rank=3
417 | | |
418 o---+ d rank=3
419 / /
420 o | c rank=4
421 | |
422 o | rank=3
423 | |
424 o | rank=2
425 | |
426 | o b rank=2
427 |/
428 o a rank=1
429
430
431 Display the sort of "f" for reference:
432
433 $ hg test-sts f
434 f,e,b,c,*,a, (no-eol) (glob)
435
436 Check that the sort of "g" delegates to the sort of "f" after processing its
437 exclusive part of "g":
438
439 $ hg test-sts g
440 g,d,f,e,b,c,*,a, (no-eol) (glob)
441
442 $ cd ..
443
444
445 Example 7: postponed iteration of common exclusive ancestors
446 ============================================================
447
448 Sibling merges "j" and "k", with partially shared exclusive parts.
449
450 When considering the sort of "l", the iteration over this shared part cannot
451 happen when iterating over excl(j) and has to be postponed to excl(k).
452
453 # l
454 # |
455 # ----<----
456 # | |
457 # j k
458 # | |
459 # -->-- --<--
460 # | | | |
461 # g e h i
462 # | | | |
463 # | --+-- | <- at this point, for the sort of "l", the iteration on
464 # f | | the end of excl(j) is postponed to the iteration of
465 # | d | excl(k)
466 # | | |
467 # | c |
468 # | | |
469 # ---+--- |
470 # | |
471 # b |
472 # | |
473 # ----+-----
474 # |
475 # a
476
477 $ hg init example-7
478 $ cd example-7
479 $ hg debugbuilddag \
480 > '.:a*a:b*b:c*c:d*d:e*b:f<f+3:g<d+2:h<a+6:i*e/g:j*h/i:k*j/k:l.'
481 $ hg test-log
482 o tip rank=21
483 |
484 o l rank=20
485 |\
486 | o k rank=13
487 | |\
488 o \ \ j rank=10
489 |\ \ \
490 | | | o i rank=7
491 | | | |
492 | | | o rank=6
493 | | | |
494 | | | o rank=5
495 | | | |
496 | | | o rank=4
497 | | | |
498 | | | o rank=3
499 | | | |
500 | | | o rank=2
501 | | | |
502 | | o | h rank=6
503 | | | |
504 | | o | rank=5
505 | | | |
506 | o | | g rank=6
507 | | | |
508 | o | | rank=5
509 | | | |
510 | o | | rank=4
511 | | | |
512 | o | | f rank=3
513 | | | |
514 o---+ | e rank=5
515 / / /
516 | o | d rank=4
517 | | |
518 | o | c rank=3
519 |/ /
520 o / b rank=2
521 |/
522 o a rank=1
523
524
525 Display the sort of "j" for reference:
526
527 $ hg test-sts j
528 j,e,d,c,g,*,f,b,a, (no-eol) (glob)
529
530 Display the sort of "k" for reference:
531
532 $ hg test-sts k
533 k,h,*,d,c,b,i,*,a, (no-eol) (glob)
534
535 Check that the common part of excl(j) and excl(k) is iterated over after "k":
536
537 $ hg test-sts l
538 l,j,e,g,*,f,k,h,*,d,c,b,i,*,a, (no-eol) (glob)
539
540 $ cd ..
541
542
543 Example 8: postponed iteration of common ancestors between parts
544 ================================================================
545
546 Sibling merges "g" and "i", with some part shared between the inherited part
547 of "g" and the exclusive part of "i".
548
549 When considering the sort of "j", the iteration over this shared part cannot
550 happen when iterating over inherited(g) and has to be postponed to excl(i).
551
552 # j
553 # |
554 # ----<----
555 # | |
556 # g i
557 # | |
558 # --<-- --<--
559 # | | | |
560 # c f | h
561 # | | | |
562 # | --+-- | <- at this point, for the sort of "j", the iteration
563 # | | | on the end of inherited(g) is postponed to the
564 # | e | iteration of excl(k)
565 # | | |
566 # ---+--- |
567 # b |
568 # | |
569 # ----+-----
570 # |
571 # a
572
573 $ hg init example-8
574 $ cd example-8
575 $ hg debugbuilddag '.:a*a:b*b:c*b:d*d:e*e:f*c/f:g<a+5:h*e/h:i*g/i:j.'
576 $ hg test-log
577 o tip rank=15
578 |
579 o j rank=14
580 |\
581 | o i rank=10
582 | |\
583 | | o h rank=6
584 | | |
585 | | o rank=5
586 | | |
587 | | o rank=4
588 | | |
589 | | o rank=3
590 | | |
591 | | o rank=2
592 | | |
593 o | | g rank=7
594 |\ \ \
595 | o | | f rank=5
596 | |/ /
597 | o | e rank=4
598 | | |
599 | o | d rank=3
600 | | |
601 o | | c rank=3
602 |/ /
603 o / b rank=2
604 |/
605 o a rank=1
606
607
608 Display the sort of "g" for reference:
609
610 $ hg test-sts g
611 g,c,f,e,d,b,a, (no-eol)
612
613 Display the sort of "i" for reference:
614
615 $ hg test-sts i
616 i,e,d,b,h,*,a, (no-eol) (glob)
617
618 Check that the common part of inherited(g) and excl(k) is iterated over after
619 "i":
620
621 $ hg test-sts j
622 j,g,c,f,i,e,d,b,h,*,a, (no-eol) (glob)
623
624 $ cd ..
625
626
627 Example 9: postponed iteration of common ancestors between both parts
628 =====================================================================
629
630 This is a combination of example 7 and 8 at the same time.
631 Both excl(i) and excl(j) share a common part.
632 Same with inherited(i) and inherited(j).
633
634 We test that the walk on the common ancestors in both cases is properly
635 postponed when considering sort(k).
636
637 # k
638 # |
639 # ----<----
640 # | |
641 # i j
642 # | |
643 # --<-- --<--
644 # | | | |
645 # c f g h
646 # | | | |
647 # | e | |
648 # | | | |
649 # +--]|[--- | <- rest of excl(i) postponed to excl(j)
650 # | | |
651 # b ----+---- <- rest of inherited(i) postponed to inherited(j)
652 # | |
653 # | d
654 # | |
655 # ----+----
656 # |
657 # a
658
659 $ hg init example-9
660 $ cd example-9
661 $ hg debugbuilddag '.:a*a:b*b:c*a:d*d:e*e:f<b+2:g<d+3:h*c/f:i*g/h:j*i/j:k.'
662 $ hg test-log
663 o tip rank=15
664 |
665 o k rank=14
666 |\
667 | o j rank=9
668 | |\
669 o \ \ i rank=7
670 |\ \ \
671 | | | o h rank=5
672 | | | |
673 | | | o rank=4
674 | | | |
675 | | | o rank=3
676 | | | |
677 | | o | g rank=4
678 | | | |
679 | | o | rank=3
680 | | | |
681 | o | | f rank=4
682 | | | |
683 | o---+ e rank=3
684 | / /
685 | | o d rank=2
686 | | |
687 o | | c rank=3
688 |/ /
689 o / b rank=2
690 |/
691 o a rank=1
692
693
694 Display sort(i) for reference:
695
696 $ hg test-sts i
697 i,c,b,f,e,d,a, (no-eol)
698
699 Display sort(j) for reference:
700
701 $ hg test-sts j
702 j,g,*,b,h,*,d,a, (no-eol) (glob)
703
704 Check that the end of excl(i) is postponed to excl(j), the end of inherited(i)
705 is postponed to inherited(j) in sort(k):
706
707 $ hg test-sts k
708 k,i,c,f,e,j,g,*,b,h,*,d,a, (no-eol) (glob)
709
710 $ cd ..
@@ -1,4783 +1,4808 b''
1 # debugcommands.py - command processing for debug* commands
1 # debugcommands.py - command processing for debug* commands
2 #
2 #
3 # Copyright 2005-2016 Olivia Mackall <olivia@selenic.com>
3 # Copyright 2005-2016 Olivia Mackall <olivia@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8
8
9 import binascii
9 import binascii
10 import codecs
10 import codecs
11 import collections
11 import collections
12 import contextlib
12 import contextlib
13 import difflib
13 import difflib
14 import errno
14 import errno
15 import glob
15 import glob
16 import operator
16 import operator
17 import os
17 import os
18 import platform
18 import platform
19 import random
19 import random
20 import re
20 import re
21 import socket
21 import socket
22 import ssl
22 import ssl
23 import stat
23 import stat
24 import subprocess
24 import subprocess
25 import sys
25 import sys
26 import time
26 import time
27
27
28 from .i18n import _
28 from .i18n import _
29 from .node import (
29 from .node import (
30 bin,
30 bin,
31 hex,
31 hex,
32 nullrev,
32 nullrev,
33 short,
33 short,
34 )
34 )
35 from .pycompat import (
35 from .pycompat import (
36 getattr,
36 getattr,
37 open,
37 open,
38 )
38 )
39 from . import (
39 from . import (
40 bundle2,
40 bundle2,
41 bundlerepo,
41 bundlerepo,
42 changegroup,
42 changegroup,
43 cmdutil,
43 cmdutil,
44 color,
44 color,
45 context,
45 context,
46 copies,
46 copies,
47 dagparser,
47 dagparser,
48 dirstateutils,
48 dirstateutils,
49 encoding,
49 encoding,
50 error,
50 error,
51 exchange,
51 exchange,
52 extensions,
52 extensions,
53 filemerge,
53 filemerge,
54 filesetlang,
54 filesetlang,
55 formatter,
55 formatter,
56 hg,
56 hg,
57 httppeer,
57 httppeer,
58 localrepo,
58 localrepo,
59 lock as lockmod,
59 lock as lockmod,
60 logcmdutil,
60 logcmdutil,
61 mergestate as mergestatemod,
61 mergestate as mergestatemod,
62 metadata,
62 metadata,
63 obsolete,
63 obsolete,
64 obsutil,
64 obsutil,
65 pathutil,
65 pathutil,
66 phases,
66 phases,
67 policy,
67 policy,
68 pvec,
68 pvec,
69 pycompat,
69 pycompat,
70 registrar,
70 registrar,
71 repair,
71 repair,
72 repoview,
72 repoview,
73 requirements,
73 requirements,
74 revlog,
74 revlog,
75 revset,
75 revset,
76 revsetlang,
76 revsetlang,
77 scmutil,
77 scmutil,
78 setdiscovery,
78 setdiscovery,
79 simplemerge,
79 simplemerge,
80 sshpeer,
80 sshpeer,
81 sslutil,
81 sslutil,
82 streamclone,
82 streamclone,
83 strip,
83 strip,
84 tags as tagsmod,
84 tags as tagsmod,
85 templater,
85 templater,
86 treediscovery,
86 treediscovery,
87 upgrade,
87 upgrade,
88 url as urlmod,
88 url as urlmod,
89 util,
89 util,
90 verify,
90 verify,
91 vfs as vfsmod,
91 vfs as vfsmod,
92 wireprotoframing,
92 wireprotoframing,
93 wireprotoserver,
93 wireprotoserver,
94 )
94 )
95 from .interfaces import repository
95 from .interfaces import repository
96 from .stabletailgraph import stabletailsort
96 from .utils import (
97 from .utils import (
97 cborutil,
98 cborutil,
98 compression,
99 compression,
99 dateutil,
100 dateutil,
100 procutil,
101 procutil,
101 stringutil,
102 stringutil,
102 urlutil,
103 urlutil,
103 )
104 )
104
105
105 from .revlogutils import (
106 from .revlogutils import (
106 constants as revlog_constants,
107 constants as revlog_constants,
107 debug as revlog_debug,
108 debug as revlog_debug,
108 deltas as deltautil,
109 deltas as deltautil,
109 nodemap,
110 nodemap,
110 rewrite,
111 rewrite,
111 sidedata,
112 sidedata,
112 )
113 )
113
114
114 release = lockmod.release
115 release = lockmod.release
115
116
116 table = {}
117 table = {}
117 table.update(strip.command._table)
118 table.update(strip.command._table)
118 command = registrar.command(table)
119 command = registrar.command(table)
119
120
120
121
121 @command(b'debugancestor', [], _(b'[INDEX] REV1 REV2'), optionalrepo=True)
122 @command(b'debugancestor', [], _(b'[INDEX] REV1 REV2'), optionalrepo=True)
122 def debugancestor(ui, repo, *args):
123 def debugancestor(ui, repo, *args):
123 """find the ancestor revision of two revisions in a given index"""
124 """find the ancestor revision of two revisions in a given index"""
124 if len(args) == 3:
125 if len(args) == 3:
125 index, rev1, rev2 = args
126 index, rev1, rev2 = args
126 r = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), index)
127 r = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), index)
127 lookup = r.lookup
128 lookup = r.lookup
128 elif len(args) == 2:
129 elif len(args) == 2:
129 if not repo:
130 if not repo:
130 raise error.Abort(
131 raise error.Abort(
131 _(b'there is no Mercurial repository here (.hg not found)')
132 _(b'there is no Mercurial repository here (.hg not found)')
132 )
133 )
133 rev1, rev2 = args
134 rev1, rev2 = args
134 r = repo.changelog
135 r = repo.changelog
135 lookup = repo.lookup
136 lookup = repo.lookup
136 else:
137 else:
137 raise error.Abort(_(b'either two or three arguments required'))
138 raise error.Abort(_(b'either two or three arguments required'))
138 a = r.ancestor(lookup(rev1), lookup(rev2))
139 a = r.ancestor(lookup(rev1), lookup(rev2))
139 ui.write(b'%d:%s\n' % (r.rev(a), hex(a)))
140 ui.write(b'%d:%s\n' % (r.rev(a), hex(a)))
140
141
141
142
142 @command(b'debugantivirusrunning', [])
143 @command(b'debugantivirusrunning', [])
143 def debugantivirusrunning(ui, repo):
144 def debugantivirusrunning(ui, repo):
144 """attempt to trigger an antivirus scanner to see if one is active"""
145 """attempt to trigger an antivirus scanner to see if one is active"""
145 with repo.cachevfs.open('eicar-test-file.com', b'wb') as f:
146 with repo.cachevfs.open('eicar-test-file.com', b'wb') as f:
146 f.write(
147 f.write(
147 util.b85decode(
148 util.b85decode(
148 # This is a base85-armored version of the EICAR test file. See
149 # This is a base85-armored version of the EICAR test file. See
149 # https://en.wikipedia.org/wiki/EICAR_test_file for details.
150 # https://en.wikipedia.org/wiki/EICAR_test_file for details.
150 b'ST#=}P$fV?P+K%yP+C|uG$>GBDK|qyDK~v2MM*<JQY}+dK~6+LQba95P'
151 b'ST#=}P$fV?P+K%yP+C|uG$>GBDK|qyDK~v2MM*<JQY}+dK~6+LQba95P'
151 b'E<)&Nm5l)EmTEQR4qnHOhq9iNGnJx'
152 b'E<)&Nm5l)EmTEQR4qnHOhq9iNGnJx'
152 )
153 )
153 )
154 )
154 # Give an AV engine time to scan the file.
155 # Give an AV engine time to scan the file.
155 time.sleep(2)
156 time.sleep(2)
156 util.unlink(repo.cachevfs.join('eicar-test-file.com'))
157 util.unlink(repo.cachevfs.join('eicar-test-file.com'))
157
158
158
159
159 @command(b'debugapplystreamclonebundle', [], b'FILE')
160 @command(b'debugapplystreamclonebundle', [], b'FILE')
160 def debugapplystreamclonebundle(ui, repo, fname):
161 def debugapplystreamclonebundle(ui, repo, fname):
161 """apply a stream clone bundle file"""
162 """apply a stream clone bundle file"""
162 f = hg.openpath(ui, fname)
163 f = hg.openpath(ui, fname)
163 gen = exchange.readbundle(ui, f, fname)
164 gen = exchange.readbundle(ui, f, fname)
164 gen.apply(repo)
165 gen.apply(repo)
165
166
166
167
167 @command(
168 @command(
168 b'debugbuilddag',
169 b'debugbuilddag',
169 [
170 [
170 (
171 (
171 b'm',
172 b'm',
172 b'mergeable-file',
173 b'mergeable-file',
173 None,
174 None,
174 _(b'add single file mergeable changes'),
175 _(b'add single file mergeable changes'),
175 ),
176 ),
176 (
177 (
177 b'o',
178 b'o',
178 b'overwritten-file',
179 b'overwritten-file',
179 None,
180 None,
180 _(b'add single file all revs overwrite'),
181 _(b'add single file all revs overwrite'),
181 ),
182 ),
182 (b'n', b'new-file', None, _(b'add new file at each rev')),
183 (b'n', b'new-file', None, _(b'add new file at each rev')),
183 (
184 (
184 b'',
185 b'',
185 b'from-existing',
186 b'from-existing',
186 None,
187 None,
187 _(b'continue from a non-empty repository'),
188 _(b'continue from a non-empty repository'),
188 ),
189 ),
189 ],
190 ],
190 _(b'[OPTION]... [TEXT]'),
191 _(b'[OPTION]... [TEXT]'),
191 )
192 )
192 def debugbuilddag(
193 def debugbuilddag(
193 ui,
194 ui,
194 repo,
195 repo,
195 text=None,
196 text=None,
196 mergeable_file=False,
197 mergeable_file=False,
197 overwritten_file=False,
198 overwritten_file=False,
198 new_file=False,
199 new_file=False,
199 from_existing=False,
200 from_existing=False,
200 ):
201 ):
201 """builds a repo with a given DAG from scratch in the current empty repo
202 """builds a repo with a given DAG from scratch in the current empty repo
202
203
203 The description of the DAG is read from stdin if not given on the
204 The description of the DAG is read from stdin if not given on the
204 command line.
205 command line.
205
206
206 Elements:
207 Elements:
207
208
208 - "+n" is a linear run of n nodes based on the current default parent
209 - "+n" is a linear run of n nodes based on the current default parent
209 - "." is a single node based on the current default parent
210 - "." is a single node based on the current default parent
210 - "$" resets the default parent to null (implied at the start);
211 - "$" resets the default parent to null (implied at the start);
211 otherwise the default parent is always the last node created
212 otherwise the default parent is always the last node created
212 - "<p" sets the default parent to the backref p
213 - "<p" sets the default parent to the backref p
213 - "*p" is a fork at parent p, which is a backref
214 - "*p" is a fork at parent p, which is a backref
214 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
215 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
215 - "/p2" is a merge of the preceding node and p2
216 - "/p2" is a merge of the preceding node and p2
216 - ":tag" defines a local tag for the preceding node
217 - ":tag" defines a local tag for the preceding node
217 - "@branch" sets the named branch for subsequent nodes
218 - "@branch" sets the named branch for subsequent nodes
218 - "#...\\n" is a comment up to the end of the line
219 - "#...\\n" is a comment up to the end of the line
219
220
220 Whitespace between the above elements is ignored.
221 Whitespace between the above elements is ignored.
221
222
222 A backref is either
223 A backref is either
223
224
224 - a number n, which references the node curr-n, where curr is the current
225 - a number n, which references the node curr-n, where curr is the current
225 node, or
226 node, or
226 - the name of a local tag you placed earlier using ":tag", or
227 - the name of a local tag you placed earlier using ":tag", or
227 - empty to denote the default parent.
228 - empty to denote the default parent.
228
229
229 All string valued-elements are either strictly alphanumeric, or must
230 All string valued-elements are either strictly alphanumeric, or must
230 be enclosed in double quotes ("..."), with "\\" as escape character.
231 be enclosed in double quotes ("..."), with "\\" as escape character.
231 """
232 """
232
233
233 if text is None:
234 if text is None:
234 ui.status(_(b"reading DAG from stdin\n"))
235 ui.status(_(b"reading DAG from stdin\n"))
235 text = ui.fin.read()
236 text = ui.fin.read()
236
237
237 cl = repo.changelog
238 cl = repo.changelog
238 if len(cl) > 0 and not from_existing:
239 if len(cl) > 0 and not from_existing:
239 raise error.Abort(_(b'repository is not empty'))
240 raise error.Abort(_(b'repository is not empty'))
240
241
241 # determine number of revs in DAG
242 # determine number of revs in DAG
242 total = 0
243 total = 0
243 for type, data in dagparser.parsedag(text):
244 for type, data in dagparser.parsedag(text):
244 if type == b'n':
245 if type == b'n':
245 total += 1
246 total += 1
246
247
247 if mergeable_file:
248 if mergeable_file:
248 linesperrev = 2
249 linesperrev = 2
249 # make a file with k lines per rev
250 # make a file with k lines per rev
250 initialmergedlines = [b'%d' % i for i in range(0, total * linesperrev)]
251 initialmergedlines = [b'%d' % i for i in range(0, total * linesperrev)]
251 initialmergedlines.append(b"")
252 initialmergedlines.append(b"")
252
253
253 tags = []
254 tags = []
254 progress = ui.makeprogress(
255 progress = ui.makeprogress(
255 _(b'building'), unit=_(b'revisions'), total=total
256 _(b'building'), unit=_(b'revisions'), total=total
256 )
257 )
257 with progress, repo.wlock(), repo.lock(), repo.transaction(b"builddag"):
258 with progress, repo.wlock(), repo.lock(), repo.transaction(b"builddag"):
258 at = -1
259 at = -1
259 atbranch = b'default'
260 atbranch = b'default'
260 nodeids = []
261 nodeids = []
261 id = 0
262 id = 0
262 progress.update(id)
263 progress.update(id)
263 for type, data in dagparser.parsedag(text):
264 for type, data in dagparser.parsedag(text):
264 if type == b'n':
265 if type == b'n':
265 ui.note((b'node %s\n' % pycompat.bytestr(data)))
266 ui.note((b'node %s\n' % pycompat.bytestr(data)))
266 id, ps = data
267 id, ps = data
267
268
268 files = []
269 files = []
269 filecontent = {}
270 filecontent = {}
270
271
271 p2 = None
272 p2 = None
272 if mergeable_file:
273 if mergeable_file:
273 fn = b"mf"
274 fn = b"mf"
274 p1 = repo[ps[0]]
275 p1 = repo[ps[0]]
275 if len(ps) > 1:
276 if len(ps) > 1:
276 p2 = repo[ps[1]]
277 p2 = repo[ps[1]]
277 pa = p1.ancestor(p2)
278 pa = p1.ancestor(p2)
278 base, local, other = [
279 base, local, other = [
279 x[fn].data() for x in (pa, p1, p2)
280 x[fn].data() for x in (pa, p1, p2)
280 ]
281 ]
281 m3 = simplemerge.Merge3Text(base, local, other)
282 m3 = simplemerge.Merge3Text(base, local, other)
282 ml = [
283 ml = [
283 l.strip()
284 l.strip()
284 for l in simplemerge.render_minimized(m3)[0]
285 for l in simplemerge.render_minimized(m3)[0]
285 ]
286 ]
286 ml.append(b"")
287 ml.append(b"")
287 elif at > 0:
288 elif at > 0:
288 ml = p1[fn].data().split(b"\n")
289 ml = p1[fn].data().split(b"\n")
289 else:
290 else:
290 ml = initialmergedlines
291 ml = initialmergedlines
291 ml[id * linesperrev] += b" r%i" % id
292 ml[id * linesperrev] += b" r%i" % id
292 mergedtext = b"\n".join(ml)
293 mergedtext = b"\n".join(ml)
293 files.append(fn)
294 files.append(fn)
294 filecontent[fn] = mergedtext
295 filecontent[fn] = mergedtext
295
296
296 if overwritten_file:
297 if overwritten_file:
297 fn = b"of"
298 fn = b"of"
298 files.append(fn)
299 files.append(fn)
299 filecontent[fn] = b"r%i\n" % id
300 filecontent[fn] = b"r%i\n" % id
300
301
301 if new_file:
302 if new_file:
302 fn = b"nf%i" % id
303 fn = b"nf%i" % id
303 files.append(fn)
304 files.append(fn)
304 filecontent[fn] = b"r%i\n" % id
305 filecontent[fn] = b"r%i\n" % id
305 if len(ps) > 1:
306 if len(ps) > 1:
306 if not p2:
307 if not p2:
307 p2 = repo[ps[1]]
308 p2 = repo[ps[1]]
308 for fn in p2:
309 for fn in p2:
309 if fn.startswith(b"nf"):
310 if fn.startswith(b"nf"):
310 files.append(fn)
311 files.append(fn)
311 filecontent[fn] = p2[fn].data()
312 filecontent[fn] = p2[fn].data()
312
313
313 def fctxfn(repo, cx, path):
314 def fctxfn(repo, cx, path):
314 if path in filecontent:
315 if path in filecontent:
315 return context.memfilectx(
316 return context.memfilectx(
316 repo, cx, path, filecontent[path]
317 repo, cx, path, filecontent[path]
317 )
318 )
318 return None
319 return None
319
320
320 if len(ps) == 0 or ps[0] < 0:
321 if len(ps) == 0 or ps[0] < 0:
321 pars = [None, None]
322 pars = [None, None]
322 elif len(ps) == 1:
323 elif len(ps) == 1:
323 pars = [nodeids[ps[0]], None]
324 pars = [nodeids[ps[0]], None]
324 else:
325 else:
325 pars = [nodeids[p] for p in ps]
326 pars = [nodeids[p] for p in ps]
326 cx = context.memctx(
327 cx = context.memctx(
327 repo,
328 repo,
328 pars,
329 pars,
329 b"r%i" % id,
330 b"r%i" % id,
330 files,
331 files,
331 fctxfn,
332 fctxfn,
332 date=(id, 0),
333 date=(id, 0),
333 user=b"debugbuilddag",
334 user=b"debugbuilddag",
334 extra={b'branch': atbranch},
335 extra={b'branch': atbranch},
335 )
336 )
336 nodeid = repo.commitctx(cx)
337 nodeid = repo.commitctx(cx)
337 nodeids.append(nodeid)
338 nodeids.append(nodeid)
338 at = id
339 at = id
339 elif type == b'l':
340 elif type == b'l':
340 id, name = data
341 id, name = data
341 ui.note((b'tag %s\n' % name))
342 ui.note((b'tag %s\n' % name))
342 tags.append(b"%s %s\n" % (hex(repo.changelog.node(id)), name))
343 tags.append(b"%s %s\n" % (hex(repo.changelog.node(id)), name))
343 elif type == b'a':
344 elif type == b'a':
344 ui.note((b'branch %s\n' % data))
345 ui.note((b'branch %s\n' % data))
345 atbranch = data
346 atbranch = data
346 progress.update(id)
347 progress.update(id)
347
348
348 if tags:
349 if tags:
349 repo.vfs.write(b"localtags", b"".join(tags))
350 repo.vfs.write(b"localtags", b"".join(tags))
350
351
351
352
352 def _debugchangegroup(ui, gen, all=None, indent=0, **opts):
353 def _debugchangegroup(ui, gen, all=None, indent=0, **opts):
353 indent_string = b' ' * indent
354 indent_string = b' ' * indent
354 if all:
355 if all:
355 ui.writenoi18n(
356 ui.writenoi18n(
356 b"%sformat: id, p1, p2, cset, delta base, len(delta)\n"
357 b"%sformat: id, p1, p2, cset, delta base, len(delta)\n"
357 % indent_string
358 % indent_string
358 )
359 )
359
360
360 def showchunks(named):
361 def showchunks(named):
361 ui.write(b"\n%s%s\n" % (indent_string, named))
362 ui.write(b"\n%s%s\n" % (indent_string, named))
362 for deltadata in gen.deltaiter():
363 for deltadata in gen.deltaiter():
363 node, p1, p2, cs, deltabase, delta, flags, sidedata = deltadata
364 node, p1, p2, cs, deltabase, delta, flags, sidedata = deltadata
364 ui.write(
365 ui.write(
365 b"%s%s %s %s %s %s %d\n"
366 b"%s%s %s %s %s %s %d\n"
366 % (
367 % (
367 indent_string,
368 indent_string,
368 hex(node),
369 hex(node),
369 hex(p1),
370 hex(p1),
370 hex(p2),
371 hex(p2),
371 hex(cs),
372 hex(cs),
372 hex(deltabase),
373 hex(deltabase),
373 len(delta),
374 len(delta),
374 )
375 )
375 )
376 )
376
377
377 gen.changelogheader()
378 gen.changelogheader()
378 showchunks(b"changelog")
379 showchunks(b"changelog")
379 gen.manifestheader()
380 gen.manifestheader()
380 showchunks(b"manifest")
381 showchunks(b"manifest")
381 for chunkdata in iter(gen.filelogheader, {}):
382 for chunkdata in iter(gen.filelogheader, {}):
382 fname = chunkdata[b'filename']
383 fname = chunkdata[b'filename']
383 showchunks(fname)
384 showchunks(fname)
384 else:
385 else:
385 if isinstance(gen, bundle2.unbundle20):
386 if isinstance(gen, bundle2.unbundle20):
386 raise error.Abort(_(b'use debugbundle2 for this file'))
387 raise error.Abort(_(b'use debugbundle2 for this file'))
387 gen.changelogheader()
388 gen.changelogheader()
388 for deltadata in gen.deltaiter():
389 for deltadata in gen.deltaiter():
389 node, p1, p2, cs, deltabase, delta, flags, sidedata = deltadata
390 node, p1, p2, cs, deltabase, delta, flags, sidedata = deltadata
390 ui.write(b"%s%s\n" % (indent_string, hex(node)))
391 ui.write(b"%s%s\n" % (indent_string, hex(node)))
391
392
392
393
393 def _debugobsmarkers(ui, part, indent=0, **opts):
394 def _debugobsmarkers(ui, part, indent=0, **opts):
394 """display version and markers contained in 'data'"""
395 """display version and markers contained in 'data'"""
395 opts = pycompat.byteskwargs(opts)
396 opts = pycompat.byteskwargs(opts)
396 data = part.read()
397 data = part.read()
397 indent_string = b' ' * indent
398 indent_string = b' ' * indent
398 try:
399 try:
399 version, markers = obsolete._readmarkers(data)
400 version, markers = obsolete._readmarkers(data)
400 except error.UnknownVersion as exc:
401 except error.UnknownVersion as exc:
401 msg = b"%sunsupported version: %s (%d bytes)\n"
402 msg = b"%sunsupported version: %s (%d bytes)\n"
402 msg %= indent_string, exc.version, len(data)
403 msg %= indent_string, exc.version, len(data)
403 ui.write(msg)
404 ui.write(msg)
404 else:
405 else:
405 msg = b"%sversion: %d (%d bytes)\n"
406 msg = b"%sversion: %d (%d bytes)\n"
406 msg %= indent_string, version, len(data)
407 msg %= indent_string, version, len(data)
407 ui.write(msg)
408 ui.write(msg)
408 fm = ui.formatter(b'debugobsolete', opts)
409 fm = ui.formatter(b'debugobsolete', opts)
409 for rawmarker in sorted(markers):
410 for rawmarker in sorted(markers):
410 m = obsutil.marker(None, rawmarker)
411 m = obsutil.marker(None, rawmarker)
411 fm.startitem()
412 fm.startitem()
412 fm.plain(indent_string)
413 fm.plain(indent_string)
413 cmdutil.showmarker(fm, m)
414 cmdutil.showmarker(fm, m)
414 fm.end()
415 fm.end()
415
416
416
417
417 def _debugphaseheads(ui, data, indent=0):
418 def _debugphaseheads(ui, data, indent=0):
418 """display version and markers contained in 'data'"""
419 """display version and markers contained in 'data'"""
419 indent_string = b' ' * indent
420 indent_string = b' ' * indent
420 headsbyphase = phases.binarydecode(data)
421 headsbyphase = phases.binarydecode(data)
421 for phase in phases.allphases:
422 for phase in phases.allphases:
422 for head in headsbyphase[phase]:
423 for head in headsbyphase[phase]:
423 ui.write(indent_string)
424 ui.write(indent_string)
424 ui.write(b'%s %s\n' % (hex(head), phases.phasenames[phase]))
425 ui.write(b'%s %s\n' % (hex(head), phases.phasenames[phase]))
425
426
426
427
427 def _quasirepr(thing):
428 def _quasirepr(thing):
428 if isinstance(thing, (dict, util.sortdict, collections.OrderedDict)):
429 if isinstance(thing, (dict, util.sortdict, collections.OrderedDict)):
429 return b'{%s}' % (
430 return b'{%s}' % (
430 b', '.join(b'%s: %s' % (k, thing[k]) for k in sorted(thing))
431 b', '.join(b'%s: %s' % (k, thing[k]) for k in sorted(thing))
431 )
432 )
432 return pycompat.bytestr(repr(thing))
433 return pycompat.bytestr(repr(thing))
433
434
434
435
435 def _debugbundle2(ui, gen, all=None, **opts):
436 def _debugbundle2(ui, gen, all=None, **opts):
436 """lists the contents of a bundle2"""
437 """lists the contents of a bundle2"""
437 if not isinstance(gen, bundle2.unbundle20):
438 if not isinstance(gen, bundle2.unbundle20):
438 raise error.Abort(_(b'not a bundle2 file'))
439 raise error.Abort(_(b'not a bundle2 file'))
439 ui.write((b'Stream params: %s\n' % _quasirepr(gen.params)))
440 ui.write((b'Stream params: %s\n' % _quasirepr(gen.params)))
440 parttypes = opts.get('part_type', [])
441 parttypes = opts.get('part_type', [])
441 for part in gen.iterparts():
442 for part in gen.iterparts():
442 if parttypes and part.type not in parttypes:
443 if parttypes and part.type not in parttypes:
443 continue
444 continue
444 msg = b'%s -- %s (mandatory: %r)\n'
445 msg = b'%s -- %s (mandatory: %r)\n'
445 ui.write((msg % (part.type, _quasirepr(part.params), part.mandatory)))
446 ui.write((msg % (part.type, _quasirepr(part.params), part.mandatory)))
446 if part.type == b'changegroup':
447 if part.type == b'changegroup':
447 version = part.params.get(b'version', b'01')
448 version = part.params.get(b'version', b'01')
448 cg = changegroup.getunbundler(version, part, b'UN')
449 cg = changegroup.getunbundler(version, part, b'UN')
449 if not ui.quiet:
450 if not ui.quiet:
450 _debugchangegroup(ui, cg, all=all, indent=4, **opts)
451 _debugchangegroup(ui, cg, all=all, indent=4, **opts)
451 if part.type == b'obsmarkers':
452 if part.type == b'obsmarkers':
452 if not ui.quiet:
453 if not ui.quiet:
453 _debugobsmarkers(ui, part, indent=4, **opts)
454 _debugobsmarkers(ui, part, indent=4, **opts)
454 if part.type == b'phase-heads':
455 if part.type == b'phase-heads':
455 if not ui.quiet:
456 if not ui.quiet:
456 _debugphaseheads(ui, part, indent=4)
457 _debugphaseheads(ui, part, indent=4)
457
458
458
459
459 @command(
460 @command(
460 b'debugbundle',
461 b'debugbundle',
461 [
462 [
462 (b'a', b'all', None, _(b'show all details')),
463 (b'a', b'all', None, _(b'show all details')),
463 (b'', b'part-type', [], _(b'show only the named part type')),
464 (b'', b'part-type', [], _(b'show only the named part type')),
464 (b'', b'spec', None, _(b'print the bundlespec of the bundle')),
465 (b'', b'spec', None, _(b'print the bundlespec of the bundle')),
465 ],
466 ],
466 _(b'FILE'),
467 _(b'FILE'),
467 norepo=True,
468 norepo=True,
468 )
469 )
469 def debugbundle(ui, bundlepath, all=None, spec=None, **opts):
470 def debugbundle(ui, bundlepath, all=None, spec=None, **opts):
470 """lists the contents of a bundle"""
471 """lists the contents of a bundle"""
471 with hg.openpath(ui, bundlepath) as f:
472 with hg.openpath(ui, bundlepath) as f:
472 if spec:
473 if spec:
473 spec = exchange.getbundlespec(ui, f)
474 spec = exchange.getbundlespec(ui, f)
474 ui.write(b'%s\n' % spec)
475 ui.write(b'%s\n' % spec)
475 return
476 return
476
477
477 gen = exchange.readbundle(ui, f, bundlepath)
478 gen = exchange.readbundle(ui, f, bundlepath)
478 if isinstance(gen, bundle2.unbundle20):
479 if isinstance(gen, bundle2.unbundle20):
479 return _debugbundle2(ui, gen, all=all, **opts)
480 return _debugbundle2(ui, gen, all=all, **opts)
480 _debugchangegroup(ui, gen, all=all, **opts)
481 _debugchangegroup(ui, gen, all=all, **opts)
481
482
482
483
483 @command(b'debugcapabilities', [], _(b'PATH'), norepo=True)
484 @command(b'debugcapabilities', [], _(b'PATH'), norepo=True)
484 def debugcapabilities(ui, path, **opts):
485 def debugcapabilities(ui, path, **opts):
485 """lists the capabilities of a remote peer"""
486 """lists the capabilities of a remote peer"""
486 opts = pycompat.byteskwargs(opts)
487 opts = pycompat.byteskwargs(opts)
487 peer = hg.peer(ui, opts, path)
488 peer = hg.peer(ui, opts, path)
488 try:
489 try:
489 caps = peer.capabilities()
490 caps = peer.capabilities()
490 ui.writenoi18n(b'Main capabilities:\n')
491 ui.writenoi18n(b'Main capabilities:\n')
491 for c in sorted(caps):
492 for c in sorted(caps):
492 ui.write(b' %s\n' % c)
493 ui.write(b' %s\n' % c)
493 b2caps = bundle2.bundle2caps(peer)
494 b2caps = bundle2.bundle2caps(peer)
494 if b2caps:
495 if b2caps:
495 ui.writenoi18n(b'Bundle2 capabilities:\n')
496 ui.writenoi18n(b'Bundle2 capabilities:\n')
496 for key, values in sorted(b2caps.items()):
497 for key, values in sorted(b2caps.items()):
497 ui.write(b' %s\n' % key)
498 ui.write(b' %s\n' % key)
498 for v in values:
499 for v in values:
499 ui.write(b' %s\n' % v)
500 ui.write(b' %s\n' % v)
500 finally:
501 finally:
501 peer.close()
502 peer.close()
502
503
503
504
504 @command(
505 @command(
505 b'debugchangedfiles',
506 b'debugchangedfiles',
506 [
507 [
507 (
508 (
508 b'',
509 b'',
509 b'compute',
510 b'compute',
510 False,
511 False,
511 b"compute information instead of reading it from storage",
512 b"compute information instead of reading it from storage",
512 ),
513 ),
513 ],
514 ],
514 b'REV',
515 b'REV',
515 )
516 )
516 def debugchangedfiles(ui, repo, rev, **opts):
517 def debugchangedfiles(ui, repo, rev, **opts):
517 """list the stored files changes for a revision"""
518 """list the stored files changes for a revision"""
518 ctx = logcmdutil.revsingle(repo, rev, None)
519 ctx = logcmdutil.revsingle(repo, rev, None)
519 files = None
520 files = None
520
521
521 if opts['compute']:
522 if opts['compute']:
522 files = metadata.compute_all_files_changes(ctx)
523 files = metadata.compute_all_files_changes(ctx)
523 else:
524 else:
524 sd = repo.changelog.sidedata(ctx.rev())
525 sd = repo.changelog.sidedata(ctx.rev())
525 files_block = sd.get(sidedata.SD_FILES)
526 files_block = sd.get(sidedata.SD_FILES)
526 if files_block is not None:
527 if files_block is not None:
527 files = metadata.decode_files_sidedata(sd)
528 files = metadata.decode_files_sidedata(sd)
528 if files is not None:
529 if files is not None:
529 for f in sorted(files.touched):
530 for f in sorted(files.touched):
530 if f in files.added:
531 if f in files.added:
531 action = b"added"
532 action = b"added"
532 elif f in files.removed:
533 elif f in files.removed:
533 action = b"removed"
534 action = b"removed"
534 elif f in files.merged:
535 elif f in files.merged:
535 action = b"merged"
536 action = b"merged"
536 elif f in files.salvaged:
537 elif f in files.salvaged:
537 action = b"salvaged"
538 action = b"salvaged"
538 else:
539 else:
539 action = b"touched"
540 action = b"touched"
540
541
541 copy_parent = b""
542 copy_parent = b""
542 copy_source = b""
543 copy_source = b""
543 if f in files.copied_from_p1:
544 if f in files.copied_from_p1:
544 copy_parent = b"p1"
545 copy_parent = b"p1"
545 copy_source = files.copied_from_p1[f]
546 copy_source = files.copied_from_p1[f]
546 elif f in files.copied_from_p2:
547 elif f in files.copied_from_p2:
547 copy_parent = b"p2"
548 copy_parent = b"p2"
548 copy_source = files.copied_from_p2[f]
549 copy_source = files.copied_from_p2[f]
549
550
550 data = (action, copy_parent, f, copy_source)
551 data = (action, copy_parent, f, copy_source)
551 template = b"%-8s %2s: %s, %s;\n"
552 template = b"%-8s %2s: %s, %s;\n"
552 ui.write(template % data)
553 ui.write(template % data)
553
554
554
555
555 @command(b'debugcheckstate', [], b'')
556 @command(b'debugcheckstate', [], b'')
556 def debugcheckstate(ui, repo):
557 def debugcheckstate(ui, repo):
557 """validate the correctness of the current dirstate"""
558 """validate the correctness of the current dirstate"""
558 errors = verify.verifier(repo)._verify_dirstate()
559 errors = verify.verifier(repo)._verify_dirstate()
559 if errors:
560 if errors:
560 errstr = _(b"dirstate inconsistent with current parent's manifest")
561 errstr = _(b"dirstate inconsistent with current parent's manifest")
561 raise error.Abort(errstr)
562 raise error.Abort(errstr)
562
563
563
564
564 @command(
565 @command(
565 b'debugcolor',
566 b'debugcolor',
566 [(b'', b'style', None, _(b'show all configured styles'))],
567 [(b'', b'style', None, _(b'show all configured styles'))],
567 b'hg debugcolor',
568 b'hg debugcolor',
568 )
569 )
569 def debugcolor(ui, repo, **opts):
570 def debugcolor(ui, repo, **opts):
570 """show available color, effects or style"""
571 """show available color, effects or style"""
571 ui.writenoi18n(b'color mode: %s\n' % stringutil.pprint(ui._colormode))
572 ui.writenoi18n(b'color mode: %s\n' % stringutil.pprint(ui._colormode))
572 if opts.get('style'):
573 if opts.get('style'):
573 return _debugdisplaystyle(ui)
574 return _debugdisplaystyle(ui)
574 else:
575 else:
575 return _debugdisplaycolor(ui)
576 return _debugdisplaycolor(ui)
576
577
577
578
578 def _debugdisplaycolor(ui):
579 def _debugdisplaycolor(ui):
579 ui = ui.copy()
580 ui = ui.copy()
580 ui._styles.clear()
581 ui._styles.clear()
581 for effect in color._activeeffects(ui).keys():
582 for effect in color._activeeffects(ui).keys():
582 ui._styles[effect] = effect
583 ui._styles[effect] = effect
583 if ui._terminfoparams:
584 if ui._terminfoparams:
584 for k, v in ui.configitems(b'color'):
585 for k, v in ui.configitems(b'color'):
585 if k.startswith(b'color.'):
586 if k.startswith(b'color.'):
586 ui._styles[k] = k[6:]
587 ui._styles[k] = k[6:]
587 elif k.startswith(b'terminfo.'):
588 elif k.startswith(b'terminfo.'):
588 ui._styles[k] = k[9:]
589 ui._styles[k] = k[9:]
589 ui.write(_(b'available colors:\n'))
590 ui.write(_(b'available colors:\n'))
590 # sort label with a '_' after the other to group '_background' entry.
591 # sort label with a '_' after the other to group '_background' entry.
591 items = sorted(ui._styles.items(), key=lambda i: (b'_' in i[0], i[0], i[1]))
592 items = sorted(ui._styles.items(), key=lambda i: (b'_' in i[0], i[0], i[1]))
592 for colorname, label in items:
593 for colorname, label in items:
593 ui.write(b'%s\n' % colorname, label=label)
594 ui.write(b'%s\n' % colorname, label=label)
594
595
595
596
596 def _debugdisplaystyle(ui):
597 def _debugdisplaystyle(ui):
597 ui.write(_(b'available style:\n'))
598 ui.write(_(b'available style:\n'))
598 if not ui._styles:
599 if not ui._styles:
599 return
600 return
600 width = max(len(s) for s in ui._styles)
601 width = max(len(s) for s in ui._styles)
601 for label, effects in sorted(ui._styles.items()):
602 for label, effects in sorted(ui._styles.items()):
602 ui.write(b'%s' % label, label=label)
603 ui.write(b'%s' % label, label=label)
603 if effects:
604 if effects:
604 # 50
605 # 50
605 ui.write(b': ')
606 ui.write(b': ')
606 ui.write(b' ' * (max(0, width - len(label))))
607 ui.write(b' ' * (max(0, width - len(label))))
607 ui.write(b', '.join(ui.label(e, e) for e in effects.split()))
608 ui.write(b', '.join(ui.label(e, e) for e in effects.split()))
608 ui.write(b'\n')
609 ui.write(b'\n')
609
610
610
611
611 @command(b'debugcreatestreamclonebundle', [], b'FILE')
612 @command(b'debugcreatestreamclonebundle', [], b'FILE')
612 def debugcreatestreamclonebundle(ui, repo, fname):
613 def debugcreatestreamclonebundle(ui, repo, fname):
613 """create a stream clone bundle file
614 """create a stream clone bundle file
614
615
615 Stream bundles are special bundles that are essentially archives of
616 Stream bundles are special bundles that are essentially archives of
616 revlog files. They are commonly used for cloning very quickly.
617 revlog files. They are commonly used for cloning very quickly.
617 """
618 """
618 # TODO we may want to turn this into an abort when this functionality
619 # TODO we may want to turn this into an abort when this functionality
619 # is moved into `hg bundle`.
620 # is moved into `hg bundle`.
620 if phases.hassecret(repo):
621 if phases.hassecret(repo):
621 ui.warn(
622 ui.warn(
622 _(
623 _(
623 b'(warning: stream clone bundle will contain secret '
624 b'(warning: stream clone bundle will contain secret '
624 b'revisions)\n'
625 b'revisions)\n'
625 )
626 )
626 )
627 )
627
628
628 requirements, gen = streamclone.generatebundlev1(repo)
629 requirements, gen = streamclone.generatebundlev1(repo)
629 changegroup.writechunks(ui, gen, fname)
630 changegroup.writechunks(ui, gen, fname)
630
631
631 ui.write(_(b'bundle requirements: %s\n') % b', '.join(sorted(requirements)))
632 ui.write(_(b'bundle requirements: %s\n') % b', '.join(sorted(requirements)))
632
633
633
634
634 @command(
635 @command(
635 b'debugdag',
636 b'debugdag',
636 [
637 [
637 (b't', b'tags', None, _(b'use tags as labels')),
638 (b't', b'tags', None, _(b'use tags as labels')),
638 (b'b', b'branches', None, _(b'annotate with branch names')),
639 (b'b', b'branches', None, _(b'annotate with branch names')),
639 (b'', b'dots', None, _(b'use dots for runs')),
640 (b'', b'dots', None, _(b'use dots for runs')),
640 (b's', b'spaces', None, _(b'separate elements by spaces')),
641 (b's', b'spaces', None, _(b'separate elements by spaces')),
641 ],
642 ],
642 _(b'[OPTION]... [FILE [REV]...]'),
643 _(b'[OPTION]... [FILE [REV]...]'),
643 optionalrepo=True,
644 optionalrepo=True,
644 )
645 )
645 def debugdag(ui, repo, file_=None, *revs, **opts):
646 def debugdag(ui, repo, file_=None, *revs, **opts):
646 """format the changelog or an index DAG as a concise textual description
647 """format the changelog or an index DAG as a concise textual description
647
648
648 If you pass a revlog index, the revlog's DAG is emitted. If you list
649 If you pass a revlog index, the revlog's DAG is emitted. If you list
649 revision numbers, they get labeled in the output as rN.
650 revision numbers, they get labeled in the output as rN.
650
651
651 Otherwise, the changelog DAG of the current repo is emitted.
652 Otherwise, the changelog DAG of the current repo is emitted.
652 """
653 """
653 spaces = opts.get('spaces')
654 spaces = opts.get('spaces')
654 dots = opts.get('dots')
655 dots = opts.get('dots')
655 if file_:
656 if file_:
656 rlog = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), file_)
657 rlog = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False), file_)
657 revs = {int(r) for r in revs}
658 revs = {int(r) for r in revs}
658
659
659 def events():
660 def events():
660 for r in rlog:
661 for r in rlog:
661 yield b'n', (r, list(p for p in rlog.parentrevs(r) if p != -1))
662 yield b'n', (r, list(p for p in rlog.parentrevs(r) if p != -1))
662 if r in revs:
663 if r in revs:
663 yield b'l', (r, b"r%i" % r)
664 yield b'l', (r, b"r%i" % r)
664
665
665 elif repo:
666 elif repo:
666 cl = repo.changelog
667 cl = repo.changelog
667 tags = opts.get('tags')
668 tags = opts.get('tags')
668 branches = opts.get('branches')
669 branches = opts.get('branches')
669 if tags:
670 if tags:
670 labels = {}
671 labels = {}
671 for l, n in repo.tags().items():
672 for l, n in repo.tags().items():
672 labels.setdefault(cl.rev(n), []).append(l)
673 labels.setdefault(cl.rev(n), []).append(l)
673
674
674 def events():
675 def events():
675 b = b"default"
676 b = b"default"
676 for r in cl:
677 for r in cl:
677 if branches:
678 if branches:
678 newb = cl.read(cl.node(r))[5][b'branch']
679 newb = cl.read(cl.node(r))[5][b'branch']
679 if newb != b:
680 if newb != b:
680 yield b'a', newb
681 yield b'a', newb
681 b = newb
682 b = newb
682 yield b'n', (r, list(p for p in cl.parentrevs(r) if p != -1))
683 yield b'n', (r, list(p for p in cl.parentrevs(r) if p != -1))
683 if tags:
684 if tags:
684 ls = labels.get(r)
685 ls = labels.get(r)
685 if ls:
686 if ls:
686 for l in ls:
687 for l in ls:
687 yield b'l', (r, l)
688 yield b'l', (r, l)
688
689
689 else:
690 else:
690 raise error.Abort(_(b'need repo for changelog dag'))
691 raise error.Abort(_(b'need repo for changelog dag'))
691
692
692 for line in dagparser.dagtextlines(
693 for line in dagparser.dagtextlines(
693 events(),
694 events(),
694 addspaces=spaces,
695 addspaces=spaces,
695 wraplabels=True,
696 wraplabels=True,
696 wrapannotations=True,
697 wrapannotations=True,
697 wrapnonlinear=dots,
698 wrapnonlinear=dots,
698 usedots=dots,
699 usedots=dots,
699 maxlinewidth=70,
700 maxlinewidth=70,
700 ):
701 ):
701 ui.write(line)
702 ui.write(line)
702 ui.write(b"\n")
703 ui.write(b"\n")
703
704
704
705
705 @command(b'debugdata', cmdutil.debugrevlogopts, _(b'-c|-m|FILE REV'))
706 @command(b'debugdata', cmdutil.debugrevlogopts, _(b'-c|-m|FILE REV'))
706 def debugdata(ui, repo, file_, rev=None, **opts):
707 def debugdata(ui, repo, file_, rev=None, **opts):
707 """dump the contents of a data file revision"""
708 """dump the contents of a data file revision"""
708 opts = pycompat.byteskwargs(opts)
709 opts = pycompat.byteskwargs(opts)
709 if opts.get(b'changelog') or opts.get(b'manifest') or opts.get(b'dir'):
710 if opts.get(b'changelog') or opts.get(b'manifest') or opts.get(b'dir'):
710 if rev is not None:
711 if rev is not None:
711 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
712 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
712 file_, rev = None, file_
713 file_, rev = None, file_
713 elif rev is None:
714 elif rev is None:
714 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
715 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
715 r = cmdutil.openstorage(repo, b'debugdata', file_, opts)
716 r = cmdutil.openstorage(repo, b'debugdata', file_, opts)
716 try:
717 try:
717 ui.write(r.rawdata(r.lookup(rev)))
718 ui.write(r.rawdata(r.lookup(rev)))
718 except KeyError:
719 except KeyError:
719 raise error.Abort(_(b'invalid revision identifier %s') % rev)
720 raise error.Abort(_(b'invalid revision identifier %s') % rev)
720
721
721
722
722 @command(
723 @command(
723 b'debugdate',
724 b'debugdate',
724 [(b'e', b'extended', None, _(b'try extended date formats'))],
725 [(b'e', b'extended', None, _(b'try extended date formats'))],
725 _(b'[-e] DATE [RANGE]'),
726 _(b'[-e] DATE [RANGE]'),
726 norepo=True,
727 norepo=True,
727 optionalrepo=True,
728 optionalrepo=True,
728 )
729 )
729 def debugdate(ui, date, range=None, **opts):
730 def debugdate(ui, date, range=None, **opts):
730 """parse and display a date"""
731 """parse and display a date"""
731 if opts["extended"]:
732 if opts["extended"]:
732 d = dateutil.parsedate(date, dateutil.extendeddateformats)
733 d = dateutil.parsedate(date, dateutil.extendeddateformats)
733 else:
734 else:
734 d = dateutil.parsedate(date)
735 d = dateutil.parsedate(date)
735 ui.writenoi18n(b"internal: %d %d\n" % d)
736 ui.writenoi18n(b"internal: %d %d\n" % d)
736 ui.writenoi18n(b"standard: %s\n" % dateutil.datestr(d))
737 ui.writenoi18n(b"standard: %s\n" % dateutil.datestr(d))
737 if range:
738 if range:
738 m = dateutil.matchdate(range)
739 m = dateutil.matchdate(range)
739 ui.writenoi18n(b"match: %s\n" % m(d[0]))
740 ui.writenoi18n(b"match: %s\n" % m(d[0]))
740
741
741
742
742 @command(
743 @command(
743 b'debugdeltachain',
744 b'debugdeltachain',
744 cmdutil.debugrevlogopts + cmdutil.formatteropts,
745 cmdutil.debugrevlogopts + cmdutil.formatteropts,
745 _(b'-c|-m|FILE'),
746 _(b'-c|-m|FILE'),
746 optionalrepo=True,
747 optionalrepo=True,
747 )
748 )
748 def debugdeltachain(ui, repo, file_=None, **opts):
749 def debugdeltachain(ui, repo, file_=None, **opts):
749 """dump information about delta chains in a revlog
750 """dump information about delta chains in a revlog
750
751
751 Output can be templatized. Available template keywords are:
752 Output can be templatized. Available template keywords are:
752
753
753 :``rev``: revision number
754 :``rev``: revision number
754 :``p1``: parent 1 revision number (for reference)
755 :``p1``: parent 1 revision number (for reference)
755 :``p2``: parent 2 revision number (for reference)
756 :``p2``: parent 2 revision number (for reference)
756 :``chainid``: delta chain identifier (numbered by unique base)
757 :``chainid``: delta chain identifier (numbered by unique base)
757 :``chainlen``: delta chain length to this revision
758 :``chainlen``: delta chain length to this revision
758 :``prevrev``: previous revision in delta chain
759 :``prevrev``: previous revision in delta chain
759 :``deltatype``: role of delta / how it was computed
760 :``deltatype``: role of delta / how it was computed
760 - base: a full snapshot
761 - base: a full snapshot
761 - snap: an intermediate snapshot
762 - snap: an intermediate snapshot
762 - p1: a delta against the first parent
763 - p1: a delta against the first parent
763 - p2: a delta against the second parent
764 - p2: a delta against the second parent
764 - skip1: a delta against the same base as p1
765 - skip1: a delta against the same base as p1
765 (when p1 has empty delta
766 (when p1 has empty delta
766 - skip2: a delta against the same base as p2
767 - skip2: a delta against the same base as p2
767 (when p2 has empty delta
768 (when p2 has empty delta
768 - prev: a delta against the previous revision
769 - prev: a delta against the previous revision
769 - other: a delta against an arbitrary revision
770 - other: a delta against an arbitrary revision
770 :``compsize``: compressed size of revision
771 :``compsize``: compressed size of revision
771 :``uncompsize``: uncompressed size of revision
772 :``uncompsize``: uncompressed size of revision
772 :``chainsize``: total size of compressed revisions in chain
773 :``chainsize``: total size of compressed revisions in chain
773 :``chainratio``: total chain size divided by uncompressed revision size
774 :``chainratio``: total chain size divided by uncompressed revision size
774 (new delta chains typically start at ratio 2.00)
775 (new delta chains typically start at ratio 2.00)
775 :``lindist``: linear distance from base revision in delta chain to end
776 :``lindist``: linear distance from base revision in delta chain to end
776 of this revision
777 of this revision
777 :``extradist``: total size of revisions not part of this delta chain from
778 :``extradist``: total size of revisions not part of this delta chain from
778 base of delta chain to end of this revision; a measurement
779 base of delta chain to end of this revision; a measurement
779 of how much extra data we need to read/seek across to read
780 of how much extra data we need to read/seek across to read
780 the delta chain for this revision
781 the delta chain for this revision
781 :``extraratio``: extradist divided by chainsize; another representation of
782 :``extraratio``: extradist divided by chainsize; another representation of
782 how much unrelated data is needed to load this delta chain
783 how much unrelated data is needed to load this delta chain
783
784
784 If the repository is configured to use the sparse read, additional keywords
785 If the repository is configured to use the sparse read, additional keywords
785 are available:
786 are available:
786
787
787 :``readsize``: total size of data read from the disk for a revision
788 :``readsize``: total size of data read from the disk for a revision
788 (sum of the sizes of all the blocks)
789 (sum of the sizes of all the blocks)
789 :``largestblock``: size of the largest block of data read from the disk
790 :``largestblock``: size of the largest block of data read from the disk
790 :``readdensity``: density of useful bytes in the data read from the disk
791 :``readdensity``: density of useful bytes in the data read from the disk
791 :``srchunks``: in how many data hunks the whole revision would be read
792 :``srchunks``: in how many data hunks the whole revision would be read
792
793
793 The sparse read can be enabled with experimental.sparse-read = True
794 The sparse read can be enabled with experimental.sparse-read = True
794 """
795 """
795 opts = pycompat.byteskwargs(opts)
796 opts = pycompat.byteskwargs(opts)
796 r = cmdutil.openrevlog(repo, b'debugdeltachain', file_, opts)
797 r = cmdutil.openrevlog(repo, b'debugdeltachain', file_, opts)
797 index = r.index
798 index = r.index
798 start = r.start
799 start = r.start
799 length = r.length
800 length = r.length
800 generaldelta = r._generaldelta
801 generaldelta = r._generaldelta
801 withsparseread = getattr(r, '_withsparseread', False)
802 withsparseread = getattr(r, '_withsparseread', False)
802
803
803 # security to avoid crash on corrupted revlogs
804 # security to avoid crash on corrupted revlogs
804 total_revs = len(index)
805 total_revs = len(index)
805
806
806 chain_size_cache = {}
807 chain_size_cache = {}
807
808
808 def revinfo(rev):
809 def revinfo(rev):
809 e = index[rev]
810 e = index[rev]
810 compsize = e[revlog_constants.ENTRY_DATA_COMPRESSED_LENGTH]
811 compsize = e[revlog_constants.ENTRY_DATA_COMPRESSED_LENGTH]
811 uncompsize = e[revlog_constants.ENTRY_DATA_UNCOMPRESSED_LENGTH]
812 uncompsize = e[revlog_constants.ENTRY_DATA_UNCOMPRESSED_LENGTH]
812
813
813 base = e[revlog_constants.ENTRY_DELTA_BASE]
814 base = e[revlog_constants.ENTRY_DELTA_BASE]
814 p1 = e[revlog_constants.ENTRY_PARENT_1]
815 p1 = e[revlog_constants.ENTRY_PARENT_1]
815 p2 = e[revlog_constants.ENTRY_PARENT_2]
816 p2 = e[revlog_constants.ENTRY_PARENT_2]
816
817
817 # If the parents of a revision has an empty delta, we never try to delta
818 # If the parents of a revision has an empty delta, we never try to delta
818 # against that parent, but directly against the delta base of that
819 # against that parent, but directly against the delta base of that
819 # parent (recursively). It avoids adding a useless entry in the chain.
820 # parent (recursively). It avoids adding a useless entry in the chain.
820 #
821 #
821 # However we need to detect that as a special case for delta-type, that
822 # However we need to detect that as a special case for delta-type, that
822 # is not simply "other".
823 # is not simply "other".
823 p1_base = p1
824 p1_base = p1
824 if p1 != nullrev and p1 < total_revs:
825 if p1 != nullrev and p1 < total_revs:
825 e1 = index[p1]
826 e1 = index[p1]
826 while e1[revlog_constants.ENTRY_DATA_COMPRESSED_LENGTH] == 0:
827 while e1[revlog_constants.ENTRY_DATA_COMPRESSED_LENGTH] == 0:
827 new_base = e1[revlog_constants.ENTRY_DELTA_BASE]
828 new_base = e1[revlog_constants.ENTRY_DELTA_BASE]
828 if (
829 if (
829 new_base == p1_base
830 new_base == p1_base
830 or new_base == nullrev
831 or new_base == nullrev
831 or new_base >= total_revs
832 or new_base >= total_revs
832 ):
833 ):
833 break
834 break
834 p1_base = new_base
835 p1_base = new_base
835 e1 = index[p1_base]
836 e1 = index[p1_base]
836 p2_base = p2
837 p2_base = p2
837 if p2 != nullrev and p2 < total_revs:
838 if p2 != nullrev and p2 < total_revs:
838 e2 = index[p2]
839 e2 = index[p2]
839 while e2[revlog_constants.ENTRY_DATA_COMPRESSED_LENGTH] == 0:
840 while e2[revlog_constants.ENTRY_DATA_COMPRESSED_LENGTH] == 0:
840 new_base = e2[revlog_constants.ENTRY_DELTA_BASE]
841 new_base = e2[revlog_constants.ENTRY_DELTA_BASE]
841 if (
842 if (
842 new_base == p2_base
843 new_base == p2_base
843 or new_base == nullrev
844 or new_base == nullrev
844 or new_base >= total_revs
845 or new_base >= total_revs
845 ):
846 ):
846 break
847 break
847 p2_base = new_base
848 p2_base = new_base
848 e2 = index[p2_base]
849 e2 = index[p2_base]
849
850
850 if generaldelta:
851 if generaldelta:
851 if base == p1:
852 if base == p1:
852 deltatype = b'p1'
853 deltatype = b'p1'
853 elif base == p2:
854 elif base == p2:
854 deltatype = b'p2'
855 deltatype = b'p2'
855 elif base == rev:
856 elif base == rev:
856 deltatype = b'base'
857 deltatype = b'base'
857 elif base == p1_base:
858 elif base == p1_base:
858 deltatype = b'skip1'
859 deltatype = b'skip1'
859 elif base == p2_base:
860 elif base == p2_base:
860 deltatype = b'skip2'
861 deltatype = b'skip2'
861 elif r.issnapshot(rev):
862 elif r.issnapshot(rev):
862 deltatype = b'snap'
863 deltatype = b'snap'
863 elif base == rev - 1:
864 elif base == rev - 1:
864 deltatype = b'prev'
865 deltatype = b'prev'
865 else:
866 else:
866 deltatype = b'other'
867 deltatype = b'other'
867 else:
868 else:
868 if base == rev:
869 if base == rev:
869 deltatype = b'base'
870 deltatype = b'base'
870 else:
871 else:
871 deltatype = b'prev'
872 deltatype = b'prev'
872
873
873 chain = r._deltachain(rev)[0]
874 chain = r._deltachain(rev)[0]
874 chain_size = 0
875 chain_size = 0
875 for iter_rev in reversed(chain):
876 for iter_rev in reversed(chain):
876 cached = chain_size_cache.get(iter_rev)
877 cached = chain_size_cache.get(iter_rev)
877 if cached is not None:
878 if cached is not None:
878 chain_size += cached
879 chain_size += cached
879 break
880 break
880 e = index[iter_rev]
881 e = index[iter_rev]
881 chain_size += e[revlog_constants.ENTRY_DATA_COMPRESSED_LENGTH]
882 chain_size += e[revlog_constants.ENTRY_DATA_COMPRESSED_LENGTH]
882 chain_size_cache[rev] = chain_size
883 chain_size_cache[rev] = chain_size
883
884
884 return p1, p2, compsize, uncompsize, deltatype, chain, chain_size
885 return p1, p2, compsize, uncompsize, deltatype, chain, chain_size
885
886
886 fm = ui.formatter(b'debugdeltachain', opts)
887 fm = ui.formatter(b'debugdeltachain', opts)
887
888
888 fm.plain(
889 fm.plain(
889 b' rev p1 p2 chain# chainlen prev delta '
890 b' rev p1 p2 chain# chainlen prev delta '
890 b'size rawsize chainsize ratio lindist extradist '
891 b'size rawsize chainsize ratio lindist extradist '
891 b'extraratio'
892 b'extraratio'
892 )
893 )
893 if withsparseread:
894 if withsparseread:
894 fm.plain(b' readsize largestblk rddensity srchunks')
895 fm.plain(b' readsize largestblk rddensity srchunks')
895 fm.plain(b'\n')
896 fm.plain(b'\n')
896
897
897 chainbases = {}
898 chainbases = {}
898 for rev in r:
899 for rev in r:
899 p1, p2, comp, uncomp, deltatype, chain, chainsize = revinfo(rev)
900 p1, p2, comp, uncomp, deltatype, chain, chainsize = revinfo(rev)
900 chainbase = chain[0]
901 chainbase = chain[0]
901 chainid = chainbases.setdefault(chainbase, len(chainbases) + 1)
902 chainid = chainbases.setdefault(chainbase, len(chainbases) + 1)
902 basestart = start(chainbase)
903 basestart = start(chainbase)
903 revstart = start(rev)
904 revstart = start(rev)
904 lineardist = revstart + comp - basestart
905 lineardist = revstart + comp - basestart
905 extradist = lineardist - chainsize
906 extradist = lineardist - chainsize
906 try:
907 try:
907 prevrev = chain[-2]
908 prevrev = chain[-2]
908 except IndexError:
909 except IndexError:
909 prevrev = -1
910 prevrev = -1
910
911
911 if uncomp != 0:
912 if uncomp != 0:
912 chainratio = float(chainsize) / float(uncomp)
913 chainratio = float(chainsize) / float(uncomp)
913 else:
914 else:
914 chainratio = chainsize
915 chainratio = chainsize
915
916
916 if chainsize != 0:
917 if chainsize != 0:
917 extraratio = float(extradist) / float(chainsize)
918 extraratio = float(extradist) / float(chainsize)
918 else:
919 else:
919 extraratio = extradist
920 extraratio = extradist
920
921
921 fm.startitem()
922 fm.startitem()
922 fm.write(
923 fm.write(
923 b'rev p1 p2 chainid chainlen prevrev deltatype compsize '
924 b'rev p1 p2 chainid chainlen prevrev deltatype compsize '
924 b'uncompsize chainsize chainratio lindist extradist '
925 b'uncompsize chainsize chainratio lindist extradist '
925 b'extraratio',
926 b'extraratio',
926 b'%7d %7d %7d %7d %8d %8d %7s %10d %10d %10d %9.5f %9d %9d %10.5f',
927 b'%7d %7d %7d %7d %8d %8d %7s %10d %10d %10d %9.5f %9d %9d %10.5f',
927 rev,
928 rev,
928 p1,
929 p1,
929 p2,
930 p2,
930 chainid,
931 chainid,
931 len(chain),
932 len(chain),
932 prevrev,
933 prevrev,
933 deltatype,
934 deltatype,
934 comp,
935 comp,
935 uncomp,
936 uncomp,
936 chainsize,
937 chainsize,
937 chainratio,
938 chainratio,
938 lineardist,
939 lineardist,
939 extradist,
940 extradist,
940 extraratio,
941 extraratio,
941 rev=rev,
942 rev=rev,
942 chainid=chainid,
943 chainid=chainid,
943 chainlen=len(chain),
944 chainlen=len(chain),
944 prevrev=prevrev,
945 prevrev=prevrev,
945 deltatype=deltatype,
946 deltatype=deltatype,
946 compsize=comp,
947 compsize=comp,
947 uncompsize=uncomp,
948 uncompsize=uncomp,
948 chainsize=chainsize,
949 chainsize=chainsize,
949 chainratio=chainratio,
950 chainratio=chainratio,
950 lindist=lineardist,
951 lindist=lineardist,
951 extradist=extradist,
952 extradist=extradist,
952 extraratio=extraratio,
953 extraratio=extraratio,
953 )
954 )
954 if withsparseread:
955 if withsparseread:
955 readsize = 0
956 readsize = 0
956 largestblock = 0
957 largestblock = 0
957 srchunks = 0
958 srchunks = 0
958
959
959 for revschunk in deltautil.slicechunk(r, chain):
960 for revschunk in deltautil.slicechunk(r, chain):
960 srchunks += 1
961 srchunks += 1
961 blkend = start(revschunk[-1]) + length(revschunk[-1])
962 blkend = start(revschunk[-1]) + length(revschunk[-1])
962 blksize = blkend - start(revschunk[0])
963 blksize = blkend - start(revschunk[0])
963
964
964 readsize += blksize
965 readsize += blksize
965 if largestblock < blksize:
966 if largestblock < blksize:
966 largestblock = blksize
967 largestblock = blksize
967
968
968 if readsize:
969 if readsize:
969 readdensity = float(chainsize) / float(readsize)
970 readdensity = float(chainsize) / float(readsize)
970 else:
971 else:
971 readdensity = 1
972 readdensity = 1
972
973
973 fm.write(
974 fm.write(
974 b'readsize largestblock readdensity srchunks',
975 b'readsize largestblock readdensity srchunks',
975 b' %10d %10d %9.5f %8d',
976 b' %10d %10d %9.5f %8d',
976 readsize,
977 readsize,
977 largestblock,
978 largestblock,
978 readdensity,
979 readdensity,
979 srchunks,
980 srchunks,
980 readsize=readsize,
981 readsize=readsize,
981 largestblock=largestblock,
982 largestblock=largestblock,
982 readdensity=readdensity,
983 readdensity=readdensity,
983 srchunks=srchunks,
984 srchunks=srchunks,
984 )
985 )
985
986
986 fm.plain(b'\n')
987 fm.plain(b'\n')
987
988
988 fm.end()
989 fm.end()
989
990
990
991
991 @command(
992 @command(
992 b'debug-delta-find',
993 b'debug-delta-find',
993 cmdutil.debugrevlogopts
994 cmdutil.debugrevlogopts
994 + cmdutil.formatteropts
995 + cmdutil.formatteropts
995 + [
996 + [
996 (
997 (
997 b'',
998 b'',
998 b'source',
999 b'source',
999 b'full',
1000 b'full',
1000 _(b'input data feed to the process (full, storage, p1, p2, prev)'),
1001 _(b'input data feed to the process (full, storage, p1, p2, prev)'),
1001 ),
1002 ),
1002 ],
1003 ],
1003 _(b'-c|-m|FILE REV'),
1004 _(b'-c|-m|FILE REV'),
1004 optionalrepo=True,
1005 optionalrepo=True,
1005 )
1006 )
1006 def debugdeltafind(ui, repo, arg_1, arg_2=None, source=b'full', **opts):
1007 def debugdeltafind(ui, repo, arg_1, arg_2=None, source=b'full', **opts):
1007 """display the computation to get to a valid delta for storing REV
1008 """display the computation to get to a valid delta for storing REV
1008
1009
1009 This command will replay the process used to find the "best" delta to store
1010 This command will replay the process used to find the "best" delta to store
1010 a revision and display information about all the steps used to get to that
1011 a revision and display information about all the steps used to get to that
1011 result.
1012 result.
1012
1013
1013 By default, the process is fed with a the full-text for the revision. This
1014 By default, the process is fed with a the full-text for the revision. This
1014 can be controlled with the --source flag.
1015 can be controlled with the --source flag.
1015
1016
1016 The revision use the revision number of the target storage (not changelog
1017 The revision use the revision number of the target storage (not changelog
1017 revision number).
1018 revision number).
1018
1019
1019 note: the process is initiated from a full text of the revision to store.
1020 note: the process is initiated from a full text of the revision to store.
1020 """
1021 """
1021 opts = pycompat.byteskwargs(opts)
1022 opts = pycompat.byteskwargs(opts)
1022 if arg_2 is None:
1023 if arg_2 is None:
1023 file_ = None
1024 file_ = None
1024 rev = arg_1
1025 rev = arg_1
1025 else:
1026 else:
1026 file_ = arg_1
1027 file_ = arg_1
1027 rev = arg_2
1028 rev = arg_2
1028
1029
1029 rev = int(rev)
1030 rev = int(rev)
1030
1031
1031 revlog = cmdutil.openrevlog(repo, b'debugdeltachain', file_, opts)
1032 revlog = cmdutil.openrevlog(repo, b'debugdeltachain', file_, opts)
1032 p1r, p2r = revlog.parentrevs(rev)
1033 p1r, p2r = revlog.parentrevs(rev)
1033
1034
1034 if source == b'full':
1035 if source == b'full':
1035 base_rev = nullrev
1036 base_rev = nullrev
1036 elif source == b'storage':
1037 elif source == b'storage':
1037 base_rev = revlog.deltaparent(rev)
1038 base_rev = revlog.deltaparent(rev)
1038 elif source == b'p1':
1039 elif source == b'p1':
1039 base_rev = p1r
1040 base_rev = p1r
1040 elif source == b'p2':
1041 elif source == b'p2':
1041 base_rev = p2r
1042 base_rev = p2r
1042 elif source == b'prev':
1043 elif source == b'prev':
1043 base_rev = rev - 1
1044 base_rev = rev - 1
1044 else:
1045 else:
1045 raise error.InputError(b"invalid --source value: %s" % source)
1046 raise error.InputError(b"invalid --source value: %s" % source)
1046
1047
1047 revlog_debug.debug_delta_find(ui, revlog, rev, base_rev=base_rev)
1048 revlog_debug.debug_delta_find(ui, revlog, rev, base_rev=base_rev)
1048
1049
1049
1050
1050 @command(
1051 @command(
1051 b'debugdirstate|debugstate',
1052 b'debugdirstate|debugstate',
1052 [
1053 [
1053 (
1054 (
1054 b'',
1055 b'',
1055 b'nodates',
1056 b'nodates',
1056 None,
1057 None,
1057 _(b'do not display the saved mtime (DEPRECATED)'),
1058 _(b'do not display the saved mtime (DEPRECATED)'),
1058 ),
1059 ),
1059 (b'', b'dates', True, _(b'display the saved mtime')),
1060 (b'', b'dates', True, _(b'display the saved mtime')),
1060 (b'', b'datesort', None, _(b'sort by saved mtime')),
1061 (b'', b'datesort', None, _(b'sort by saved mtime')),
1061 (
1062 (
1062 b'',
1063 b'',
1063 b'docket',
1064 b'docket',
1064 False,
1065 False,
1065 _(b'display the docket (metadata file) instead'),
1066 _(b'display the docket (metadata file) instead'),
1066 ),
1067 ),
1067 (
1068 (
1068 b'',
1069 b'',
1069 b'all',
1070 b'all',
1070 False,
1071 False,
1071 _(b'display dirstate-v2 tree nodes that would not exist in v1'),
1072 _(b'display dirstate-v2 tree nodes that would not exist in v1'),
1072 ),
1073 ),
1073 ],
1074 ],
1074 _(b'[OPTION]...'),
1075 _(b'[OPTION]...'),
1075 )
1076 )
1076 def debugstate(ui, repo, **opts):
1077 def debugstate(ui, repo, **opts):
1077 """show the contents of the current dirstate"""
1078 """show the contents of the current dirstate"""
1078
1079
1079 if opts.get("docket"):
1080 if opts.get("docket"):
1080 if not repo.dirstate._use_dirstate_v2:
1081 if not repo.dirstate._use_dirstate_v2:
1081 raise error.Abort(_(b'dirstate v1 does not have a docket'))
1082 raise error.Abort(_(b'dirstate v1 does not have a docket'))
1082
1083
1083 docket = repo.dirstate._map.docket
1084 docket = repo.dirstate._map.docket
1084 (
1085 (
1085 start_offset,
1086 start_offset,
1086 root_nodes,
1087 root_nodes,
1087 nodes_with_entry,
1088 nodes_with_entry,
1088 nodes_with_copy,
1089 nodes_with_copy,
1089 unused_bytes,
1090 unused_bytes,
1090 _unused,
1091 _unused,
1091 ignore_pattern,
1092 ignore_pattern,
1092 ) = dirstateutils.v2.TREE_METADATA.unpack(docket.tree_metadata)
1093 ) = dirstateutils.v2.TREE_METADATA.unpack(docket.tree_metadata)
1093
1094
1094 ui.write(_(b"size of dirstate data: %d\n") % docket.data_size)
1095 ui.write(_(b"size of dirstate data: %d\n") % docket.data_size)
1095 ui.write(_(b"data file uuid: %s\n") % docket.uuid)
1096 ui.write(_(b"data file uuid: %s\n") % docket.uuid)
1096 ui.write(_(b"start offset of root nodes: %d\n") % start_offset)
1097 ui.write(_(b"start offset of root nodes: %d\n") % start_offset)
1097 ui.write(_(b"number of root nodes: %d\n") % root_nodes)
1098 ui.write(_(b"number of root nodes: %d\n") % root_nodes)
1098 ui.write(_(b"nodes with entries: %d\n") % nodes_with_entry)
1099 ui.write(_(b"nodes with entries: %d\n") % nodes_with_entry)
1099 ui.write(_(b"nodes with copies: %d\n") % nodes_with_copy)
1100 ui.write(_(b"nodes with copies: %d\n") % nodes_with_copy)
1100 ui.write(_(b"number of unused bytes: %d\n") % unused_bytes)
1101 ui.write(_(b"number of unused bytes: %d\n") % unused_bytes)
1101 ui.write(
1102 ui.write(
1102 _(b"ignore pattern hash: %s\n") % binascii.hexlify(ignore_pattern)
1103 _(b"ignore pattern hash: %s\n") % binascii.hexlify(ignore_pattern)
1103 )
1104 )
1104 return
1105 return
1105
1106
1106 nodates = not opts['dates']
1107 nodates = not opts['dates']
1107 if opts.get('nodates') is not None:
1108 if opts.get('nodates') is not None:
1108 nodates = True
1109 nodates = True
1109 datesort = opts.get('datesort')
1110 datesort = opts.get('datesort')
1110
1111
1111 if datesort:
1112 if datesort:
1112
1113
1113 def keyfunc(entry):
1114 def keyfunc(entry):
1114 filename, _state, _mode, _size, mtime = entry
1115 filename, _state, _mode, _size, mtime = entry
1115 return (mtime, filename)
1116 return (mtime, filename)
1116
1117
1117 else:
1118 else:
1118 keyfunc = None # sort by filename
1119 keyfunc = None # sort by filename
1119 entries = list(repo.dirstate._map.debug_iter(all=opts['all']))
1120 entries = list(repo.dirstate._map.debug_iter(all=opts['all']))
1120 entries.sort(key=keyfunc)
1121 entries.sort(key=keyfunc)
1121 for entry in entries:
1122 for entry in entries:
1122 filename, state, mode, size, mtime = entry
1123 filename, state, mode, size, mtime = entry
1123 if mtime == -1:
1124 if mtime == -1:
1124 timestr = b'unset '
1125 timestr = b'unset '
1125 elif nodates:
1126 elif nodates:
1126 timestr = b'set '
1127 timestr = b'set '
1127 else:
1128 else:
1128 timestr = time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime(mtime))
1129 timestr = time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime(mtime))
1129 timestr = encoding.strtolocal(timestr)
1130 timestr = encoding.strtolocal(timestr)
1130 if mode & 0o20000:
1131 if mode & 0o20000:
1131 mode = b'lnk'
1132 mode = b'lnk'
1132 else:
1133 else:
1133 mode = b'%3o' % (mode & 0o777 & ~util.umask)
1134 mode = b'%3o' % (mode & 0o777 & ~util.umask)
1134 ui.write(b"%c %s %10d %s%s\n" % (state, mode, size, timestr, filename))
1135 ui.write(b"%c %s %10d %s%s\n" % (state, mode, size, timestr, filename))
1135 for f in repo.dirstate.copies():
1136 for f in repo.dirstate.copies():
1136 ui.write(_(b"copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
1137 ui.write(_(b"copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
1137
1138
1138
1139
1139 @command(
1140 @command(
1140 b'debugdirstateignorepatternshash',
1141 b'debugdirstateignorepatternshash',
1141 [],
1142 [],
1142 _(b''),
1143 _(b''),
1143 )
1144 )
1144 def debugdirstateignorepatternshash(ui, repo, **opts):
1145 def debugdirstateignorepatternshash(ui, repo, **opts):
1145 """show the hash of ignore patterns stored in dirstate if v2,
1146 """show the hash of ignore patterns stored in dirstate if v2,
1146 or nothing for dirstate-v2
1147 or nothing for dirstate-v2
1147 """
1148 """
1148 if repo.dirstate._use_dirstate_v2:
1149 if repo.dirstate._use_dirstate_v2:
1149 docket = repo.dirstate._map.docket
1150 docket = repo.dirstate._map.docket
1150 hash_len = 20 # 160 bits for SHA-1
1151 hash_len = 20 # 160 bits for SHA-1
1151 hash_bytes = docket.tree_metadata[-hash_len:]
1152 hash_bytes = docket.tree_metadata[-hash_len:]
1152 ui.write(binascii.hexlify(hash_bytes) + b'\n')
1153 ui.write(binascii.hexlify(hash_bytes) + b'\n')
1153
1154
1154
1155
1155 @command(
1156 @command(
1156 b'debugdiscovery',
1157 b'debugdiscovery',
1157 [
1158 [
1158 (b'', b'old', None, _(b'use old-style discovery')),
1159 (b'', b'old', None, _(b'use old-style discovery')),
1159 (
1160 (
1160 b'',
1161 b'',
1161 b'nonheads',
1162 b'nonheads',
1162 None,
1163 None,
1163 _(b'use old-style discovery with non-heads included'),
1164 _(b'use old-style discovery with non-heads included'),
1164 ),
1165 ),
1165 (b'', b'rev', [], b'restrict discovery to this set of revs'),
1166 (b'', b'rev', [], b'restrict discovery to this set of revs'),
1166 (b'', b'seed', b'12323', b'specify the random seed use for discovery'),
1167 (b'', b'seed', b'12323', b'specify the random seed use for discovery'),
1167 (
1168 (
1168 b'',
1169 b'',
1169 b'local-as-revs',
1170 b'local-as-revs',
1170 b"",
1171 b"",
1171 b'treat local has having these revisions only',
1172 b'treat local has having these revisions only',
1172 ),
1173 ),
1173 (
1174 (
1174 b'',
1175 b'',
1175 b'remote-as-revs',
1176 b'remote-as-revs',
1176 b"",
1177 b"",
1177 b'use local as remote, with only these revisions',
1178 b'use local as remote, with only these revisions',
1178 ),
1179 ),
1179 ]
1180 ]
1180 + cmdutil.remoteopts
1181 + cmdutil.remoteopts
1181 + cmdutil.formatteropts,
1182 + cmdutil.formatteropts,
1182 _(b'[--rev REV] [OTHER]'),
1183 _(b'[--rev REV] [OTHER]'),
1183 )
1184 )
1184 def debugdiscovery(ui, repo, remoteurl=b"default", **opts):
1185 def debugdiscovery(ui, repo, remoteurl=b"default", **opts):
1185 """runs the changeset discovery protocol in isolation
1186 """runs the changeset discovery protocol in isolation
1186
1187
1187 The local peer can be "replaced" by a subset of the local repository by
1188 The local peer can be "replaced" by a subset of the local repository by
1188 using the `--local-as-revs` flag. In the same way, the usual `remote` peer
1189 using the `--local-as-revs` flag. In the same way, the usual `remote` peer
1189 can be "replaced" by a subset of the local repository using the
1190 can be "replaced" by a subset of the local repository using the
1190 `--remote-as-revs` flag. This is useful to efficiently debug pathological
1191 `--remote-as-revs` flag. This is useful to efficiently debug pathological
1191 discovery situations.
1192 discovery situations.
1192
1193
1193 The following developer oriented config are relevant for people playing with this command:
1194 The following developer oriented config are relevant for people playing with this command:
1194
1195
1195 * devel.discovery.exchange-heads=True
1196 * devel.discovery.exchange-heads=True
1196
1197
1197 If False, the discovery will not start with
1198 If False, the discovery will not start with
1198 remote head fetching and local head querying.
1199 remote head fetching and local head querying.
1199
1200
1200 * devel.discovery.grow-sample=True
1201 * devel.discovery.grow-sample=True
1201
1202
1202 If False, the sample size used in set discovery will not be increased
1203 If False, the sample size used in set discovery will not be increased
1203 through the process
1204 through the process
1204
1205
1205 * devel.discovery.grow-sample.dynamic=True
1206 * devel.discovery.grow-sample.dynamic=True
1206
1207
1207 When discovery.grow-sample.dynamic is True, the default, the sample size is
1208 When discovery.grow-sample.dynamic is True, the default, the sample size is
1208 adapted to the shape of the undecided set (it is set to the max of:
1209 adapted to the shape of the undecided set (it is set to the max of:
1209 <target-size>, len(roots(undecided)), len(heads(undecided)
1210 <target-size>, len(roots(undecided)), len(heads(undecided)
1210
1211
1211 * devel.discovery.grow-sample.rate=1.05
1212 * devel.discovery.grow-sample.rate=1.05
1212
1213
1213 the rate at which the sample grow
1214 the rate at which the sample grow
1214
1215
1215 * devel.discovery.randomize=True
1216 * devel.discovery.randomize=True
1216
1217
1217 If andom sampling during discovery are deterministic. It is meant for
1218 If andom sampling during discovery are deterministic. It is meant for
1218 integration tests.
1219 integration tests.
1219
1220
1220 * devel.discovery.sample-size=200
1221 * devel.discovery.sample-size=200
1221
1222
1222 Control the initial size of the discovery sample
1223 Control the initial size of the discovery sample
1223
1224
1224 * devel.discovery.sample-size.initial=100
1225 * devel.discovery.sample-size.initial=100
1225
1226
1226 Control the initial size of the discovery for initial change
1227 Control the initial size of the discovery for initial change
1227 """
1228 """
1228 opts = pycompat.byteskwargs(opts)
1229 opts = pycompat.byteskwargs(opts)
1229 unfi = repo.unfiltered()
1230 unfi = repo.unfiltered()
1230
1231
1231 # setup potential extra filtering
1232 # setup potential extra filtering
1232 local_revs = opts[b"local_as_revs"]
1233 local_revs = opts[b"local_as_revs"]
1233 remote_revs = opts[b"remote_as_revs"]
1234 remote_revs = opts[b"remote_as_revs"]
1234
1235
1235 # make sure tests are repeatable
1236 # make sure tests are repeatable
1236 random.seed(int(opts[b'seed']))
1237 random.seed(int(opts[b'seed']))
1237
1238
1238 if not remote_revs:
1239 if not remote_revs:
1239 path = urlutil.get_unique_pull_path_obj(
1240 path = urlutil.get_unique_pull_path_obj(
1240 b'debugdiscovery', ui, remoteurl
1241 b'debugdiscovery', ui, remoteurl
1241 )
1242 )
1242 branches = (path.branch, [])
1243 branches = (path.branch, [])
1243 remote = hg.peer(repo, opts, path)
1244 remote = hg.peer(repo, opts, path)
1244 ui.status(_(b'comparing with %s\n') % urlutil.hidepassword(path.loc))
1245 ui.status(_(b'comparing with %s\n') % urlutil.hidepassword(path.loc))
1245 else:
1246 else:
1246 branches = (None, [])
1247 branches = (None, [])
1247 remote_filtered_revs = logcmdutil.revrange(
1248 remote_filtered_revs = logcmdutil.revrange(
1248 unfi, [b"not (::(%s))" % remote_revs]
1249 unfi, [b"not (::(%s))" % remote_revs]
1249 )
1250 )
1250 remote_filtered_revs = frozenset(remote_filtered_revs)
1251 remote_filtered_revs = frozenset(remote_filtered_revs)
1251
1252
1252 def remote_func(x):
1253 def remote_func(x):
1253 return remote_filtered_revs
1254 return remote_filtered_revs
1254
1255
1255 repoview.filtertable[b'debug-discovery-remote-filter'] = remote_func
1256 repoview.filtertable[b'debug-discovery-remote-filter'] = remote_func
1256
1257
1257 remote = repo.peer()
1258 remote = repo.peer()
1258 remote._repo = remote._repo.filtered(b'debug-discovery-remote-filter')
1259 remote._repo = remote._repo.filtered(b'debug-discovery-remote-filter')
1259
1260
1260 if local_revs:
1261 if local_revs:
1261 local_filtered_revs = logcmdutil.revrange(
1262 local_filtered_revs = logcmdutil.revrange(
1262 unfi, [b"not (::(%s))" % local_revs]
1263 unfi, [b"not (::(%s))" % local_revs]
1263 )
1264 )
1264 local_filtered_revs = frozenset(local_filtered_revs)
1265 local_filtered_revs = frozenset(local_filtered_revs)
1265
1266
1266 def local_func(x):
1267 def local_func(x):
1267 return local_filtered_revs
1268 return local_filtered_revs
1268
1269
1269 repoview.filtertable[b'debug-discovery-local-filter'] = local_func
1270 repoview.filtertable[b'debug-discovery-local-filter'] = local_func
1270 repo = repo.filtered(b'debug-discovery-local-filter')
1271 repo = repo.filtered(b'debug-discovery-local-filter')
1271
1272
1272 data = {}
1273 data = {}
1273 if opts.get(b'old'):
1274 if opts.get(b'old'):
1274
1275
1275 def doit(pushedrevs, remoteheads, remote=remote):
1276 def doit(pushedrevs, remoteheads, remote=remote):
1276 if not util.safehasattr(remote, b'branches'):
1277 if not util.safehasattr(remote, b'branches'):
1277 # enable in-client legacy support
1278 # enable in-client legacy support
1278 remote = localrepo.locallegacypeer(remote.local())
1279 remote = localrepo.locallegacypeer(remote.local())
1279 if remote_revs:
1280 if remote_revs:
1280 r = remote._repo.filtered(b'debug-discovery-remote-filter')
1281 r = remote._repo.filtered(b'debug-discovery-remote-filter')
1281 remote._repo = r
1282 remote._repo = r
1282 common, _in, hds = treediscovery.findcommonincoming(
1283 common, _in, hds = treediscovery.findcommonincoming(
1283 repo, remote, force=True, audit=data
1284 repo, remote, force=True, audit=data
1284 )
1285 )
1285 common = set(common)
1286 common = set(common)
1286 if not opts.get(b'nonheads'):
1287 if not opts.get(b'nonheads'):
1287 ui.writenoi18n(
1288 ui.writenoi18n(
1288 b"unpruned common: %s\n"
1289 b"unpruned common: %s\n"
1289 % b" ".join(sorted(short(n) for n in common))
1290 % b" ".join(sorted(short(n) for n in common))
1290 )
1291 )
1291
1292
1292 clnode = repo.changelog.node
1293 clnode = repo.changelog.node
1293 common = repo.revs(b'heads(::%ln)', common)
1294 common = repo.revs(b'heads(::%ln)', common)
1294 common = {clnode(r) for r in common}
1295 common = {clnode(r) for r in common}
1295 return common, hds
1296 return common, hds
1296
1297
1297 else:
1298 else:
1298
1299
1299 def doit(pushedrevs, remoteheads, remote=remote):
1300 def doit(pushedrevs, remoteheads, remote=remote):
1300 nodes = None
1301 nodes = None
1301 if pushedrevs:
1302 if pushedrevs:
1302 revs = logcmdutil.revrange(repo, pushedrevs)
1303 revs = logcmdutil.revrange(repo, pushedrevs)
1303 nodes = [repo[r].node() for r in revs]
1304 nodes = [repo[r].node() for r in revs]
1304 common, any, hds = setdiscovery.findcommonheads(
1305 common, any, hds = setdiscovery.findcommonheads(
1305 ui,
1306 ui,
1306 repo,
1307 repo,
1307 remote,
1308 remote,
1308 ancestorsof=nodes,
1309 ancestorsof=nodes,
1309 audit=data,
1310 audit=data,
1310 abortwhenunrelated=False,
1311 abortwhenunrelated=False,
1311 )
1312 )
1312 return common, hds
1313 return common, hds
1313
1314
1314 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches, revs=None)
1315 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches, revs=None)
1315 localrevs = opts[b'rev']
1316 localrevs = opts[b'rev']
1316
1317
1317 fm = ui.formatter(b'debugdiscovery', opts)
1318 fm = ui.formatter(b'debugdiscovery', opts)
1318 if fm.strict_format:
1319 if fm.strict_format:
1319
1320
1320 @contextlib.contextmanager
1321 @contextlib.contextmanager
1321 def may_capture_output():
1322 def may_capture_output():
1322 ui.pushbuffer()
1323 ui.pushbuffer()
1323 yield
1324 yield
1324 data[b'output'] = ui.popbuffer()
1325 data[b'output'] = ui.popbuffer()
1325
1326
1326 else:
1327 else:
1327 may_capture_output = util.nullcontextmanager
1328 may_capture_output = util.nullcontextmanager
1328 with may_capture_output():
1329 with may_capture_output():
1329 with util.timedcm('debug-discovery') as t:
1330 with util.timedcm('debug-discovery') as t:
1330 common, hds = doit(localrevs, remoterevs)
1331 common, hds = doit(localrevs, remoterevs)
1331
1332
1332 # compute all statistics
1333 # compute all statistics
1333 if len(common) == 1 and repo.nullid in common:
1334 if len(common) == 1 and repo.nullid in common:
1334 common = set()
1335 common = set()
1335 heads_common = set(common)
1336 heads_common = set(common)
1336 heads_remote = set(hds)
1337 heads_remote = set(hds)
1337 heads_local = set(repo.heads())
1338 heads_local = set(repo.heads())
1338 # note: they cannot be a local or remote head that is in common and not
1339 # note: they cannot be a local or remote head that is in common and not
1339 # itself a head of common.
1340 # itself a head of common.
1340 heads_common_local = heads_common & heads_local
1341 heads_common_local = heads_common & heads_local
1341 heads_common_remote = heads_common & heads_remote
1342 heads_common_remote = heads_common & heads_remote
1342 heads_common_both = heads_common & heads_remote & heads_local
1343 heads_common_both = heads_common & heads_remote & heads_local
1343
1344
1344 all = repo.revs(b'all()')
1345 all = repo.revs(b'all()')
1345 common = repo.revs(b'::%ln', common)
1346 common = repo.revs(b'::%ln', common)
1346 roots_common = repo.revs(b'roots(::%ld)', common)
1347 roots_common = repo.revs(b'roots(::%ld)', common)
1347 missing = repo.revs(b'not ::%ld', common)
1348 missing = repo.revs(b'not ::%ld', common)
1348 heads_missing = repo.revs(b'heads(%ld)', missing)
1349 heads_missing = repo.revs(b'heads(%ld)', missing)
1349 roots_missing = repo.revs(b'roots(%ld)', missing)
1350 roots_missing = repo.revs(b'roots(%ld)', missing)
1350 assert len(common) + len(missing) == len(all)
1351 assert len(common) + len(missing) == len(all)
1351
1352
1352 initial_undecided = repo.revs(
1353 initial_undecided = repo.revs(
1353 b'not (::%ln or %ln::)', heads_common_remote, heads_common_local
1354 b'not (::%ln or %ln::)', heads_common_remote, heads_common_local
1354 )
1355 )
1355 heads_initial_undecided = repo.revs(b'heads(%ld)', initial_undecided)
1356 heads_initial_undecided = repo.revs(b'heads(%ld)', initial_undecided)
1356 roots_initial_undecided = repo.revs(b'roots(%ld)', initial_undecided)
1357 roots_initial_undecided = repo.revs(b'roots(%ld)', initial_undecided)
1357 common_initial_undecided = initial_undecided & common
1358 common_initial_undecided = initial_undecided & common
1358 missing_initial_undecided = initial_undecided & missing
1359 missing_initial_undecided = initial_undecided & missing
1359
1360
1360 data[b'elapsed'] = t.elapsed
1361 data[b'elapsed'] = t.elapsed
1361 data[b'nb-common-heads'] = len(heads_common)
1362 data[b'nb-common-heads'] = len(heads_common)
1362 data[b'nb-common-heads-local'] = len(heads_common_local)
1363 data[b'nb-common-heads-local'] = len(heads_common_local)
1363 data[b'nb-common-heads-remote'] = len(heads_common_remote)
1364 data[b'nb-common-heads-remote'] = len(heads_common_remote)
1364 data[b'nb-common-heads-both'] = len(heads_common_both)
1365 data[b'nb-common-heads-both'] = len(heads_common_both)
1365 data[b'nb-common-roots'] = len(roots_common)
1366 data[b'nb-common-roots'] = len(roots_common)
1366 data[b'nb-head-local'] = len(heads_local)
1367 data[b'nb-head-local'] = len(heads_local)
1367 data[b'nb-head-local-missing'] = len(heads_local) - len(heads_common_local)
1368 data[b'nb-head-local-missing'] = len(heads_local) - len(heads_common_local)
1368 data[b'nb-head-remote'] = len(heads_remote)
1369 data[b'nb-head-remote'] = len(heads_remote)
1369 data[b'nb-head-remote-unknown'] = len(heads_remote) - len(
1370 data[b'nb-head-remote-unknown'] = len(heads_remote) - len(
1370 heads_common_remote
1371 heads_common_remote
1371 )
1372 )
1372 data[b'nb-revs'] = len(all)
1373 data[b'nb-revs'] = len(all)
1373 data[b'nb-revs-common'] = len(common)
1374 data[b'nb-revs-common'] = len(common)
1374 data[b'nb-revs-missing'] = len(missing)
1375 data[b'nb-revs-missing'] = len(missing)
1375 data[b'nb-missing-heads'] = len(heads_missing)
1376 data[b'nb-missing-heads'] = len(heads_missing)
1376 data[b'nb-missing-roots'] = len(roots_missing)
1377 data[b'nb-missing-roots'] = len(roots_missing)
1377 data[b'nb-ini_und'] = len(initial_undecided)
1378 data[b'nb-ini_und'] = len(initial_undecided)
1378 data[b'nb-ini_und-heads'] = len(heads_initial_undecided)
1379 data[b'nb-ini_und-heads'] = len(heads_initial_undecided)
1379 data[b'nb-ini_und-roots'] = len(roots_initial_undecided)
1380 data[b'nb-ini_und-roots'] = len(roots_initial_undecided)
1380 data[b'nb-ini_und-common'] = len(common_initial_undecided)
1381 data[b'nb-ini_und-common'] = len(common_initial_undecided)
1381 data[b'nb-ini_und-missing'] = len(missing_initial_undecided)
1382 data[b'nb-ini_und-missing'] = len(missing_initial_undecided)
1382
1383
1383 fm.startitem()
1384 fm.startitem()
1384 fm.data(**pycompat.strkwargs(data))
1385 fm.data(**pycompat.strkwargs(data))
1385 # display discovery summary
1386 # display discovery summary
1386 fm.plain(b"elapsed time: %(elapsed)f seconds\n" % data)
1387 fm.plain(b"elapsed time: %(elapsed)f seconds\n" % data)
1387 fm.plain(b"round-trips: %(total-roundtrips)9d\n" % data)
1388 fm.plain(b"round-trips: %(total-roundtrips)9d\n" % data)
1388 if b'total-round-trips-heads' in data:
1389 if b'total-round-trips-heads' in data:
1389 fm.plain(
1390 fm.plain(
1390 b" round-trips-heads: %(total-round-trips-heads)9d\n" % data
1391 b" round-trips-heads: %(total-round-trips-heads)9d\n" % data
1391 )
1392 )
1392 if b'total-round-trips-branches' in data:
1393 if b'total-round-trips-branches' in data:
1393 fm.plain(
1394 fm.plain(
1394 b" round-trips-branches: %(total-round-trips-branches)9d\n"
1395 b" round-trips-branches: %(total-round-trips-branches)9d\n"
1395 % data
1396 % data
1396 )
1397 )
1397 if b'total-round-trips-between' in data:
1398 if b'total-round-trips-between' in data:
1398 fm.plain(
1399 fm.plain(
1399 b" round-trips-between: %(total-round-trips-between)9d\n" % data
1400 b" round-trips-between: %(total-round-trips-between)9d\n" % data
1400 )
1401 )
1401 fm.plain(b"queries: %(total-queries)9d\n" % data)
1402 fm.plain(b"queries: %(total-queries)9d\n" % data)
1402 if b'total-queries-branches' in data:
1403 if b'total-queries-branches' in data:
1403 fm.plain(b" queries-branches: %(total-queries-branches)9d\n" % data)
1404 fm.plain(b" queries-branches: %(total-queries-branches)9d\n" % data)
1404 if b'total-queries-between' in data:
1405 if b'total-queries-between' in data:
1405 fm.plain(b" queries-between: %(total-queries-between)9d\n" % data)
1406 fm.plain(b" queries-between: %(total-queries-between)9d\n" % data)
1406 fm.plain(b"heads summary:\n")
1407 fm.plain(b"heads summary:\n")
1407 fm.plain(b" total common heads: %(nb-common-heads)9d\n" % data)
1408 fm.plain(b" total common heads: %(nb-common-heads)9d\n" % data)
1408 fm.plain(b" also local heads: %(nb-common-heads-local)9d\n" % data)
1409 fm.plain(b" also local heads: %(nb-common-heads-local)9d\n" % data)
1409 fm.plain(b" also remote heads: %(nb-common-heads-remote)9d\n" % data)
1410 fm.plain(b" also remote heads: %(nb-common-heads-remote)9d\n" % data)
1410 fm.plain(b" both: %(nb-common-heads-both)9d\n" % data)
1411 fm.plain(b" both: %(nb-common-heads-both)9d\n" % data)
1411 fm.plain(b" local heads: %(nb-head-local)9d\n" % data)
1412 fm.plain(b" local heads: %(nb-head-local)9d\n" % data)
1412 fm.plain(b" common: %(nb-common-heads-local)9d\n" % data)
1413 fm.plain(b" common: %(nb-common-heads-local)9d\n" % data)
1413 fm.plain(b" missing: %(nb-head-local-missing)9d\n" % data)
1414 fm.plain(b" missing: %(nb-head-local-missing)9d\n" % data)
1414 fm.plain(b" remote heads: %(nb-head-remote)9d\n" % data)
1415 fm.plain(b" remote heads: %(nb-head-remote)9d\n" % data)
1415 fm.plain(b" common: %(nb-common-heads-remote)9d\n" % data)
1416 fm.plain(b" common: %(nb-common-heads-remote)9d\n" % data)
1416 fm.plain(b" unknown: %(nb-head-remote-unknown)9d\n" % data)
1417 fm.plain(b" unknown: %(nb-head-remote-unknown)9d\n" % data)
1417 fm.plain(b"local changesets: %(nb-revs)9d\n" % data)
1418 fm.plain(b"local changesets: %(nb-revs)9d\n" % data)
1418 fm.plain(b" common: %(nb-revs-common)9d\n" % data)
1419 fm.plain(b" common: %(nb-revs-common)9d\n" % data)
1419 fm.plain(b" heads: %(nb-common-heads)9d\n" % data)
1420 fm.plain(b" heads: %(nb-common-heads)9d\n" % data)
1420 fm.plain(b" roots: %(nb-common-roots)9d\n" % data)
1421 fm.plain(b" roots: %(nb-common-roots)9d\n" % data)
1421 fm.plain(b" missing: %(nb-revs-missing)9d\n" % data)
1422 fm.plain(b" missing: %(nb-revs-missing)9d\n" % data)
1422 fm.plain(b" heads: %(nb-missing-heads)9d\n" % data)
1423 fm.plain(b" heads: %(nb-missing-heads)9d\n" % data)
1423 fm.plain(b" roots: %(nb-missing-roots)9d\n" % data)
1424 fm.plain(b" roots: %(nb-missing-roots)9d\n" % data)
1424 fm.plain(b" first undecided set: %(nb-ini_und)9d\n" % data)
1425 fm.plain(b" first undecided set: %(nb-ini_und)9d\n" % data)
1425 fm.plain(b" heads: %(nb-ini_und-heads)9d\n" % data)
1426 fm.plain(b" heads: %(nb-ini_und-heads)9d\n" % data)
1426 fm.plain(b" roots: %(nb-ini_und-roots)9d\n" % data)
1427 fm.plain(b" roots: %(nb-ini_und-roots)9d\n" % data)
1427 fm.plain(b" common: %(nb-ini_und-common)9d\n" % data)
1428 fm.plain(b" common: %(nb-ini_und-common)9d\n" % data)
1428 fm.plain(b" missing: %(nb-ini_und-missing)9d\n" % data)
1429 fm.plain(b" missing: %(nb-ini_und-missing)9d\n" % data)
1429
1430
1430 if ui.verbose:
1431 if ui.verbose:
1431 fm.plain(
1432 fm.plain(
1432 b"common heads: %s\n"
1433 b"common heads: %s\n"
1433 % b" ".join(sorted(short(n) for n in heads_common))
1434 % b" ".join(sorted(short(n) for n in heads_common))
1434 )
1435 )
1435 fm.end()
1436 fm.end()
1436
1437
1437
1438
1438 _chunksize = 4 << 10
1439 _chunksize = 4 << 10
1439
1440
1440
1441
1441 @command(
1442 @command(
1442 b'debugdownload',
1443 b'debugdownload',
1443 [
1444 [
1444 (b'o', b'output', b'', _(b'path')),
1445 (b'o', b'output', b'', _(b'path')),
1445 ],
1446 ],
1446 optionalrepo=True,
1447 optionalrepo=True,
1447 )
1448 )
1448 def debugdownload(ui, repo, url, output=None, **opts):
1449 def debugdownload(ui, repo, url, output=None, **opts):
1449 """download a resource using Mercurial logic and config"""
1450 """download a resource using Mercurial logic and config"""
1450 fh = urlmod.open(ui, url, output)
1451 fh = urlmod.open(ui, url, output)
1451
1452
1452 dest = ui
1453 dest = ui
1453 if output:
1454 if output:
1454 dest = open(output, b"wb", _chunksize)
1455 dest = open(output, b"wb", _chunksize)
1455 try:
1456 try:
1456 data = fh.read(_chunksize)
1457 data = fh.read(_chunksize)
1457 while data:
1458 while data:
1458 dest.write(data)
1459 dest.write(data)
1459 data = fh.read(_chunksize)
1460 data = fh.read(_chunksize)
1460 finally:
1461 finally:
1461 if output:
1462 if output:
1462 dest.close()
1463 dest.close()
1463
1464
1464
1465
1465 @command(b'debugextensions', cmdutil.formatteropts, [], optionalrepo=True)
1466 @command(b'debugextensions', cmdutil.formatteropts, [], optionalrepo=True)
1466 def debugextensions(ui, repo, **opts):
1467 def debugextensions(ui, repo, **opts):
1467 '''show information about active extensions'''
1468 '''show information about active extensions'''
1468 opts = pycompat.byteskwargs(opts)
1469 opts = pycompat.byteskwargs(opts)
1469 exts = extensions.extensions(ui)
1470 exts = extensions.extensions(ui)
1470 hgver = util.version()
1471 hgver = util.version()
1471 fm = ui.formatter(b'debugextensions', opts)
1472 fm = ui.formatter(b'debugextensions', opts)
1472 for extname, extmod in sorted(exts, key=operator.itemgetter(0)):
1473 for extname, extmod in sorted(exts, key=operator.itemgetter(0)):
1473 isinternal = extensions.ismoduleinternal(extmod)
1474 isinternal = extensions.ismoduleinternal(extmod)
1474 extsource = None
1475 extsource = None
1475
1476
1476 if util.safehasattr(extmod, '__file__'):
1477 if util.safehasattr(extmod, '__file__'):
1477 extsource = pycompat.fsencode(extmod.__file__)
1478 extsource = pycompat.fsencode(extmod.__file__)
1478 elif getattr(sys, 'oxidized', False):
1479 elif getattr(sys, 'oxidized', False):
1479 extsource = pycompat.sysexecutable
1480 extsource = pycompat.sysexecutable
1480 if isinternal:
1481 if isinternal:
1481 exttestedwith = [] # never expose magic string to users
1482 exttestedwith = [] # never expose magic string to users
1482 else:
1483 else:
1483 exttestedwith = getattr(extmod, 'testedwith', b'').split()
1484 exttestedwith = getattr(extmod, 'testedwith', b'').split()
1484 extbuglink = getattr(extmod, 'buglink', None)
1485 extbuglink = getattr(extmod, 'buglink', None)
1485
1486
1486 fm.startitem()
1487 fm.startitem()
1487
1488
1488 if ui.quiet or ui.verbose:
1489 if ui.quiet or ui.verbose:
1489 fm.write(b'name', b'%s\n', extname)
1490 fm.write(b'name', b'%s\n', extname)
1490 else:
1491 else:
1491 fm.write(b'name', b'%s', extname)
1492 fm.write(b'name', b'%s', extname)
1492 if isinternal or hgver in exttestedwith:
1493 if isinternal or hgver in exttestedwith:
1493 fm.plain(b'\n')
1494 fm.plain(b'\n')
1494 elif not exttestedwith:
1495 elif not exttestedwith:
1495 fm.plain(_(b' (untested!)\n'))
1496 fm.plain(_(b' (untested!)\n'))
1496 else:
1497 else:
1497 lasttestedversion = exttestedwith[-1]
1498 lasttestedversion = exttestedwith[-1]
1498 fm.plain(b' (%s!)\n' % lasttestedversion)
1499 fm.plain(b' (%s!)\n' % lasttestedversion)
1499
1500
1500 fm.condwrite(
1501 fm.condwrite(
1501 ui.verbose and extsource,
1502 ui.verbose and extsource,
1502 b'source',
1503 b'source',
1503 _(b' location: %s\n'),
1504 _(b' location: %s\n'),
1504 extsource or b"",
1505 extsource or b"",
1505 )
1506 )
1506
1507
1507 if ui.verbose:
1508 if ui.verbose:
1508 fm.plain(_(b' bundled: %s\n') % [b'no', b'yes'][isinternal])
1509 fm.plain(_(b' bundled: %s\n') % [b'no', b'yes'][isinternal])
1509 fm.data(bundled=isinternal)
1510 fm.data(bundled=isinternal)
1510
1511
1511 fm.condwrite(
1512 fm.condwrite(
1512 ui.verbose and exttestedwith,
1513 ui.verbose and exttestedwith,
1513 b'testedwith',
1514 b'testedwith',
1514 _(b' tested with: %s\n'),
1515 _(b' tested with: %s\n'),
1515 fm.formatlist(exttestedwith, name=b'ver'),
1516 fm.formatlist(exttestedwith, name=b'ver'),
1516 )
1517 )
1517
1518
1518 fm.condwrite(
1519 fm.condwrite(
1519 ui.verbose and extbuglink,
1520 ui.verbose and extbuglink,
1520 b'buglink',
1521 b'buglink',
1521 _(b' bug reporting: %s\n'),
1522 _(b' bug reporting: %s\n'),
1522 extbuglink or b"",
1523 extbuglink or b"",
1523 )
1524 )
1524
1525
1525 fm.end()
1526 fm.end()
1526
1527
1527
1528
1528 @command(
1529 @command(
1529 b'debugfileset',
1530 b'debugfileset',
1530 [
1531 [
1531 (
1532 (
1532 b'r',
1533 b'r',
1533 b'rev',
1534 b'rev',
1534 b'',
1535 b'',
1535 _(b'apply the filespec on this revision'),
1536 _(b'apply the filespec on this revision'),
1536 _(b'REV'),
1537 _(b'REV'),
1537 ),
1538 ),
1538 (
1539 (
1539 b'',
1540 b'',
1540 b'all-files',
1541 b'all-files',
1541 False,
1542 False,
1542 _(b'test files from all revisions and working directory'),
1543 _(b'test files from all revisions and working directory'),
1543 ),
1544 ),
1544 (
1545 (
1545 b's',
1546 b's',
1546 b'show-matcher',
1547 b'show-matcher',
1547 None,
1548 None,
1548 _(b'print internal representation of matcher'),
1549 _(b'print internal representation of matcher'),
1549 ),
1550 ),
1550 (
1551 (
1551 b'p',
1552 b'p',
1552 b'show-stage',
1553 b'show-stage',
1553 [],
1554 [],
1554 _(b'print parsed tree at the given stage'),
1555 _(b'print parsed tree at the given stage'),
1555 _(b'NAME'),
1556 _(b'NAME'),
1556 ),
1557 ),
1557 ],
1558 ],
1558 _(b'[-r REV] [--all-files] [OPTION]... FILESPEC'),
1559 _(b'[-r REV] [--all-files] [OPTION]... FILESPEC'),
1559 )
1560 )
1560 def debugfileset(ui, repo, expr, **opts):
1561 def debugfileset(ui, repo, expr, **opts):
1561 '''parse and apply a fileset specification'''
1562 '''parse and apply a fileset specification'''
1562 from . import fileset
1563 from . import fileset
1563
1564
1564 fileset.symbols # force import of fileset so we have predicates to optimize
1565 fileset.symbols # force import of fileset so we have predicates to optimize
1565 opts = pycompat.byteskwargs(opts)
1566 opts = pycompat.byteskwargs(opts)
1566 ctx = logcmdutil.revsingle(repo, opts.get(b'rev'), None)
1567 ctx = logcmdutil.revsingle(repo, opts.get(b'rev'), None)
1567
1568
1568 stages = [
1569 stages = [
1569 (b'parsed', pycompat.identity),
1570 (b'parsed', pycompat.identity),
1570 (b'analyzed', filesetlang.analyze),
1571 (b'analyzed', filesetlang.analyze),
1571 (b'optimized', filesetlang.optimize),
1572 (b'optimized', filesetlang.optimize),
1572 ]
1573 ]
1573 stagenames = {n for n, f in stages}
1574 stagenames = {n for n, f in stages}
1574
1575
1575 showalways = set()
1576 showalways = set()
1576 if ui.verbose and not opts[b'show_stage']:
1577 if ui.verbose and not opts[b'show_stage']:
1577 # show parsed tree by --verbose (deprecated)
1578 # show parsed tree by --verbose (deprecated)
1578 showalways.add(b'parsed')
1579 showalways.add(b'parsed')
1579 if opts[b'show_stage'] == [b'all']:
1580 if opts[b'show_stage'] == [b'all']:
1580 showalways.update(stagenames)
1581 showalways.update(stagenames)
1581 else:
1582 else:
1582 for n in opts[b'show_stage']:
1583 for n in opts[b'show_stage']:
1583 if n not in stagenames:
1584 if n not in stagenames:
1584 raise error.Abort(_(b'invalid stage name: %s') % n)
1585 raise error.Abort(_(b'invalid stage name: %s') % n)
1585 showalways.update(opts[b'show_stage'])
1586 showalways.update(opts[b'show_stage'])
1586
1587
1587 tree = filesetlang.parse(expr)
1588 tree = filesetlang.parse(expr)
1588 for n, f in stages:
1589 for n, f in stages:
1589 tree = f(tree)
1590 tree = f(tree)
1590 if n in showalways:
1591 if n in showalways:
1591 if opts[b'show_stage'] or n != b'parsed':
1592 if opts[b'show_stage'] or n != b'parsed':
1592 ui.write(b"* %s:\n" % n)
1593 ui.write(b"* %s:\n" % n)
1593 ui.write(filesetlang.prettyformat(tree), b"\n")
1594 ui.write(filesetlang.prettyformat(tree), b"\n")
1594
1595
1595 files = set()
1596 files = set()
1596 if opts[b'all_files']:
1597 if opts[b'all_files']:
1597 for r in repo:
1598 for r in repo:
1598 c = repo[r]
1599 c = repo[r]
1599 files.update(c.files())
1600 files.update(c.files())
1600 files.update(c.substate)
1601 files.update(c.substate)
1601 if opts[b'all_files'] or ctx.rev() is None:
1602 if opts[b'all_files'] or ctx.rev() is None:
1602 wctx = repo[None]
1603 wctx = repo[None]
1603 files.update(
1604 files.update(
1604 repo.dirstate.walk(
1605 repo.dirstate.walk(
1605 scmutil.matchall(repo),
1606 scmutil.matchall(repo),
1606 subrepos=list(wctx.substate),
1607 subrepos=list(wctx.substate),
1607 unknown=True,
1608 unknown=True,
1608 ignored=True,
1609 ignored=True,
1609 )
1610 )
1610 )
1611 )
1611 files.update(wctx.substate)
1612 files.update(wctx.substate)
1612 else:
1613 else:
1613 files.update(ctx.files())
1614 files.update(ctx.files())
1614 files.update(ctx.substate)
1615 files.update(ctx.substate)
1615
1616
1616 m = ctx.matchfileset(repo.getcwd(), expr)
1617 m = ctx.matchfileset(repo.getcwd(), expr)
1617 if opts[b'show_matcher'] or (opts[b'show_matcher'] is None and ui.verbose):
1618 if opts[b'show_matcher'] or (opts[b'show_matcher'] is None and ui.verbose):
1618 ui.writenoi18n(b'* matcher:\n', stringutil.prettyrepr(m), b'\n')
1619 ui.writenoi18n(b'* matcher:\n', stringutil.prettyrepr(m), b'\n')
1619 for f in sorted(files):
1620 for f in sorted(files):
1620 if not m(f):
1621 if not m(f):
1621 continue
1622 continue
1622 ui.write(b"%s\n" % f)
1623 ui.write(b"%s\n" % f)
1623
1624
1624
1625
1625 @command(
1626 @command(
1626 b"debug-repair-issue6528",
1627 b"debug-repair-issue6528",
1627 [
1628 [
1628 (
1629 (
1629 b'',
1630 b'',
1630 b'to-report',
1631 b'to-report',
1631 b'',
1632 b'',
1632 _(b'build a report of affected revisions to this file'),
1633 _(b'build a report of affected revisions to this file'),
1633 _(b'FILE'),
1634 _(b'FILE'),
1634 ),
1635 ),
1635 (
1636 (
1636 b'',
1637 b'',
1637 b'from-report',
1638 b'from-report',
1638 b'',
1639 b'',
1639 _(b'repair revisions listed in this report file'),
1640 _(b'repair revisions listed in this report file'),
1640 _(b'FILE'),
1641 _(b'FILE'),
1641 ),
1642 ),
1642 (
1643 (
1643 b'',
1644 b'',
1644 b'paranoid',
1645 b'paranoid',
1645 False,
1646 False,
1646 _(b'check that both detection methods do the same thing'),
1647 _(b'check that both detection methods do the same thing'),
1647 ),
1648 ),
1648 ]
1649 ]
1649 + cmdutil.dryrunopts,
1650 + cmdutil.dryrunopts,
1650 )
1651 )
1651 def debug_repair_issue6528(ui, repo, **opts):
1652 def debug_repair_issue6528(ui, repo, **opts):
1652 """find affected revisions and repair them. See issue6528 for more details.
1653 """find affected revisions and repair them. See issue6528 for more details.
1653
1654
1654 The `--to-report` and `--from-report` flags allow you to cache and reuse the
1655 The `--to-report` and `--from-report` flags allow you to cache and reuse the
1655 computation of affected revisions for a given repository across clones.
1656 computation of affected revisions for a given repository across clones.
1656 The report format is line-based (with empty lines ignored):
1657 The report format is line-based (with empty lines ignored):
1657
1658
1658 ```
1659 ```
1659 <ascii-hex of the affected revision>,... <unencoded filelog index filename>
1660 <ascii-hex of the affected revision>,... <unencoded filelog index filename>
1660 ```
1661 ```
1661
1662
1662 There can be multiple broken revisions per filelog, they are separated by
1663 There can be multiple broken revisions per filelog, they are separated by
1663 a comma with no spaces. The only space is between the revision(s) and the
1664 a comma with no spaces. The only space is between the revision(s) and the
1664 filename.
1665 filename.
1665
1666
1666 Note that this does *not* mean that this repairs future affected revisions,
1667 Note that this does *not* mean that this repairs future affected revisions,
1667 that needs a separate fix at the exchange level that was introduced in
1668 that needs a separate fix at the exchange level that was introduced in
1668 Mercurial 5.9.1.
1669 Mercurial 5.9.1.
1669
1670
1670 There is a `--paranoid` flag to test that the fast implementation is correct
1671 There is a `--paranoid` flag to test that the fast implementation is correct
1671 by checking it against the slow implementation. Since this matter is quite
1672 by checking it against the slow implementation. Since this matter is quite
1672 urgent and testing every edge-case is probably quite costly, we use this
1673 urgent and testing every edge-case is probably quite costly, we use this
1673 method to test on large repositories as a fuzzing method of sorts.
1674 method to test on large repositories as a fuzzing method of sorts.
1674 """
1675 """
1675 cmdutil.check_incompatible_arguments(
1676 cmdutil.check_incompatible_arguments(
1676 opts, 'to_report', ['from_report', 'dry_run']
1677 opts, 'to_report', ['from_report', 'dry_run']
1677 )
1678 )
1678 dry_run = opts.get('dry_run')
1679 dry_run = opts.get('dry_run')
1679 to_report = opts.get('to_report')
1680 to_report = opts.get('to_report')
1680 from_report = opts.get('from_report')
1681 from_report = opts.get('from_report')
1681 paranoid = opts.get('paranoid')
1682 paranoid = opts.get('paranoid')
1682 # TODO maybe add filelog pattern and revision pattern parameters to help
1683 # TODO maybe add filelog pattern and revision pattern parameters to help
1683 # narrow down the search for users that know what they're looking for?
1684 # narrow down the search for users that know what they're looking for?
1684
1685
1685 if requirements.REVLOGV1_REQUIREMENT not in repo.requirements:
1686 if requirements.REVLOGV1_REQUIREMENT not in repo.requirements:
1686 msg = b"can only repair revlogv1 repositories, v2 is not affected"
1687 msg = b"can only repair revlogv1 repositories, v2 is not affected"
1687 raise error.Abort(_(msg))
1688 raise error.Abort(_(msg))
1688
1689
1689 rewrite.repair_issue6528(
1690 rewrite.repair_issue6528(
1690 ui,
1691 ui,
1691 repo,
1692 repo,
1692 dry_run=dry_run,
1693 dry_run=dry_run,
1693 to_report=to_report,
1694 to_report=to_report,
1694 from_report=from_report,
1695 from_report=from_report,
1695 paranoid=paranoid,
1696 paranoid=paranoid,
1696 )
1697 )
1697
1698
1698
1699
1699 @command(b'debugformat', [] + cmdutil.formatteropts)
1700 @command(b'debugformat', [] + cmdutil.formatteropts)
1700 def debugformat(ui, repo, **opts):
1701 def debugformat(ui, repo, **opts):
1701 """display format information about the current repository
1702 """display format information about the current repository
1702
1703
1703 Use --verbose to get extra information about current config value and
1704 Use --verbose to get extra information about current config value and
1704 Mercurial default."""
1705 Mercurial default."""
1705 opts = pycompat.byteskwargs(opts)
1706 opts = pycompat.byteskwargs(opts)
1706 maxvariantlength = max(len(fv.name) for fv in upgrade.allformatvariant)
1707 maxvariantlength = max(len(fv.name) for fv in upgrade.allformatvariant)
1707 maxvariantlength = max(len(b'format-variant'), maxvariantlength)
1708 maxvariantlength = max(len(b'format-variant'), maxvariantlength)
1708
1709
1709 def makeformatname(name):
1710 def makeformatname(name):
1710 return b'%s:' + (b' ' * (maxvariantlength - len(name)))
1711 return b'%s:' + (b' ' * (maxvariantlength - len(name)))
1711
1712
1712 fm = ui.formatter(b'debugformat', opts)
1713 fm = ui.formatter(b'debugformat', opts)
1713 if fm.isplain():
1714 if fm.isplain():
1714
1715
1715 def formatvalue(value):
1716 def formatvalue(value):
1716 if util.safehasattr(value, b'startswith'):
1717 if util.safehasattr(value, b'startswith'):
1717 return value
1718 return value
1718 if value:
1719 if value:
1719 return b'yes'
1720 return b'yes'
1720 else:
1721 else:
1721 return b'no'
1722 return b'no'
1722
1723
1723 else:
1724 else:
1724 formatvalue = pycompat.identity
1725 formatvalue = pycompat.identity
1725
1726
1726 fm.plain(b'format-variant')
1727 fm.plain(b'format-variant')
1727 fm.plain(b' ' * (maxvariantlength - len(b'format-variant')))
1728 fm.plain(b' ' * (maxvariantlength - len(b'format-variant')))
1728 fm.plain(b' repo')
1729 fm.plain(b' repo')
1729 if ui.verbose:
1730 if ui.verbose:
1730 fm.plain(b' config default')
1731 fm.plain(b' config default')
1731 fm.plain(b'\n')
1732 fm.plain(b'\n')
1732 for fv in upgrade.allformatvariant:
1733 for fv in upgrade.allformatvariant:
1733 fm.startitem()
1734 fm.startitem()
1734 repovalue = fv.fromrepo(repo)
1735 repovalue = fv.fromrepo(repo)
1735 configvalue = fv.fromconfig(repo)
1736 configvalue = fv.fromconfig(repo)
1736
1737
1737 if repovalue != configvalue:
1738 if repovalue != configvalue:
1738 namelabel = b'formatvariant.name.mismatchconfig'
1739 namelabel = b'formatvariant.name.mismatchconfig'
1739 repolabel = b'formatvariant.repo.mismatchconfig'
1740 repolabel = b'formatvariant.repo.mismatchconfig'
1740 elif repovalue != fv.default:
1741 elif repovalue != fv.default:
1741 namelabel = b'formatvariant.name.mismatchdefault'
1742 namelabel = b'formatvariant.name.mismatchdefault'
1742 repolabel = b'formatvariant.repo.mismatchdefault'
1743 repolabel = b'formatvariant.repo.mismatchdefault'
1743 else:
1744 else:
1744 namelabel = b'formatvariant.name.uptodate'
1745 namelabel = b'formatvariant.name.uptodate'
1745 repolabel = b'formatvariant.repo.uptodate'
1746 repolabel = b'formatvariant.repo.uptodate'
1746
1747
1747 fm.write(b'name', makeformatname(fv.name), fv.name, label=namelabel)
1748 fm.write(b'name', makeformatname(fv.name), fv.name, label=namelabel)
1748 fm.write(b'repo', b' %3s', formatvalue(repovalue), label=repolabel)
1749 fm.write(b'repo', b' %3s', formatvalue(repovalue), label=repolabel)
1749 if fv.default != configvalue:
1750 if fv.default != configvalue:
1750 configlabel = b'formatvariant.config.special'
1751 configlabel = b'formatvariant.config.special'
1751 else:
1752 else:
1752 configlabel = b'formatvariant.config.default'
1753 configlabel = b'formatvariant.config.default'
1753 fm.condwrite(
1754 fm.condwrite(
1754 ui.verbose,
1755 ui.verbose,
1755 b'config',
1756 b'config',
1756 b' %6s',
1757 b' %6s',
1757 formatvalue(configvalue),
1758 formatvalue(configvalue),
1758 label=configlabel,
1759 label=configlabel,
1759 )
1760 )
1760 fm.condwrite(
1761 fm.condwrite(
1761 ui.verbose,
1762 ui.verbose,
1762 b'default',
1763 b'default',
1763 b' %7s',
1764 b' %7s',
1764 formatvalue(fv.default),
1765 formatvalue(fv.default),
1765 label=b'formatvariant.default',
1766 label=b'formatvariant.default',
1766 )
1767 )
1767 fm.plain(b'\n')
1768 fm.plain(b'\n')
1768 fm.end()
1769 fm.end()
1769
1770
1770
1771
1771 @command(b'debugfsinfo', [], _(b'[PATH]'), norepo=True)
1772 @command(b'debugfsinfo', [], _(b'[PATH]'), norepo=True)
1772 def debugfsinfo(ui, path=b"."):
1773 def debugfsinfo(ui, path=b"."):
1773 """show information detected about current filesystem"""
1774 """show information detected about current filesystem"""
1774 ui.writenoi18n(b'path: %s\n' % path)
1775 ui.writenoi18n(b'path: %s\n' % path)
1775 ui.writenoi18n(
1776 ui.writenoi18n(
1776 b'mounted on: %s\n' % (util.getfsmountpoint(path) or b'(unknown)')
1777 b'mounted on: %s\n' % (util.getfsmountpoint(path) or b'(unknown)')
1777 )
1778 )
1778 ui.writenoi18n(b'exec: %s\n' % (util.checkexec(path) and b'yes' or b'no'))
1779 ui.writenoi18n(b'exec: %s\n' % (util.checkexec(path) and b'yes' or b'no'))
1779 ui.writenoi18n(b'fstype: %s\n' % (util.getfstype(path) or b'(unknown)'))
1780 ui.writenoi18n(b'fstype: %s\n' % (util.getfstype(path) or b'(unknown)'))
1780 ui.writenoi18n(
1781 ui.writenoi18n(
1781 b'symlink: %s\n' % (util.checklink(path) and b'yes' or b'no')
1782 b'symlink: %s\n' % (util.checklink(path) and b'yes' or b'no')
1782 )
1783 )
1783 ui.writenoi18n(
1784 ui.writenoi18n(
1784 b'hardlink: %s\n' % (util.checknlink(path) and b'yes' or b'no')
1785 b'hardlink: %s\n' % (util.checknlink(path) and b'yes' or b'no')
1785 )
1786 )
1786 casesensitive = b'(unknown)'
1787 casesensitive = b'(unknown)'
1787 try:
1788 try:
1788 with pycompat.namedtempfile(prefix=b'.debugfsinfo', dir=path) as f:
1789 with pycompat.namedtempfile(prefix=b'.debugfsinfo', dir=path) as f:
1789 casesensitive = util.fscasesensitive(f.name) and b'yes' or b'no'
1790 casesensitive = util.fscasesensitive(f.name) and b'yes' or b'no'
1790 except OSError:
1791 except OSError:
1791 pass
1792 pass
1792 ui.writenoi18n(b'case-sensitive: %s\n' % casesensitive)
1793 ui.writenoi18n(b'case-sensitive: %s\n' % casesensitive)
1793
1794
1794
1795
1795 @command(
1796 @command(
1796 b'debuggetbundle',
1797 b'debuggetbundle',
1797 [
1798 [
1798 (b'H', b'head', [], _(b'id of head node'), _(b'ID')),
1799 (b'H', b'head', [], _(b'id of head node'), _(b'ID')),
1799 (b'C', b'common', [], _(b'id of common node'), _(b'ID')),
1800 (b'C', b'common', [], _(b'id of common node'), _(b'ID')),
1800 (
1801 (
1801 b't',
1802 b't',
1802 b'type',
1803 b'type',
1803 b'bzip2',
1804 b'bzip2',
1804 _(b'bundle compression type to use'),
1805 _(b'bundle compression type to use'),
1805 _(b'TYPE'),
1806 _(b'TYPE'),
1806 ),
1807 ),
1807 ],
1808 ],
1808 _(b'REPO FILE [-H|-C ID]...'),
1809 _(b'REPO FILE [-H|-C ID]...'),
1809 norepo=True,
1810 norepo=True,
1810 )
1811 )
1811 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1812 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1812 """retrieves a bundle from a repo
1813 """retrieves a bundle from a repo
1813
1814
1814 Every ID must be a full-length hex node id string. Saves the bundle to the
1815 Every ID must be a full-length hex node id string. Saves the bundle to the
1815 given file.
1816 given file.
1816 """
1817 """
1817 opts = pycompat.byteskwargs(opts)
1818 opts = pycompat.byteskwargs(opts)
1818 repo = hg.peer(ui, opts, repopath)
1819 repo = hg.peer(ui, opts, repopath)
1819 if not repo.capable(b'getbundle'):
1820 if not repo.capable(b'getbundle'):
1820 raise error.Abort(b"getbundle() not supported by target repository")
1821 raise error.Abort(b"getbundle() not supported by target repository")
1821 args = {}
1822 args = {}
1822 if common:
1823 if common:
1823 args['common'] = [bin(s) for s in common]
1824 args['common'] = [bin(s) for s in common]
1824 if head:
1825 if head:
1825 args['heads'] = [bin(s) for s in head]
1826 args['heads'] = [bin(s) for s in head]
1826 # TODO: get desired bundlecaps from command line.
1827 # TODO: get desired bundlecaps from command line.
1827 args['bundlecaps'] = None
1828 args['bundlecaps'] = None
1828 bundle = repo.getbundle(b'debug', **args)
1829 bundle = repo.getbundle(b'debug', **args)
1829
1830
1830 bundletype = opts.get(b'type', b'bzip2').lower()
1831 bundletype = opts.get(b'type', b'bzip2').lower()
1831 btypes = {
1832 btypes = {
1832 b'none': b'HG10UN',
1833 b'none': b'HG10UN',
1833 b'bzip2': b'HG10BZ',
1834 b'bzip2': b'HG10BZ',
1834 b'gzip': b'HG10GZ',
1835 b'gzip': b'HG10GZ',
1835 b'bundle2': b'HG20',
1836 b'bundle2': b'HG20',
1836 }
1837 }
1837 bundletype = btypes.get(bundletype)
1838 bundletype = btypes.get(bundletype)
1838 if bundletype not in bundle2.bundletypes:
1839 if bundletype not in bundle2.bundletypes:
1839 raise error.Abort(_(b'unknown bundle type specified with --type'))
1840 raise error.Abort(_(b'unknown bundle type specified with --type'))
1840 bundle2.writebundle(ui, bundle, bundlepath, bundletype)
1841 bundle2.writebundle(ui, bundle, bundlepath, bundletype)
1841
1842
1842
1843
1843 @command(b'debugignore', [], b'[FILE]')
1844 @command(b'debugignore', [], b'[FILE]')
1844 def debugignore(ui, repo, *files, **opts):
1845 def debugignore(ui, repo, *files, **opts):
1845 """display the combined ignore pattern and information about ignored files
1846 """display the combined ignore pattern and information about ignored files
1846
1847
1847 With no argument display the combined ignore pattern.
1848 With no argument display the combined ignore pattern.
1848
1849
1849 Given space separated file names, shows if the given file is ignored and
1850 Given space separated file names, shows if the given file is ignored and
1850 if so, show the ignore rule (file and line number) that matched it.
1851 if so, show the ignore rule (file and line number) that matched it.
1851 """
1852 """
1852 ignore = repo.dirstate._ignore
1853 ignore = repo.dirstate._ignore
1853 if not files:
1854 if not files:
1854 # Show all the patterns
1855 # Show all the patterns
1855 ui.write(b"%s\n" % pycompat.byterepr(ignore))
1856 ui.write(b"%s\n" % pycompat.byterepr(ignore))
1856 else:
1857 else:
1857 m = scmutil.match(repo[None], pats=files)
1858 m = scmutil.match(repo[None], pats=files)
1858 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
1859 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
1859 for f in m.files():
1860 for f in m.files():
1860 nf = util.normpath(f)
1861 nf = util.normpath(f)
1861 ignored = None
1862 ignored = None
1862 ignoredata = None
1863 ignoredata = None
1863 if nf != b'.':
1864 if nf != b'.':
1864 if ignore(nf):
1865 if ignore(nf):
1865 ignored = nf
1866 ignored = nf
1866 ignoredata = repo.dirstate._ignorefileandline(nf)
1867 ignoredata = repo.dirstate._ignorefileandline(nf)
1867 else:
1868 else:
1868 for p in pathutil.finddirs(nf):
1869 for p in pathutil.finddirs(nf):
1869 if ignore(p):
1870 if ignore(p):
1870 ignored = p
1871 ignored = p
1871 ignoredata = repo.dirstate._ignorefileandline(p)
1872 ignoredata = repo.dirstate._ignorefileandline(p)
1872 break
1873 break
1873 if ignored:
1874 if ignored:
1874 if ignored == nf:
1875 if ignored == nf:
1875 ui.write(_(b"%s is ignored\n") % uipathfn(f))
1876 ui.write(_(b"%s is ignored\n") % uipathfn(f))
1876 else:
1877 else:
1877 ui.write(
1878 ui.write(
1878 _(
1879 _(
1879 b"%s is ignored because of "
1880 b"%s is ignored because of "
1880 b"containing directory %s\n"
1881 b"containing directory %s\n"
1881 )
1882 )
1882 % (uipathfn(f), ignored)
1883 % (uipathfn(f), ignored)
1883 )
1884 )
1884 ignorefile, lineno, line = ignoredata
1885 ignorefile, lineno, line = ignoredata
1885 ui.write(
1886 ui.write(
1886 _(b"(ignore rule in %s, line %d: '%s')\n")
1887 _(b"(ignore rule in %s, line %d: '%s')\n")
1887 % (ignorefile, lineno, line)
1888 % (ignorefile, lineno, line)
1888 )
1889 )
1889 else:
1890 else:
1890 ui.write(_(b"%s is not ignored\n") % uipathfn(f))
1891 ui.write(_(b"%s is not ignored\n") % uipathfn(f))
1891
1892
1892
1893
1893 @command(
1894 @command(
1894 b'debug-revlog-index|debugindex',
1895 b'debug-revlog-index|debugindex',
1895 cmdutil.debugrevlogopts + cmdutil.formatteropts,
1896 cmdutil.debugrevlogopts + cmdutil.formatteropts,
1896 _(b'-c|-m|FILE'),
1897 _(b'-c|-m|FILE'),
1897 )
1898 )
1898 def debugindex(ui, repo, file_=None, **opts):
1899 def debugindex(ui, repo, file_=None, **opts):
1899 """dump index data for a revlog"""
1900 """dump index data for a revlog"""
1900 opts = pycompat.byteskwargs(opts)
1901 opts = pycompat.byteskwargs(opts)
1901 store = cmdutil.openstorage(repo, b'debugindex', file_, opts)
1902 store = cmdutil.openstorage(repo, b'debugindex', file_, opts)
1902
1903
1903 fm = ui.formatter(b'debugindex', opts)
1904 fm = ui.formatter(b'debugindex', opts)
1904
1905
1905 revlog = getattr(store, b'_revlog', store)
1906 revlog = getattr(store, b'_revlog', store)
1906
1907
1907 return revlog_debug.debug_index(
1908 return revlog_debug.debug_index(
1908 ui,
1909 ui,
1909 repo,
1910 repo,
1910 formatter=fm,
1911 formatter=fm,
1911 revlog=revlog,
1912 revlog=revlog,
1912 full_node=ui.debugflag,
1913 full_node=ui.debugflag,
1913 )
1914 )
1914
1915
1915
1916
1916 @command(
1917 @command(
1917 b'debugindexdot',
1918 b'debugindexdot',
1918 cmdutil.debugrevlogopts,
1919 cmdutil.debugrevlogopts,
1919 _(b'-c|-m|FILE'),
1920 _(b'-c|-m|FILE'),
1920 optionalrepo=True,
1921 optionalrepo=True,
1921 )
1922 )
1922 def debugindexdot(ui, repo, file_=None, **opts):
1923 def debugindexdot(ui, repo, file_=None, **opts):
1923 """dump an index DAG as a graphviz dot file"""
1924 """dump an index DAG as a graphviz dot file"""
1924 opts = pycompat.byteskwargs(opts)
1925 opts = pycompat.byteskwargs(opts)
1925 r = cmdutil.openstorage(repo, b'debugindexdot', file_, opts)
1926 r = cmdutil.openstorage(repo, b'debugindexdot', file_, opts)
1926 ui.writenoi18n(b"digraph G {\n")
1927 ui.writenoi18n(b"digraph G {\n")
1927 for i in r:
1928 for i in r:
1928 node = r.node(i)
1929 node = r.node(i)
1929 pp = r.parents(node)
1930 pp = r.parents(node)
1930 ui.write(b"\t%d -> %d\n" % (r.rev(pp[0]), i))
1931 ui.write(b"\t%d -> %d\n" % (r.rev(pp[0]), i))
1931 if pp[1] != repo.nullid:
1932 if pp[1] != repo.nullid:
1932 ui.write(b"\t%d -> %d\n" % (r.rev(pp[1]), i))
1933 ui.write(b"\t%d -> %d\n" % (r.rev(pp[1]), i))
1933 ui.write(b"}\n")
1934 ui.write(b"}\n")
1934
1935
1935
1936
1936 @command(b'debugindexstats', [])
1937 @command(b'debugindexstats', [])
1937 def debugindexstats(ui, repo):
1938 def debugindexstats(ui, repo):
1938 """show stats related to the changelog index"""
1939 """show stats related to the changelog index"""
1939 repo.changelog.shortest(repo.nullid, 1)
1940 repo.changelog.shortest(repo.nullid, 1)
1940 index = repo.changelog.index
1941 index = repo.changelog.index
1941 if not util.safehasattr(index, b'stats'):
1942 if not util.safehasattr(index, b'stats'):
1942 raise error.Abort(_(b'debugindexstats only works with native code'))
1943 raise error.Abort(_(b'debugindexstats only works with native code'))
1943 for k, v in sorted(index.stats().items()):
1944 for k, v in sorted(index.stats().items()):
1944 ui.write(b'%s: %d\n' % (k, v))
1945 ui.write(b'%s: %d\n' % (k, v))
1945
1946
1946
1947
1947 @command(b'debuginstall', [] + cmdutil.formatteropts, b'', norepo=True)
1948 @command(b'debuginstall', [] + cmdutil.formatteropts, b'', norepo=True)
1948 def debuginstall(ui, **opts):
1949 def debuginstall(ui, **opts):
1949 """test Mercurial installation
1950 """test Mercurial installation
1950
1951
1951 Returns 0 on success.
1952 Returns 0 on success.
1952 """
1953 """
1953 opts = pycompat.byteskwargs(opts)
1954 opts = pycompat.byteskwargs(opts)
1954
1955
1955 problems = 0
1956 problems = 0
1956
1957
1957 fm = ui.formatter(b'debuginstall', opts)
1958 fm = ui.formatter(b'debuginstall', opts)
1958 fm.startitem()
1959 fm.startitem()
1959
1960
1960 # encoding might be unknown or wrong. don't translate these messages.
1961 # encoding might be unknown or wrong. don't translate these messages.
1961 fm.write(b'encoding', b"checking encoding (%s)...\n", encoding.encoding)
1962 fm.write(b'encoding', b"checking encoding (%s)...\n", encoding.encoding)
1962 err = None
1963 err = None
1963 try:
1964 try:
1964 codecs.lookup(pycompat.sysstr(encoding.encoding))
1965 codecs.lookup(pycompat.sysstr(encoding.encoding))
1965 except LookupError as inst:
1966 except LookupError as inst:
1966 err = stringutil.forcebytestr(inst)
1967 err = stringutil.forcebytestr(inst)
1967 problems += 1
1968 problems += 1
1968 fm.condwrite(
1969 fm.condwrite(
1969 err,
1970 err,
1970 b'encodingerror',
1971 b'encodingerror',
1971 b" %s\n (check that your locale is properly set)\n",
1972 b" %s\n (check that your locale is properly set)\n",
1972 err,
1973 err,
1973 )
1974 )
1974
1975
1975 # Python
1976 # Python
1976 pythonlib = None
1977 pythonlib = None
1977 if util.safehasattr(os, '__file__'):
1978 if util.safehasattr(os, '__file__'):
1978 pythonlib = os.path.dirname(pycompat.fsencode(os.__file__))
1979 pythonlib = os.path.dirname(pycompat.fsencode(os.__file__))
1979 elif getattr(sys, 'oxidized', False):
1980 elif getattr(sys, 'oxidized', False):
1980 pythonlib = pycompat.sysexecutable
1981 pythonlib = pycompat.sysexecutable
1981
1982
1982 fm.write(
1983 fm.write(
1983 b'pythonexe',
1984 b'pythonexe',
1984 _(b"checking Python executable (%s)\n"),
1985 _(b"checking Python executable (%s)\n"),
1985 pycompat.sysexecutable or _(b"unknown"),
1986 pycompat.sysexecutable or _(b"unknown"),
1986 )
1987 )
1987 fm.write(
1988 fm.write(
1988 b'pythonimplementation',
1989 b'pythonimplementation',
1989 _(b"checking Python implementation (%s)\n"),
1990 _(b"checking Python implementation (%s)\n"),
1990 pycompat.sysbytes(platform.python_implementation()),
1991 pycompat.sysbytes(platform.python_implementation()),
1991 )
1992 )
1992 fm.write(
1993 fm.write(
1993 b'pythonver',
1994 b'pythonver',
1994 _(b"checking Python version (%s)\n"),
1995 _(b"checking Python version (%s)\n"),
1995 (b"%d.%d.%d" % sys.version_info[:3]),
1996 (b"%d.%d.%d" % sys.version_info[:3]),
1996 )
1997 )
1997 fm.write(
1998 fm.write(
1998 b'pythonlib',
1999 b'pythonlib',
1999 _(b"checking Python lib (%s)...\n"),
2000 _(b"checking Python lib (%s)...\n"),
2000 pythonlib or _(b"unknown"),
2001 pythonlib or _(b"unknown"),
2001 )
2002 )
2002
2003
2003 try:
2004 try:
2004 from . import rustext # pytype: disable=import-error
2005 from . import rustext # pytype: disable=import-error
2005
2006
2006 rustext.__doc__ # trigger lazy import
2007 rustext.__doc__ # trigger lazy import
2007 except ImportError:
2008 except ImportError:
2008 rustext = None
2009 rustext = None
2009
2010
2010 security = set(sslutil.supportedprotocols)
2011 security = set(sslutil.supportedprotocols)
2011 if sslutil.hassni:
2012 if sslutil.hassni:
2012 security.add(b'sni')
2013 security.add(b'sni')
2013
2014
2014 fm.write(
2015 fm.write(
2015 b'pythonsecurity',
2016 b'pythonsecurity',
2016 _(b"checking Python security support (%s)\n"),
2017 _(b"checking Python security support (%s)\n"),
2017 fm.formatlist(sorted(security), name=b'protocol', fmt=b'%s', sep=b','),
2018 fm.formatlist(sorted(security), name=b'protocol', fmt=b'%s', sep=b','),
2018 )
2019 )
2019
2020
2020 # These are warnings, not errors. So don't increment problem count. This
2021 # These are warnings, not errors. So don't increment problem count. This
2021 # may change in the future.
2022 # may change in the future.
2022 if b'tls1.2' not in security:
2023 if b'tls1.2' not in security:
2023 fm.plain(
2024 fm.plain(
2024 _(
2025 _(
2025 b' TLS 1.2 not supported by Python install; '
2026 b' TLS 1.2 not supported by Python install; '
2026 b'network connections lack modern security\n'
2027 b'network connections lack modern security\n'
2027 )
2028 )
2028 )
2029 )
2029 if b'sni' not in security:
2030 if b'sni' not in security:
2030 fm.plain(
2031 fm.plain(
2031 _(
2032 _(
2032 b' SNI not supported by Python install; may have '
2033 b' SNI not supported by Python install; may have '
2033 b'connectivity issues with some servers\n'
2034 b'connectivity issues with some servers\n'
2034 )
2035 )
2035 )
2036 )
2036
2037
2037 fm.plain(
2038 fm.plain(
2038 _(
2039 _(
2039 b"checking Rust extensions (%s)\n"
2040 b"checking Rust extensions (%s)\n"
2040 % (b'missing' if rustext is None else b'installed')
2041 % (b'missing' if rustext is None else b'installed')
2041 ),
2042 ),
2042 )
2043 )
2043
2044
2044 # TODO print CA cert info
2045 # TODO print CA cert info
2045
2046
2046 # hg version
2047 # hg version
2047 hgver = util.version()
2048 hgver = util.version()
2048 fm.write(
2049 fm.write(
2049 b'hgver', _(b"checking Mercurial version (%s)\n"), hgver.split(b'+')[0]
2050 b'hgver', _(b"checking Mercurial version (%s)\n"), hgver.split(b'+')[0]
2050 )
2051 )
2051 fm.write(
2052 fm.write(
2052 b'hgverextra',
2053 b'hgverextra',
2053 _(b"checking Mercurial custom build (%s)\n"),
2054 _(b"checking Mercurial custom build (%s)\n"),
2054 b'+'.join(hgver.split(b'+')[1:]),
2055 b'+'.join(hgver.split(b'+')[1:]),
2055 )
2056 )
2056
2057
2057 # compiled modules
2058 # compiled modules
2058 hgmodules = None
2059 hgmodules = None
2059 if util.safehasattr(sys.modules[__name__], '__file__'):
2060 if util.safehasattr(sys.modules[__name__], '__file__'):
2060 hgmodules = os.path.dirname(pycompat.fsencode(__file__))
2061 hgmodules = os.path.dirname(pycompat.fsencode(__file__))
2061 elif getattr(sys, 'oxidized', False):
2062 elif getattr(sys, 'oxidized', False):
2062 hgmodules = pycompat.sysexecutable
2063 hgmodules = pycompat.sysexecutable
2063
2064
2064 fm.write(
2065 fm.write(
2065 b'hgmodulepolicy', _(b"checking module policy (%s)\n"), policy.policy
2066 b'hgmodulepolicy', _(b"checking module policy (%s)\n"), policy.policy
2066 )
2067 )
2067 fm.write(
2068 fm.write(
2068 b'hgmodules',
2069 b'hgmodules',
2069 _(b"checking installed modules (%s)...\n"),
2070 _(b"checking installed modules (%s)...\n"),
2070 hgmodules or _(b"unknown"),
2071 hgmodules or _(b"unknown"),
2071 )
2072 )
2072
2073
2073 rustandc = policy.policy in (b'rust+c', b'rust+c-allow')
2074 rustandc = policy.policy in (b'rust+c', b'rust+c-allow')
2074 rustext = rustandc # for now, that's the only case
2075 rustext = rustandc # for now, that's the only case
2075 cext = policy.policy in (b'c', b'allow') or rustandc
2076 cext = policy.policy in (b'c', b'allow') or rustandc
2076 nopure = cext or rustext
2077 nopure = cext or rustext
2077 if nopure:
2078 if nopure:
2078 err = None
2079 err = None
2079 try:
2080 try:
2080 if cext:
2081 if cext:
2081 from .cext import ( # pytype: disable=import-error
2082 from .cext import ( # pytype: disable=import-error
2082 base85,
2083 base85,
2083 bdiff,
2084 bdiff,
2084 mpatch,
2085 mpatch,
2085 osutil,
2086 osutil,
2086 )
2087 )
2087
2088
2088 # quiet pyflakes
2089 # quiet pyflakes
2089 dir(bdiff), dir(mpatch), dir(base85), dir(osutil)
2090 dir(bdiff), dir(mpatch), dir(base85), dir(osutil)
2090 if rustext:
2091 if rustext:
2091 from .rustext import ( # pytype: disable=import-error
2092 from .rustext import ( # pytype: disable=import-error
2092 ancestor,
2093 ancestor,
2093 dirstate,
2094 dirstate,
2094 )
2095 )
2095
2096
2096 dir(ancestor), dir(dirstate) # quiet pyflakes
2097 dir(ancestor), dir(dirstate) # quiet pyflakes
2097 except Exception as inst:
2098 except Exception as inst:
2098 err = stringutil.forcebytestr(inst)
2099 err = stringutil.forcebytestr(inst)
2099 problems += 1
2100 problems += 1
2100 fm.condwrite(err, b'extensionserror', b" %s\n", err)
2101 fm.condwrite(err, b'extensionserror', b" %s\n", err)
2101
2102
2102 compengines = util.compengines._engines.values()
2103 compengines = util.compengines._engines.values()
2103 fm.write(
2104 fm.write(
2104 b'compengines',
2105 b'compengines',
2105 _(b'checking registered compression engines (%s)\n'),
2106 _(b'checking registered compression engines (%s)\n'),
2106 fm.formatlist(
2107 fm.formatlist(
2107 sorted(e.name() for e in compengines),
2108 sorted(e.name() for e in compengines),
2108 name=b'compengine',
2109 name=b'compengine',
2109 fmt=b'%s',
2110 fmt=b'%s',
2110 sep=b', ',
2111 sep=b', ',
2111 ),
2112 ),
2112 )
2113 )
2113 fm.write(
2114 fm.write(
2114 b'compenginesavail',
2115 b'compenginesavail',
2115 _(b'checking available compression engines (%s)\n'),
2116 _(b'checking available compression engines (%s)\n'),
2116 fm.formatlist(
2117 fm.formatlist(
2117 sorted(e.name() for e in compengines if e.available()),
2118 sorted(e.name() for e in compengines if e.available()),
2118 name=b'compengine',
2119 name=b'compengine',
2119 fmt=b'%s',
2120 fmt=b'%s',
2120 sep=b', ',
2121 sep=b', ',
2121 ),
2122 ),
2122 )
2123 )
2123 wirecompengines = compression.compengines.supportedwireengines(
2124 wirecompengines = compression.compengines.supportedwireengines(
2124 compression.SERVERROLE
2125 compression.SERVERROLE
2125 )
2126 )
2126 fm.write(
2127 fm.write(
2127 b'compenginesserver',
2128 b'compenginesserver',
2128 _(
2129 _(
2129 b'checking available compression engines '
2130 b'checking available compression engines '
2130 b'for wire protocol (%s)\n'
2131 b'for wire protocol (%s)\n'
2131 ),
2132 ),
2132 fm.formatlist(
2133 fm.formatlist(
2133 [e.name() for e in wirecompengines if e.wireprotosupport()],
2134 [e.name() for e in wirecompengines if e.wireprotosupport()],
2134 name=b'compengine',
2135 name=b'compengine',
2135 fmt=b'%s',
2136 fmt=b'%s',
2136 sep=b', ',
2137 sep=b', ',
2137 ),
2138 ),
2138 )
2139 )
2139 re2 = b'missing'
2140 re2 = b'missing'
2140 if util._re2:
2141 if util._re2:
2141 re2 = b'available'
2142 re2 = b'available'
2142 fm.plain(_(b'checking "re2" regexp engine (%s)\n') % re2)
2143 fm.plain(_(b'checking "re2" regexp engine (%s)\n') % re2)
2143 fm.data(re2=bool(util._re2))
2144 fm.data(re2=bool(util._re2))
2144
2145
2145 # templates
2146 # templates
2146 p = templater.templatedir()
2147 p = templater.templatedir()
2147 fm.write(b'templatedirs', b'checking templates (%s)...\n', p or b'')
2148 fm.write(b'templatedirs', b'checking templates (%s)...\n', p or b'')
2148 fm.condwrite(not p, b'', _(b" no template directories found\n"))
2149 fm.condwrite(not p, b'', _(b" no template directories found\n"))
2149 if p:
2150 if p:
2150 (m, fp) = templater.try_open_template(b"map-cmdline.default")
2151 (m, fp) = templater.try_open_template(b"map-cmdline.default")
2151 if m:
2152 if m:
2152 # template found, check if it is working
2153 # template found, check if it is working
2153 err = None
2154 err = None
2154 try:
2155 try:
2155 templater.templater.frommapfile(m)
2156 templater.templater.frommapfile(m)
2156 except Exception as inst:
2157 except Exception as inst:
2157 err = stringutil.forcebytestr(inst)
2158 err = stringutil.forcebytestr(inst)
2158 p = None
2159 p = None
2159 fm.condwrite(err, b'defaulttemplateerror', b" %s\n", err)
2160 fm.condwrite(err, b'defaulttemplateerror', b" %s\n", err)
2160 else:
2161 else:
2161 p = None
2162 p = None
2162 fm.condwrite(
2163 fm.condwrite(
2163 p, b'defaulttemplate', _(b"checking default template (%s)\n"), m
2164 p, b'defaulttemplate', _(b"checking default template (%s)\n"), m
2164 )
2165 )
2165 fm.condwrite(
2166 fm.condwrite(
2166 not m,
2167 not m,
2167 b'defaulttemplatenotfound',
2168 b'defaulttemplatenotfound',
2168 _(b" template '%s' not found\n"),
2169 _(b" template '%s' not found\n"),
2169 b"default",
2170 b"default",
2170 )
2171 )
2171 if not p:
2172 if not p:
2172 problems += 1
2173 problems += 1
2173 fm.condwrite(
2174 fm.condwrite(
2174 not p, b'', _(b" (templates seem to have been installed incorrectly)\n")
2175 not p, b'', _(b" (templates seem to have been installed incorrectly)\n")
2175 )
2176 )
2176
2177
2177 # editor
2178 # editor
2178 editor = ui.geteditor()
2179 editor = ui.geteditor()
2179 editor = util.expandpath(editor)
2180 editor = util.expandpath(editor)
2180 editorbin = procutil.shellsplit(editor)[0]
2181 editorbin = procutil.shellsplit(editor)[0]
2181 fm.write(b'editor', _(b"checking commit editor... (%s)\n"), editorbin)
2182 fm.write(b'editor', _(b"checking commit editor... (%s)\n"), editorbin)
2182 cmdpath = procutil.findexe(editorbin)
2183 cmdpath = procutil.findexe(editorbin)
2183 fm.condwrite(
2184 fm.condwrite(
2184 not cmdpath and editor == b'vi',
2185 not cmdpath and editor == b'vi',
2185 b'vinotfound',
2186 b'vinotfound',
2186 _(
2187 _(
2187 b" No commit editor set and can't find %s in PATH\n"
2188 b" No commit editor set and can't find %s in PATH\n"
2188 b" (specify a commit editor in your configuration"
2189 b" (specify a commit editor in your configuration"
2189 b" file)\n"
2190 b" file)\n"
2190 ),
2191 ),
2191 not cmdpath and editor == b'vi' and editorbin,
2192 not cmdpath and editor == b'vi' and editorbin,
2192 )
2193 )
2193 fm.condwrite(
2194 fm.condwrite(
2194 not cmdpath and editor != b'vi',
2195 not cmdpath and editor != b'vi',
2195 b'editornotfound',
2196 b'editornotfound',
2196 _(
2197 _(
2197 b" Can't find editor '%s' in PATH\n"
2198 b" Can't find editor '%s' in PATH\n"
2198 b" (specify a commit editor in your configuration"
2199 b" (specify a commit editor in your configuration"
2199 b" file)\n"
2200 b" file)\n"
2200 ),
2201 ),
2201 not cmdpath and editorbin,
2202 not cmdpath and editorbin,
2202 )
2203 )
2203 if not cmdpath and editor != b'vi':
2204 if not cmdpath and editor != b'vi':
2204 problems += 1
2205 problems += 1
2205
2206
2206 # check username
2207 # check username
2207 username = None
2208 username = None
2208 err = None
2209 err = None
2209 try:
2210 try:
2210 username = ui.username()
2211 username = ui.username()
2211 except error.Abort as e:
2212 except error.Abort as e:
2212 err = e.message
2213 err = e.message
2213 problems += 1
2214 problems += 1
2214
2215
2215 fm.condwrite(
2216 fm.condwrite(
2216 username, b'username', _(b"checking username (%s)\n"), username
2217 username, b'username', _(b"checking username (%s)\n"), username
2217 )
2218 )
2218 fm.condwrite(
2219 fm.condwrite(
2219 err,
2220 err,
2220 b'usernameerror',
2221 b'usernameerror',
2221 _(
2222 _(
2222 b"checking username...\n %s\n"
2223 b"checking username...\n %s\n"
2223 b" (specify a username in your configuration file)\n"
2224 b" (specify a username in your configuration file)\n"
2224 ),
2225 ),
2225 err,
2226 err,
2226 )
2227 )
2227
2228
2228 for name, mod in extensions.extensions():
2229 for name, mod in extensions.extensions():
2229 handler = getattr(mod, 'debuginstall', None)
2230 handler = getattr(mod, 'debuginstall', None)
2230 if handler is not None:
2231 if handler is not None:
2231 problems += handler(ui, fm)
2232 problems += handler(ui, fm)
2232
2233
2233 fm.condwrite(not problems, b'', _(b"no problems detected\n"))
2234 fm.condwrite(not problems, b'', _(b"no problems detected\n"))
2234 if not problems:
2235 if not problems:
2235 fm.data(problems=problems)
2236 fm.data(problems=problems)
2236 fm.condwrite(
2237 fm.condwrite(
2237 problems,
2238 problems,
2238 b'problems',
2239 b'problems',
2239 _(b"%d problems detected, please check your install!\n"),
2240 _(b"%d problems detected, please check your install!\n"),
2240 problems,
2241 problems,
2241 )
2242 )
2242 fm.end()
2243 fm.end()
2243
2244
2244 return problems
2245 return problems
2245
2246
2246
2247
2247 @command(b'debugknown', [], _(b'REPO ID...'), norepo=True)
2248 @command(b'debugknown', [], _(b'REPO ID...'), norepo=True)
2248 def debugknown(ui, repopath, *ids, **opts):
2249 def debugknown(ui, repopath, *ids, **opts):
2249 """test whether node ids are known to a repo
2250 """test whether node ids are known to a repo
2250
2251
2251 Every ID must be a full-length hex node id string. Returns a list of 0s
2252 Every ID must be a full-length hex node id string. Returns a list of 0s
2252 and 1s indicating unknown/known.
2253 and 1s indicating unknown/known.
2253 """
2254 """
2254 opts = pycompat.byteskwargs(opts)
2255 opts = pycompat.byteskwargs(opts)
2255 repo = hg.peer(ui, opts, repopath)
2256 repo = hg.peer(ui, opts, repopath)
2256 if not repo.capable(b'known'):
2257 if not repo.capable(b'known'):
2257 raise error.Abort(b"known() not supported by target repository")
2258 raise error.Abort(b"known() not supported by target repository")
2258 flags = repo.known([bin(s) for s in ids])
2259 flags = repo.known([bin(s) for s in ids])
2259 ui.write(b"%s\n" % (b"".join([f and b"1" or b"0" for f in flags])))
2260 ui.write(b"%s\n" % (b"".join([f and b"1" or b"0" for f in flags])))
2260
2261
2261
2262
2262 @command(b'debuglabelcomplete', [], _(b'LABEL...'))
2263 @command(b'debuglabelcomplete', [], _(b'LABEL...'))
2263 def debuglabelcomplete(ui, repo, *args):
2264 def debuglabelcomplete(ui, repo, *args):
2264 '''backwards compatibility with old bash completion scripts (DEPRECATED)'''
2265 '''backwards compatibility with old bash completion scripts (DEPRECATED)'''
2265 debugnamecomplete(ui, repo, *args)
2266 debugnamecomplete(ui, repo, *args)
2266
2267
2267
2268
2268 @command(
2269 @command(
2269 b'debuglocks',
2270 b'debuglocks',
2270 [
2271 [
2271 (b'L', b'force-free-lock', None, _(b'free the store lock (DANGEROUS)')),
2272 (b'L', b'force-free-lock', None, _(b'free the store lock (DANGEROUS)')),
2272 (
2273 (
2273 b'W',
2274 b'W',
2274 b'force-free-wlock',
2275 b'force-free-wlock',
2275 None,
2276 None,
2276 _(b'free the working state lock (DANGEROUS)'),
2277 _(b'free the working state lock (DANGEROUS)'),
2277 ),
2278 ),
2278 (b's', b'set-lock', None, _(b'set the store lock until stopped')),
2279 (b's', b'set-lock', None, _(b'set the store lock until stopped')),
2279 (
2280 (
2280 b'S',
2281 b'S',
2281 b'set-wlock',
2282 b'set-wlock',
2282 None,
2283 None,
2283 _(b'set the working state lock until stopped'),
2284 _(b'set the working state lock until stopped'),
2284 ),
2285 ),
2285 ],
2286 ],
2286 _(b'[OPTION]...'),
2287 _(b'[OPTION]...'),
2287 )
2288 )
2288 def debuglocks(ui, repo, **opts):
2289 def debuglocks(ui, repo, **opts):
2289 """show or modify state of locks
2290 """show or modify state of locks
2290
2291
2291 By default, this command will show which locks are held. This
2292 By default, this command will show which locks are held. This
2292 includes the user and process holding the lock, the amount of time
2293 includes the user and process holding the lock, the amount of time
2293 the lock has been held, and the machine name where the process is
2294 the lock has been held, and the machine name where the process is
2294 running if it's not local.
2295 running if it's not local.
2295
2296
2296 Locks protect the integrity of Mercurial's data, so should be
2297 Locks protect the integrity of Mercurial's data, so should be
2297 treated with care. System crashes or other interruptions may cause
2298 treated with care. System crashes or other interruptions may cause
2298 locks to not be properly released, though Mercurial will usually
2299 locks to not be properly released, though Mercurial will usually
2299 detect and remove such stale locks automatically.
2300 detect and remove such stale locks automatically.
2300
2301
2301 However, detecting stale locks may not always be possible (for
2302 However, detecting stale locks may not always be possible (for
2302 instance, on a shared filesystem). Removing locks may also be
2303 instance, on a shared filesystem). Removing locks may also be
2303 blocked by filesystem permissions.
2304 blocked by filesystem permissions.
2304
2305
2305 Setting a lock will prevent other commands from changing the data.
2306 Setting a lock will prevent other commands from changing the data.
2306 The command will wait until an interruption (SIGINT, SIGTERM, ...) occurs.
2307 The command will wait until an interruption (SIGINT, SIGTERM, ...) occurs.
2307 The set locks are removed when the command exits.
2308 The set locks are removed when the command exits.
2308
2309
2309 Returns 0 if no locks are held.
2310 Returns 0 if no locks are held.
2310
2311
2311 """
2312 """
2312
2313
2313 if opts.get('force_free_lock'):
2314 if opts.get('force_free_lock'):
2314 repo.svfs.tryunlink(b'lock')
2315 repo.svfs.tryunlink(b'lock')
2315 if opts.get('force_free_wlock'):
2316 if opts.get('force_free_wlock'):
2316 repo.vfs.tryunlink(b'wlock')
2317 repo.vfs.tryunlink(b'wlock')
2317 if opts.get('force_free_lock') or opts.get('force_free_wlock'):
2318 if opts.get('force_free_lock') or opts.get('force_free_wlock'):
2318 return 0
2319 return 0
2319
2320
2320 locks = []
2321 locks = []
2321 try:
2322 try:
2322 if opts.get('set_wlock'):
2323 if opts.get('set_wlock'):
2323 try:
2324 try:
2324 locks.append(repo.wlock(False))
2325 locks.append(repo.wlock(False))
2325 except error.LockHeld:
2326 except error.LockHeld:
2326 raise error.Abort(_(b'wlock is already held'))
2327 raise error.Abort(_(b'wlock is already held'))
2327 if opts.get('set_lock'):
2328 if opts.get('set_lock'):
2328 try:
2329 try:
2329 locks.append(repo.lock(False))
2330 locks.append(repo.lock(False))
2330 except error.LockHeld:
2331 except error.LockHeld:
2331 raise error.Abort(_(b'lock is already held'))
2332 raise error.Abort(_(b'lock is already held'))
2332 if len(locks):
2333 if len(locks):
2333 try:
2334 try:
2334 if ui.interactive():
2335 if ui.interactive():
2335 prompt = _(b"ready to release the lock (y)? $$ &Yes")
2336 prompt = _(b"ready to release the lock (y)? $$ &Yes")
2336 ui.promptchoice(prompt)
2337 ui.promptchoice(prompt)
2337 else:
2338 else:
2338 msg = b"%d locks held, waiting for signal\n"
2339 msg = b"%d locks held, waiting for signal\n"
2339 msg %= len(locks)
2340 msg %= len(locks)
2340 ui.status(msg)
2341 ui.status(msg)
2341 while True: # XXX wait for a signal
2342 while True: # XXX wait for a signal
2342 time.sleep(0.1)
2343 time.sleep(0.1)
2343 except KeyboardInterrupt:
2344 except KeyboardInterrupt:
2344 msg = b"signal-received releasing locks\n"
2345 msg = b"signal-received releasing locks\n"
2345 ui.status(msg)
2346 ui.status(msg)
2346 return 0
2347 return 0
2347 finally:
2348 finally:
2348 release(*locks)
2349 release(*locks)
2349
2350
2350 now = time.time()
2351 now = time.time()
2351 held = 0
2352 held = 0
2352
2353
2353 def report(vfs, name, method):
2354 def report(vfs, name, method):
2354 # this causes stale locks to get reaped for more accurate reporting
2355 # this causes stale locks to get reaped for more accurate reporting
2355 try:
2356 try:
2356 l = method(False)
2357 l = method(False)
2357 except error.LockHeld:
2358 except error.LockHeld:
2358 l = None
2359 l = None
2359
2360
2360 if l:
2361 if l:
2361 l.release()
2362 l.release()
2362 else:
2363 else:
2363 try:
2364 try:
2364 st = vfs.lstat(name)
2365 st = vfs.lstat(name)
2365 age = now - st[stat.ST_MTIME]
2366 age = now - st[stat.ST_MTIME]
2366 user = util.username(st.st_uid)
2367 user = util.username(st.st_uid)
2367 locker = vfs.readlock(name)
2368 locker = vfs.readlock(name)
2368 if b":" in locker:
2369 if b":" in locker:
2369 host, pid = locker.split(b':')
2370 host, pid = locker.split(b':')
2370 if host == socket.gethostname():
2371 if host == socket.gethostname():
2371 locker = b'user %s, process %s' % (user or b'None', pid)
2372 locker = b'user %s, process %s' % (user or b'None', pid)
2372 else:
2373 else:
2373 locker = b'user %s, process %s, host %s' % (
2374 locker = b'user %s, process %s, host %s' % (
2374 user or b'None',
2375 user or b'None',
2375 pid,
2376 pid,
2376 host,
2377 host,
2377 )
2378 )
2378 ui.writenoi18n(b"%-6s %s (%ds)\n" % (name + b":", locker, age))
2379 ui.writenoi18n(b"%-6s %s (%ds)\n" % (name + b":", locker, age))
2379 return 1
2380 return 1
2380 except FileNotFoundError:
2381 except FileNotFoundError:
2381 pass
2382 pass
2382
2383
2383 ui.writenoi18n(b"%-6s free\n" % (name + b":"))
2384 ui.writenoi18n(b"%-6s free\n" % (name + b":"))
2384 return 0
2385 return 0
2385
2386
2386 held += report(repo.svfs, b"lock", repo.lock)
2387 held += report(repo.svfs, b"lock", repo.lock)
2387 held += report(repo.vfs, b"wlock", repo.wlock)
2388 held += report(repo.vfs, b"wlock", repo.wlock)
2388
2389
2389 return held
2390 return held
2390
2391
2391
2392
2392 @command(
2393 @command(
2393 b'debugmanifestfulltextcache',
2394 b'debugmanifestfulltextcache',
2394 [
2395 [
2395 (b'', b'clear', False, _(b'clear the cache')),
2396 (b'', b'clear', False, _(b'clear the cache')),
2396 (
2397 (
2397 b'a',
2398 b'a',
2398 b'add',
2399 b'add',
2399 [],
2400 [],
2400 _(b'add the given manifest nodes to the cache'),
2401 _(b'add the given manifest nodes to the cache'),
2401 _(b'NODE'),
2402 _(b'NODE'),
2402 ),
2403 ),
2403 ],
2404 ],
2404 b'',
2405 b'',
2405 )
2406 )
2406 def debugmanifestfulltextcache(ui, repo, add=(), **opts):
2407 def debugmanifestfulltextcache(ui, repo, add=(), **opts):
2407 """show, clear or amend the contents of the manifest fulltext cache"""
2408 """show, clear or amend the contents of the manifest fulltext cache"""
2408
2409
2409 def getcache():
2410 def getcache():
2410 r = repo.manifestlog.getstorage(b'')
2411 r = repo.manifestlog.getstorage(b'')
2411 try:
2412 try:
2412 return r._fulltextcache
2413 return r._fulltextcache
2413 except AttributeError:
2414 except AttributeError:
2414 msg = _(
2415 msg = _(
2415 b"Current revlog implementation doesn't appear to have a "
2416 b"Current revlog implementation doesn't appear to have a "
2416 b"manifest fulltext cache\n"
2417 b"manifest fulltext cache\n"
2417 )
2418 )
2418 raise error.Abort(msg)
2419 raise error.Abort(msg)
2419
2420
2420 if opts.get('clear'):
2421 if opts.get('clear'):
2421 with repo.wlock():
2422 with repo.wlock():
2422 cache = getcache()
2423 cache = getcache()
2423 cache.clear(clear_persisted_data=True)
2424 cache.clear(clear_persisted_data=True)
2424 return
2425 return
2425
2426
2426 if add:
2427 if add:
2427 with repo.wlock():
2428 with repo.wlock():
2428 m = repo.manifestlog
2429 m = repo.manifestlog
2429 store = m.getstorage(b'')
2430 store = m.getstorage(b'')
2430 for n in add:
2431 for n in add:
2431 try:
2432 try:
2432 manifest = m[store.lookup(n)]
2433 manifest = m[store.lookup(n)]
2433 except error.LookupError as e:
2434 except error.LookupError as e:
2434 raise error.Abort(
2435 raise error.Abort(
2435 bytes(e), hint=b"Check your manifest node id"
2436 bytes(e), hint=b"Check your manifest node id"
2436 )
2437 )
2437 manifest.read() # stores revisision in cache too
2438 manifest.read() # stores revisision in cache too
2438 return
2439 return
2439
2440
2440 cache = getcache()
2441 cache = getcache()
2441 if not len(cache):
2442 if not len(cache):
2442 ui.write(_(b'cache empty\n'))
2443 ui.write(_(b'cache empty\n'))
2443 else:
2444 else:
2444 ui.write(
2445 ui.write(
2445 _(
2446 _(
2446 b'cache contains %d manifest entries, in order of most to '
2447 b'cache contains %d manifest entries, in order of most to '
2447 b'least recent:\n'
2448 b'least recent:\n'
2448 )
2449 )
2449 % (len(cache),)
2450 % (len(cache),)
2450 )
2451 )
2451 totalsize = 0
2452 totalsize = 0
2452 for nodeid in cache:
2453 for nodeid in cache:
2453 # Use cache.get to not update the LRU order
2454 # Use cache.get to not update the LRU order
2454 data = cache.peek(nodeid)
2455 data = cache.peek(nodeid)
2455 size = len(data)
2456 size = len(data)
2456 totalsize += size + 24 # 20 bytes nodeid, 4 bytes size
2457 totalsize += size + 24 # 20 bytes nodeid, 4 bytes size
2457 ui.write(
2458 ui.write(
2458 _(b'id: %s, size %s\n') % (hex(nodeid), util.bytecount(size))
2459 _(b'id: %s, size %s\n') % (hex(nodeid), util.bytecount(size))
2459 )
2460 )
2460 ondisk = cache._opener.stat(b'manifestfulltextcache').st_size
2461 ondisk = cache._opener.stat(b'manifestfulltextcache').st_size
2461 ui.write(
2462 ui.write(
2462 _(b'total cache data size %s, on-disk %s\n')
2463 _(b'total cache data size %s, on-disk %s\n')
2463 % (util.bytecount(totalsize), util.bytecount(ondisk))
2464 % (util.bytecount(totalsize), util.bytecount(ondisk))
2464 )
2465 )
2465
2466
2466
2467
2467 @command(b'debugmergestate', [] + cmdutil.templateopts, b'')
2468 @command(b'debugmergestate', [] + cmdutil.templateopts, b'')
2468 def debugmergestate(ui, repo, *args, **opts):
2469 def debugmergestate(ui, repo, *args, **opts):
2469 """print merge state
2470 """print merge state
2470
2471
2471 Use --verbose to print out information about whether v1 or v2 merge state
2472 Use --verbose to print out information about whether v1 or v2 merge state
2472 was chosen."""
2473 was chosen."""
2473
2474
2474 if ui.verbose:
2475 if ui.verbose:
2475 ms = mergestatemod.mergestate(repo)
2476 ms = mergestatemod.mergestate(repo)
2476
2477
2477 # sort so that reasonable information is on top
2478 # sort so that reasonable information is on top
2478 v1records = ms._readrecordsv1()
2479 v1records = ms._readrecordsv1()
2479 v2records = ms._readrecordsv2()
2480 v2records = ms._readrecordsv2()
2480
2481
2481 if not v1records and not v2records:
2482 if not v1records and not v2records:
2482 pass
2483 pass
2483 elif not v2records:
2484 elif not v2records:
2484 ui.writenoi18n(b'no version 2 merge state\n')
2485 ui.writenoi18n(b'no version 2 merge state\n')
2485 elif ms._v1v2match(v1records, v2records):
2486 elif ms._v1v2match(v1records, v2records):
2486 ui.writenoi18n(b'v1 and v2 states match: using v2\n')
2487 ui.writenoi18n(b'v1 and v2 states match: using v2\n')
2487 else:
2488 else:
2488 ui.writenoi18n(b'v1 and v2 states mismatch: using v1\n')
2489 ui.writenoi18n(b'v1 and v2 states mismatch: using v1\n')
2489
2490
2490 opts = pycompat.byteskwargs(opts)
2491 opts = pycompat.byteskwargs(opts)
2491 if not opts[b'template']:
2492 if not opts[b'template']:
2492 opts[b'template'] = (
2493 opts[b'template'] = (
2493 b'{if(commits, "", "no merge state found\n")}'
2494 b'{if(commits, "", "no merge state found\n")}'
2494 b'{commits % "{name}{if(label, " ({label})")}: {node}\n"}'
2495 b'{commits % "{name}{if(label, " ({label})")}: {node}\n"}'
2495 b'{files % "file: {path} (state \\"{state}\\")\n'
2496 b'{files % "file: {path} (state \\"{state}\\")\n'
2496 b'{if(local_path, "'
2497 b'{if(local_path, "'
2497 b' local path: {local_path} (hash {local_key}, flags \\"{local_flags}\\")\n'
2498 b' local path: {local_path} (hash {local_key}, flags \\"{local_flags}\\")\n'
2498 b' ancestor path: {ancestor_path} (node {ancestor_node})\n'
2499 b' ancestor path: {ancestor_path} (node {ancestor_node})\n'
2499 b' other path: {other_path} (node {other_node})\n'
2500 b' other path: {other_path} (node {other_node})\n'
2500 b'")}'
2501 b'")}'
2501 b'{if(rename_side, "'
2502 b'{if(rename_side, "'
2502 b' rename side: {rename_side}\n'
2503 b' rename side: {rename_side}\n'
2503 b' renamed path: {renamed_path}\n'
2504 b' renamed path: {renamed_path}\n'
2504 b'")}'
2505 b'")}'
2505 b'{extras % " extra: {key} = {value}\n"}'
2506 b'{extras % " extra: {key} = {value}\n"}'
2506 b'"}'
2507 b'"}'
2507 b'{extras % "extra: {file} ({key} = {value})\n"}'
2508 b'{extras % "extra: {file} ({key} = {value})\n"}'
2508 )
2509 )
2509
2510
2510 ms = mergestatemod.mergestate.read(repo)
2511 ms = mergestatemod.mergestate.read(repo)
2511
2512
2512 fm = ui.formatter(b'debugmergestate', opts)
2513 fm = ui.formatter(b'debugmergestate', opts)
2513 fm.startitem()
2514 fm.startitem()
2514
2515
2515 fm_commits = fm.nested(b'commits')
2516 fm_commits = fm.nested(b'commits')
2516 if ms.active():
2517 if ms.active():
2517 for name, node, label_index in (
2518 for name, node, label_index in (
2518 (b'local', ms.local, 0),
2519 (b'local', ms.local, 0),
2519 (b'other', ms.other, 1),
2520 (b'other', ms.other, 1),
2520 ):
2521 ):
2521 fm_commits.startitem()
2522 fm_commits.startitem()
2522 fm_commits.data(name=name)
2523 fm_commits.data(name=name)
2523 fm_commits.data(node=hex(node))
2524 fm_commits.data(node=hex(node))
2524 if ms._labels and len(ms._labels) > label_index:
2525 if ms._labels and len(ms._labels) > label_index:
2525 fm_commits.data(label=ms._labels[label_index])
2526 fm_commits.data(label=ms._labels[label_index])
2526 fm_commits.end()
2527 fm_commits.end()
2527
2528
2528 fm_files = fm.nested(b'files')
2529 fm_files = fm.nested(b'files')
2529 if ms.active():
2530 if ms.active():
2530 for f in ms:
2531 for f in ms:
2531 fm_files.startitem()
2532 fm_files.startitem()
2532 fm_files.data(path=f)
2533 fm_files.data(path=f)
2533 state = ms._state[f]
2534 state = ms._state[f]
2534 fm_files.data(state=state[0])
2535 fm_files.data(state=state[0])
2535 if state[0] in (
2536 if state[0] in (
2536 mergestatemod.MERGE_RECORD_UNRESOLVED,
2537 mergestatemod.MERGE_RECORD_UNRESOLVED,
2537 mergestatemod.MERGE_RECORD_RESOLVED,
2538 mergestatemod.MERGE_RECORD_RESOLVED,
2538 ):
2539 ):
2539 fm_files.data(local_key=state[1])
2540 fm_files.data(local_key=state[1])
2540 fm_files.data(local_path=state[2])
2541 fm_files.data(local_path=state[2])
2541 fm_files.data(ancestor_path=state[3])
2542 fm_files.data(ancestor_path=state[3])
2542 fm_files.data(ancestor_node=state[4])
2543 fm_files.data(ancestor_node=state[4])
2543 fm_files.data(other_path=state[5])
2544 fm_files.data(other_path=state[5])
2544 fm_files.data(other_node=state[6])
2545 fm_files.data(other_node=state[6])
2545 fm_files.data(local_flags=state[7])
2546 fm_files.data(local_flags=state[7])
2546 elif state[0] in (
2547 elif state[0] in (
2547 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
2548 mergestatemod.MERGE_RECORD_UNRESOLVED_PATH,
2548 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
2549 mergestatemod.MERGE_RECORD_RESOLVED_PATH,
2549 ):
2550 ):
2550 fm_files.data(renamed_path=state[1])
2551 fm_files.data(renamed_path=state[1])
2551 fm_files.data(rename_side=state[2])
2552 fm_files.data(rename_side=state[2])
2552 fm_extras = fm_files.nested(b'extras')
2553 fm_extras = fm_files.nested(b'extras')
2553 for k, v in sorted(ms.extras(f).items()):
2554 for k, v in sorted(ms.extras(f).items()):
2554 fm_extras.startitem()
2555 fm_extras.startitem()
2555 fm_extras.data(key=k)
2556 fm_extras.data(key=k)
2556 fm_extras.data(value=v)
2557 fm_extras.data(value=v)
2557 fm_extras.end()
2558 fm_extras.end()
2558
2559
2559 fm_files.end()
2560 fm_files.end()
2560
2561
2561 fm_extras = fm.nested(b'extras')
2562 fm_extras = fm.nested(b'extras')
2562 for f, d in sorted(ms.allextras().items()):
2563 for f, d in sorted(ms.allextras().items()):
2563 if f in ms:
2564 if f in ms:
2564 # If file is in mergestate, we have already processed it's extras
2565 # If file is in mergestate, we have already processed it's extras
2565 continue
2566 continue
2566 for k, v in d.items():
2567 for k, v in d.items():
2567 fm_extras.startitem()
2568 fm_extras.startitem()
2568 fm_extras.data(file=f)
2569 fm_extras.data(file=f)
2569 fm_extras.data(key=k)
2570 fm_extras.data(key=k)
2570 fm_extras.data(value=v)
2571 fm_extras.data(value=v)
2571 fm_extras.end()
2572 fm_extras.end()
2572
2573
2573 fm.end()
2574 fm.end()
2574
2575
2575
2576
2576 @command(b'debugnamecomplete', [], _(b'NAME...'))
2577 @command(b'debugnamecomplete', [], _(b'NAME...'))
2577 def debugnamecomplete(ui, repo, *args):
2578 def debugnamecomplete(ui, repo, *args):
2578 '''complete "names" - tags, open branch names, bookmark names'''
2579 '''complete "names" - tags, open branch names, bookmark names'''
2579
2580
2580 names = set()
2581 names = set()
2581 # since we previously only listed open branches, we will handle that
2582 # since we previously only listed open branches, we will handle that
2582 # specially (after this for loop)
2583 # specially (after this for loop)
2583 for name, ns in repo.names.items():
2584 for name, ns in repo.names.items():
2584 if name != b'branches':
2585 if name != b'branches':
2585 names.update(ns.listnames(repo))
2586 names.update(ns.listnames(repo))
2586 names.update(
2587 names.update(
2587 tag
2588 tag
2588 for (tag, heads, tip, closed) in repo.branchmap().iterbranches()
2589 for (tag, heads, tip, closed) in repo.branchmap().iterbranches()
2589 if not closed
2590 if not closed
2590 )
2591 )
2591 completions = set()
2592 completions = set()
2592 if not args:
2593 if not args:
2593 args = [b'']
2594 args = [b'']
2594 for a in args:
2595 for a in args:
2595 completions.update(n for n in names if n.startswith(a))
2596 completions.update(n for n in names if n.startswith(a))
2596 ui.write(b'\n'.join(sorted(completions)))
2597 ui.write(b'\n'.join(sorted(completions)))
2597 ui.write(b'\n')
2598 ui.write(b'\n')
2598
2599
2599
2600
2600 @command(
2601 @command(
2601 b'debugnodemap',
2602 b'debugnodemap',
2602 [
2603 [
2603 (
2604 (
2604 b'',
2605 b'',
2605 b'dump-new',
2606 b'dump-new',
2606 False,
2607 False,
2607 _(b'write a (new) persistent binary nodemap on stdout'),
2608 _(b'write a (new) persistent binary nodemap on stdout'),
2608 ),
2609 ),
2609 (b'', b'dump-disk', False, _(b'dump on-disk data on stdout')),
2610 (b'', b'dump-disk', False, _(b'dump on-disk data on stdout')),
2610 (
2611 (
2611 b'',
2612 b'',
2612 b'check',
2613 b'check',
2613 False,
2614 False,
2614 _(b'check that the data on disk data are correct.'),
2615 _(b'check that the data on disk data are correct.'),
2615 ),
2616 ),
2616 (
2617 (
2617 b'',
2618 b'',
2618 b'metadata',
2619 b'metadata',
2619 False,
2620 False,
2620 _(b'display the on disk meta data for the nodemap'),
2621 _(b'display the on disk meta data for the nodemap'),
2621 ),
2622 ),
2622 ],
2623 ],
2623 )
2624 )
2624 def debugnodemap(ui, repo, **opts):
2625 def debugnodemap(ui, repo, **opts):
2625 """write and inspect on disk nodemap"""
2626 """write and inspect on disk nodemap"""
2626 if opts['dump_new']:
2627 if opts['dump_new']:
2627 unfi = repo.unfiltered()
2628 unfi = repo.unfiltered()
2628 cl = unfi.changelog
2629 cl = unfi.changelog
2629 if util.safehasattr(cl.index, "nodemap_data_all"):
2630 if util.safehasattr(cl.index, "nodemap_data_all"):
2630 data = cl.index.nodemap_data_all()
2631 data = cl.index.nodemap_data_all()
2631 else:
2632 else:
2632 data = nodemap.persistent_data(cl.index)
2633 data = nodemap.persistent_data(cl.index)
2633 ui.write(data)
2634 ui.write(data)
2634 elif opts['dump_disk']:
2635 elif opts['dump_disk']:
2635 unfi = repo.unfiltered()
2636 unfi = repo.unfiltered()
2636 cl = unfi.changelog
2637 cl = unfi.changelog
2637 nm_data = nodemap.persisted_data(cl)
2638 nm_data = nodemap.persisted_data(cl)
2638 if nm_data is not None:
2639 if nm_data is not None:
2639 docket, data = nm_data
2640 docket, data = nm_data
2640 ui.write(data[:])
2641 ui.write(data[:])
2641 elif opts['check']:
2642 elif opts['check']:
2642 unfi = repo.unfiltered()
2643 unfi = repo.unfiltered()
2643 cl = unfi.changelog
2644 cl = unfi.changelog
2644 nm_data = nodemap.persisted_data(cl)
2645 nm_data = nodemap.persisted_data(cl)
2645 if nm_data is not None:
2646 if nm_data is not None:
2646 docket, data = nm_data
2647 docket, data = nm_data
2647 return nodemap.check_data(ui, cl.index, data)
2648 return nodemap.check_data(ui, cl.index, data)
2648 elif opts['metadata']:
2649 elif opts['metadata']:
2649 unfi = repo.unfiltered()
2650 unfi = repo.unfiltered()
2650 cl = unfi.changelog
2651 cl = unfi.changelog
2651 nm_data = nodemap.persisted_data(cl)
2652 nm_data = nodemap.persisted_data(cl)
2652 if nm_data is not None:
2653 if nm_data is not None:
2653 docket, data = nm_data
2654 docket, data = nm_data
2654 ui.write((b"uid: %s\n") % docket.uid)
2655 ui.write((b"uid: %s\n") % docket.uid)
2655 ui.write((b"tip-rev: %d\n") % docket.tip_rev)
2656 ui.write((b"tip-rev: %d\n") % docket.tip_rev)
2656 ui.write((b"tip-node: %s\n") % hex(docket.tip_node))
2657 ui.write((b"tip-node: %s\n") % hex(docket.tip_node))
2657 ui.write((b"data-length: %d\n") % docket.data_length)
2658 ui.write((b"data-length: %d\n") % docket.data_length)
2658 ui.write((b"data-unused: %d\n") % docket.data_unused)
2659 ui.write((b"data-unused: %d\n") % docket.data_unused)
2659 unused_perc = docket.data_unused * 100.0 / docket.data_length
2660 unused_perc = docket.data_unused * 100.0 / docket.data_length
2660 ui.write((b"data-unused: %2.3f%%\n") % unused_perc)
2661 ui.write((b"data-unused: %2.3f%%\n") % unused_perc)
2661
2662
2662
2663
2663 @command(
2664 @command(
2664 b'debugobsolete',
2665 b'debugobsolete',
2665 [
2666 [
2666 (b'', b'flags', 0, _(b'markers flag')),
2667 (b'', b'flags', 0, _(b'markers flag')),
2667 (
2668 (
2668 b'',
2669 b'',
2669 b'record-parents',
2670 b'record-parents',
2670 False,
2671 False,
2671 _(b'record parent information for the precursor'),
2672 _(b'record parent information for the precursor'),
2672 ),
2673 ),
2673 (b'r', b'rev', [], _(b'display markers relevant to REV')),
2674 (b'r', b'rev', [], _(b'display markers relevant to REV')),
2674 (
2675 (
2675 b'',
2676 b'',
2676 b'exclusive',
2677 b'exclusive',
2677 False,
2678 False,
2678 _(b'restrict display to markers only relevant to REV'),
2679 _(b'restrict display to markers only relevant to REV'),
2679 ),
2680 ),
2680 (b'', b'index', False, _(b'display index of the marker')),
2681 (b'', b'index', False, _(b'display index of the marker')),
2681 (b'', b'delete', [], _(b'delete markers specified by indices')),
2682 (b'', b'delete', [], _(b'delete markers specified by indices')),
2682 ]
2683 ]
2683 + cmdutil.commitopts2
2684 + cmdutil.commitopts2
2684 + cmdutil.formatteropts,
2685 + cmdutil.formatteropts,
2685 _(b'[OBSOLETED [REPLACEMENT ...]]'),
2686 _(b'[OBSOLETED [REPLACEMENT ...]]'),
2686 )
2687 )
2687 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2688 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2688 """create arbitrary obsolete marker
2689 """create arbitrary obsolete marker
2689
2690
2690 With no arguments, displays the list of obsolescence markers."""
2691 With no arguments, displays the list of obsolescence markers."""
2691
2692
2692 opts = pycompat.byteskwargs(opts)
2693 opts = pycompat.byteskwargs(opts)
2693
2694
2694 def parsenodeid(s):
2695 def parsenodeid(s):
2695 try:
2696 try:
2696 # We do not use revsingle/revrange functions here to accept
2697 # We do not use revsingle/revrange functions here to accept
2697 # arbitrary node identifiers, possibly not present in the
2698 # arbitrary node identifiers, possibly not present in the
2698 # local repository.
2699 # local repository.
2699 n = bin(s)
2700 n = bin(s)
2700 if len(n) != repo.nodeconstants.nodelen:
2701 if len(n) != repo.nodeconstants.nodelen:
2701 raise ValueError
2702 raise ValueError
2702 return n
2703 return n
2703 except ValueError:
2704 except ValueError:
2704 raise error.InputError(
2705 raise error.InputError(
2705 b'changeset references must be full hexadecimal '
2706 b'changeset references must be full hexadecimal '
2706 b'node identifiers'
2707 b'node identifiers'
2707 )
2708 )
2708
2709
2709 if opts.get(b'delete'):
2710 if opts.get(b'delete'):
2710 indices = []
2711 indices = []
2711 for v in opts.get(b'delete'):
2712 for v in opts.get(b'delete'):
2712 try:
2713 try:
2713 indices.append(int(v))
2714 indices.append(int(v))
2714 except ValueError:
2715 except ValueError:
2715 raise error.InputError(
2716 raise error.InputError(
2716 _(b'invalid index value: %r') % v,
2717 _(b'invalid index value: %r') % v,
2717 hint=_(b'use integers for indices'),
2718 hint=_(b'use integers for indices'),
2718 )
2719 )
2719
2720
2720 if repo.currenttransaction():
2721 if repo.currenttransaction():
2721 raise error.Abort(
2722 raise error.Abort(
2722 _(b'cannot delete obsmarkers in the middle of transaction.')
2723 _(b'cannot delete obsmarkers in the middle of transaction.')
2723 )
2724 )
2724
2725
2725 with repo.lock():
2726 with repo.lock():
2726 n = repair.deleteobsmarkers(repo.obsstore, indices)
2727 n = repair.deleteobsmarkers(repo.obsstore, indices)
2727 ui.write(_(b'deleted %i obsolescence markers\n') % n)
2728 ui.write(_(b'deleted %i obsolescence markers\n') % n)
2728
2729
2729 return
2730 return
2730
2731
2731 if precursor is not None:
2732 if precursor is not None:
2732 if opts[b'rev']:
2733 if opts[b'rev']:
2733 raise error.InputError(
2734 raise error.InputError(
2734 b'cannot select revision when creating marker'
2735 b'cannot select revision when creating marker'
2735 )
2736 )
2736 metadata = {}
2737 metadata = {}
2737 metadata[b'user'] = encoding.fromlocal(opts[b'user'] or ui.username())
2738 metadata[b'user'] = encoding.fromlocal(opts[b'user'] or ui.username())
2738 succs = tuple(parsenodeid(succ) for succ in successors)
2739 succs = tuple(parsenodeid(succ) for succ in successors)
2739 l = repo.lock()
2740 l = repo.lock()
2740 try:
2741 try:
2741 tr = repo.transaction(b'debugobsolete')
2742 tr = repo.transaction(b'debugobsolete')
2742 try:
2743 try:
2743 date = opts.get(b'date')
2744 date = opts.get(b'date')
2744 if date:
2745 if date:
2745 date = dateutil.parsedate(date)
2746 date = dateutil.parsedate(date)
2746 else:
2747 else:
2747 date = None
2748 date = None
2748 prec = parsenodeid(precursor)
2749 prec = parsenodeid(precursor)
2749 parents = None
2750 parents = None
2750 if opts[b'record_parents']:
2751 if opts[b'record_parents']:
2751 if prec not in repo.unfiltered():
2752 if prec not in repo.unfiltered():
2752 raise error.Abort(
2753 raise error.Abort(
2753 b'cannot used --record-parents on '
2754 b'cannot used --record-parents on '
2754 b'unknown changesets'
2755 b'unknown changesets'
2755 )
2756 )
2756 parents = repo.unfiltered()[prec].parents()
2757 parents = repo.unfiltered()[prec].parents()
2757 parents = tuple(p.node() for p in parents)
2758 parents = tuple(p.node() for p in parents)
2758 repo.obsstore.create(
2759 repo.obsstore.create(
2759 tr,
2760 tr,
2760 prec,
2761 prec,
2761 succs,
2762 succs,
2762 opts[b'flags'],
2763 opts[b'flags'],
2763 parents=parents,
2764 parents=parents,
2764 date=date,
2765 date=date,
2765 metadata=metadata,
2766 metadata=metadata,
2766 ui=ui,
2767 ui=ui,
2767 )
2768 )
2768 tr.close()
2769 tr.close()
2769 except ValueError as exc:
2770 except ValueError as exc:
2770 raise error.Abort(
2771 raise error.Abort(
2771 _(b'bad obsmarker input: %s') % stringutil.forcebytestr(exc)
2772 _(b'bad obsmarker input: %s') % stringutil.forcebytestr(exc)
2772 )
2773 )
2773 finally:
2774 finally:
2774 tr.release()
2775 tr.release()
2775 finally:
2776 finally:
2776 l.release()
2777 l.release()
2777 else:
2778 else:
2778 if opts[b'rev']:
2779 if opts[b'rev']:
2779 revs = logcmdutil.revrange(repo, opts[b'rev'])
2780 revs = logcmdutil.revrange(repo, opts[b'rev'])
2780 nodes = [repo[r].node() for r in revs]
2781 nodes = [repo[r].node() for r in revs]
2781 markers = list(
2782 markers = list(
2782 obsutil.getmarkers(
2783 obsutil.getmarkers(
2783 repo, nodes=nodes, exclusive=opts[b'exclusive']
2784 repo, nodes=nodes, exclusive=opts[b'exclusive']
2784 )
2785 )
2785 )
2786 )
2786 markers.sort(key=lambda x: x._data)
2787 markers.sort(key=lambda x: x._data)
2787 else:
2788 else:
2788 markers = obsutil.getmarkers(repo)
2789 markers = obsutil.getmarkers(repo)
2789
2790
2790 markerstoiter = markers
2791 markerstoiter = markers
2791 isrelevant = lambda m: True
2792 isrelevant = lambda m: True
2792 if opts.get(b'rev') and opts.get(b'index'):
2793 if opts.get(b'rev') and opts.get(b'index'):
2793 markerstoiter = obsutil.getmarkers(repo)
2794 markerstoiter = obsutil.getmarkers(repo)
2794 markerset = set(markers)
2795 markerset = set(markers)
2795 isrelevant = lambda m: m in markerset
2796 isrelevant = lambda m: m in markerset
2796
2797
2797 fm = ui.formatter(b'debugobsolete', opts)
2798 fm = ui.formatter(b'debugobsolete', opts)
2798 for i, m in enumerate(markerstoiter):
2799 for i, m in enumerate(markerstoiter):
2799 if not isrelevant(m):
2800 if not isrelevant(m):
2800 # marker can be irrelevant when we're iterating over a set
2801 # marker can be irrelevant when we're iterating over a set
2801 # of markers (markerstoiter) which is bigger than the set
2802 # of markers (markerstoiter) which is bigger than the set
2802 # of markers we want to display (markers)
2803 # of markers we want to display (markers)
2803 # this can happen if both --index and --rev options are
2804 # this can happen if both --index and --rev options are
2804 # provided and thus we need to iterate over all of the markers
2805 # provided and thus we need to iterate over all of the markers
2805 # to get the correct indices, but only display the ones that
2806 # to get the correct indices, but only display the ones that
2806 # are relevant to --rev value
2807 # are relevant to --rev value
2807 continue
2808 continue
2808 fm.startitem()
2809 fm.startitem()
2809 ind = i if opts.get(b'index') else None
2810 ind = i if opts.get(b'index') else None
2810 cmdutil.showmarker(fm, m, index=ind)
2811 cmdutil.showmarker(fm, m, index=ind)
2811 fm.end()
2812 fm.end()
2812
2813
2813
2814
2814 @command(
2815 @command(
2815 b'debugp1copies',
2816 b'debugp1copies',
2816 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2817 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2817 _(b'[-r REV]'),
2818 _(b'[-r REV]'),
2818 )
2819 )
2819 def debugp1copies(ui, repo, **opts):
2820 def debugp1copies(ui, repo, **opts):
2820 """dump copy information compared to p1"""
2821 """dump copy information compared to p1"""
2821
2822
2822 opts = pycompat.byteskwargs(opts)
2823 opts = pycompat.byteskwargs(opts)
2823 ctx = scmutil.revsingle(repo, opts.get(b'rev'), default=None)
2824 ctx = scmutil.revsingle(repo, opts.get(b'rev'), default=None)
2824 for dst, src in ctx.p1copies().items():
2825 for dst, src in ctx.p1copies().items():
2825 ui.write(b'%s -> %s\n' % (src, dst))
2826 ui.write(b'%s -> %s\n' % (src, dst))
2826
2827
2827
2828
2828 @command(
2829 @command(
2829 b'debugp2copies',
2830 b'debugp2copies',
2830 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2831 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
2831 _(b'[-r REV]'),
2832 _(b'[-r REV]'),
2832 )
2833 )
2833 def debugp2copies(ui, repo, **opts):
2834 def debugp2copies(ui, repo, **opts):
2834 """dump copy information compared to p2"""
2835 """dump copy information compared to p2"""
2835
2836
2836 opts = pycompat.byteskwargs(opts)
2837 opts = pycompat.byteskwargs(opts)
2837 ctx = scmutil.revsingle(repo, opts.get(b'rev'), default=None)
2838 ctx = scmutil.revsingle(repo, opts.get(b'rev'), default=None)
2838 for dst, src in ctx.p2copies().items():
2839 for dst, src in ctx.p2copies().items():
2839 ui.write(b'%s -> %s\n' % (src, dst))
2840 ui.write(b'%s -> %s\n' % (src, dst))
2840
2841
2841
2842
2842 @command(
2843 @command(
2843 b'debugpathcomplete',
2844 b'debugpathcomplete',
2844 [
2845 [
2845 (b'f', b'full', None, _(b'complete an entire path')),
2846 (b'f', b'full', None, _(b'complete an entire path')),
2846 (b'n', b'normal', None, _(b'show only normal files')),
2847 (b'n', b'normal', None, _(b'show only normal files')),
2847 (b'a', b'added', None, _(b'show only added files')),
2848 (b'a', b'added', None, _(b'show only added files')),
2848 (b'r', b'removed', None, _(b'show only removed files')),
2849 (b'r', b'removed', None, _(b'show only removed files')),
2849 ],
2850 ],
2850 _(b'FILESPEC...'),
2851 _(b'FILESPEC...'),
2851 )
2852 )
2852 def debugpathcomplete(ui, repo, *specs, **opts):
2853 def debugpathcomplete(ui, repo, *specs, **opts):
2853 """complete part or all of a tracked path
2854 """complete part or all of a tracked path
2854
2855
2855 This command supports shells that offer path name completion. It
2856 This command supports shells that offer path name completion. It
2856 currently completes only files already known to the dirstate.
2857 currently completes only files already known to the dirstate.
2857
2858
2858 Completion extends only to the next path segment unless
2859 Completion extends only to the next path segment unless
2859 --full is specified, in which case entire paths are used."""
2860 --full is specified, in which case entire paths are used."""
2860
2861
2861 def complete(path, acceptable):
2862 def complete(path, acceptable):
2862 dirstate = repo.dirstate
2863 dirstate = repo.dirstate
2863 spec = os.path.normpath(os.path.join(encoding.getcwd(), path))
2864 spec = os.path.normpath(os.path.join(encoding.getcwd(), path))
2864 rootdir = repo.root + pycompat.ossep
2865 rootdir = repo.root + pycompat.ossep
2865 if spec != repo.root and not spec.startswith(rootdir):
2866 if spec != repo.root and not spec.startswith(rootdir):
2866 return [], []
2867 return [], []
2867 if os.path.isdir(spec):
2868 if os.path.isdir(spec):
2868 spec += b'/'
2869 spec += b'/'
2869 spec = spec[len(rootdir) :]
2870 spec = spec[len(rootdir) :]
2870 fixpaths = pycompat.ossep != b'/'
2871 fixpaths = pycompat.ossep != b'/'
2871 if fixpaths:
2872 if fixpaths:
2872 spec = spec.replace(pycompat.ossep, b'/')
2873 spec = spec.replace(pycompat.ossep, b'/')
2873 speclen = len(spec)
2874 speclen = len(spec)
2874 fullpaths = opts['full']
2875 fullpaths = opts['full']
2875 files, dirs = set(), set()
2876 files, dirs = set(), set()
2876 adddir, addfile = dirs.add, files.add
2877 adddir, addfile = dirs.add, files.add
2877 for f, st in dirstate.items():
2878 for f, st in dirstate.items():
2878 if f.startswith(spec) and st.state in acceptable:
2879 if f.startswith(spec) and st.state in acceptable:
2879 if fixpaths:
2880 if fixpaths:
2880 f = f.replace(b'/', pycompat.ossep)
2881 f = f.replace(b'/', pycompat.ossep)
2881 if fullpaths:
2882 if fullpaths:
2882 addfile(f)
2883 addfile(f)
2883 continue
2884 continue
2884 s = f.find(pycompat.ossep, speclen)
2885 s = f.find(pycompat.ossep, speclen)
2885 if s >= 0:
2886 if s >= 0:
2886 adddir(f[:s])
2887 adddir(f[:s])
2887 else:
2888 else:
2888 addfile(f)
2889 addfile(f)
2889 return files, dirs
2890 return files, dirs
2890
2891
2891 acceptable = b''
2892 acceptable = b''
2892 if opts['normal']:
2893 if opts['normal']:
2893 acceptable += b'nm'
2894 acceptable += b'nm'
2894 if opts['added']:
2895 if opts['added']:
2895 acceptable += b'a'
2896 acceptable += b'a'
2896 if opts['removed']:
2897 if opts['removed']:
2897 acceptable += b'r'
2898 acceptable += b'r'
2898 cwd = repo.getcwd()
2899 cwd = repo.getcwd()
2899 if not specs:
2900 if not specs:
2900 specs = [b'.']
2901 specs = [b'.']
2901
2902
2902 files, dirs = set(), set()
2903 files, dirs = set(), set()
2903 for spec in specs:
2904 for spec in specs:
2904 f, d = complete(spec, acceptable or b'nmar')
2905 f, d = complete(spec, acceptable or b'nmar')
2905 files.update(f)
2906 files.update(f)
2906 dirs.update(d)
2907 dirs.update(d)
2907 files.update(dirs)
2908 files.update(dirs)
2908 ui.write(b'\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2909 ui.write(b'\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2909 ui.write(b'\n')
2910 ui.write(b'\n')
2910
2911
2911
2912
2912 @command(
2913 @command(
2913 b'debugpathcopies',
2914 b'debugpathcopies',
2914 cmdutil.walkopts,
2915 cmdutil.walkopts,
2915 b'hg debugpathcopies REV1 REV2 [FILE]',
2916 b'hg debugpathcopies REV1 REV2 [FILE]',
2916 inferrepo=True,
2917 inferrepo=True,
2917 )
2918 )
2918 def debugpathcopies(ui, repo, rev1, rev2, *pats, **opts):
2919 def debugpathcopies(ui, repo, rev1, rev2, *pats, **opts):
2919 """show copies between two revisions"""
2920 """show copies between two revisions"""
2920 ctx1 = scmutil.revsingle(repo, rev1)
2921 ctx1 = scmutil.revsingle(repo, rev1)
2921 ctx2 = scmutil.revsingle(repo, rev2)
2922 ctx2 = scmutil.revsingle(repo, rev2)
2922 m = scmutil.match(ctx1, pats, opts)
2923 m = scmutil.match(ctx1, pats, opts)
2923 for dst, src in sorted(copies.pathcopies(ctx1, ctx2, m).items()):
2924 for dst, src in sorted(copies.pathcopies(ctx1, ctx2, m).items()):
2924 ui.write(b'%s -> %s\n' % (src, dst))
2925 ui.write(b'%s -> %s\n' % (src, dst))
2925
2926
2926
2927
2927 @command(b'debugpeer', [], _(b'PATH'), norepo=True)
2928 @command(b'debugpeer', [], _(b'PATH'), norepo=True)
2928 def debugpeer(ui, path):
2929 def debugpeer(ui, path):
2929 """establish a connection to a peer repository"""
2930 """establish a connection to a peer repository"""
2930 # Always enable peer request logging. Requires --debug to display
2931 # Always enable peer request logging. Requires --debug to display
2931 # though.
2932 # though.
2932 overrides = {
2933 overrides = {
2933 (b'devel', b'debug.peer-request'): True,
2934 (b'devel', b'debug.peer-request'): True,
2934 }
2935 }
2935
2936
2936 with ui.configoverride(overrides):
2937 with ui.configoverride(overrides):
2937 peer = hg.peer(ui, {}, path)
2938 peer = hg.peer(ui, {}, path)
2938
2939
2939 try:
2940 try:
2940 local = peer.local() is not None
2941 local = peer.local() is not None
2941 canpush = peer.canpush()
2942 canpush = peer.canpush()
2942
2943
2943 ui.write(_(b'url: %s\n') % peer.url())
2944 ui.write(_(b'url: %s\n') % peer.url())
2944 ui.write(_(b'local: %s\n') % (_(b'yes') if local else _(b'no')))
2945 ui.write(_(b'local: %s\n') % (_(b'yes') if local else _(b'no')))
2945 ui.write(
2946 ui.write(
2946 _(b'pushable: %s\n') % (_(b'yes') if canpush else _(b'no'))
2947 _(b'pushable: %s\n') % (_(b'yes') if canpush else _(b'no'))
2947 )
2948 )
2948 finally:
2949 finally:
2949 peer.close()
2950 peer.close()
2950
2951
2951
2952
2952 @command(
2953 @command(
2953 b'debugpickmergetool',
2954 b'debugpickmergetool',
2954 [
2955 [
2955 (b'r', b'rev', b'', _(b'check for files in this revision'), _(b'REV')),
2956 (b'r', b'rev', b'', _(b'check for files in this revision'), _(b'REV')),
2956 (b'', b'changedelete', None, _(b'emulate merging change and delete')),
2957 (b'', b'changedelete', None, _(b'emulate merging change and delete')),
2957 ]
2958 ]
2958 + cmdutil.walkopts
2959 + cmdutil.walkopts
2959 + cmdutil.mergetoolopts,
2960 + cmdutil.mergetoolopts,
2960 _(b'[PATTERN]...'),
2961 _(b'[PATTERN]...'),
2961 inferrepo=True,
2962 inferrepo=True,
2962 )
2963 )
2963 def debugpickmergetool(ui, repo, *pats, **opts):
2964 def debugpickmergetool(ui, repo, *pats, **opts):
2964 """examine which merge tool is chosen for specified file
2965 """examine which merge tool is chosen for specified file
2965
2966
2966 As described in :hg:`help merge-tools`, Mercurial examines
2967 As described in :hg:`help merge-tools`, Mercurial examines
2967 configurations below in this order to decide which merge tool is
2968 configurations below in this order to decide which merge tool is
2968 chosen for specified file.
2969 chosen for specified file.
2969
2970
2970 1. ``--tool`` option
2971 1. ``--tool`` option
2971 2. ``HGMERGE`` environment variable
2972 2. ``HGMERGE`` environment variable
2972 3. configurations in ``merge-patterns`` section
2973 3. configurations in ``merge-patterns`` section
2973 4. configuration of ``ui.merge``
2974 4. configuration of ``ui.merge``
2974 5. configurations in ``merge-tools`` section
2975 5. configurations in ``merge-tools`` section
2975 6. ``hgmerge`` tool (for historical reason only)
2976 6. ``hgmerge`` tool (for historical reason only)
2976 7. default tool for fallback (``:merge`` or ``:prompt``)
2977 7. default tool for fallback (``:merge`` or ``:prompt``)
2977
2978
2978 This command writes out examination result in the style below::
2979 This command writes out examination result in the style below::
2979
2980
2980 FILE = MERGETOOL
2981 FILE = MERGETOOL
2981
2982
2982 By default, all files known in the first parent context of the
2983 By default, all files known in the first parent context of the
2983 working directory are examined. Use file patterns and/or -I/-X
2984 working directory are examined. Use file patterns and/or -I/-X
2984 options to limit target files. -r/--rev is also useful to examine
2985 options to limit target files. -r/--rev is also useful to examine
2985 files in another context without actual updating to it.
2986 files in another context without actual updating to it.
2986
2987
2987 With --debug, this command shows warning messages while matching
2988 With --debug, this command shows warning messages while matching
2988 against ``merge-patterns`` and so on, too. It is recommended to
2989 against ``merge-patterns`` and so on, too. It is recommended to
2989 use this option with explicit file patterns and/or -I/-X options,
2990 use this option with explicit file patterns and/or -I/-X options,
2990 because this option increases amount of output per file according
2991 because this option increases amount of output per file according
2991 to configurations in hgrc.
2992 to configurations in hgrc.
2992
2993
2993 With -v/--verbose, this command shows configurations below at
2994 With -v/--verbose, this command shows configurations below at
2994 first (only if specified).
2995 first (only if specified).
2995
2996
2996 - ``--tool`` option
2997 - ``--tool`` option
2997 - ``HGMERGE`` environment variable
2998 - ``HGMERGE`` environment variable
2998 - configuration of ``ui.merge``
2999 - configuration of ``ui.merge``
2999
3000
3000 If merge tool is chosen before matching against
3001 If merge tool is chosen before matching against
3001 ``merge-patterns``, this command can't show any helpful
3002 ``merge-patterns``, this command can't show any helpful
3002 information, even with --debug. In such case, information above is
3003 information, even with --debug. In such case, information above is
3003 useful to know why a merge tool is chosen.
3004 useful to know why a merge tool is chosen.
3004 """
3005 """
3005 opts = pycompat.byteskwargs(opts)
3006 opts = pycompat.byteskwargs(opts)
3006 overrides = {}
3007 overrides = {}
3007 if opts[b'tool']:
3008 if opts[b'tool']:
3008 overrides[(b'ui', b'forcemerge')] = opts[b'tool']
3009 overrides[(b'ui', b'forcemerge')] = opts[b'tool']
3009 ui.notenoi18n(b'with --tool %r\n' % (pycompat.bytestr(opts[b'tool'])))
3010 ui.notenoi18n(b'with --tool %r\n' % (pycompat.bytestr(opts[b'tool'])))
3010
3011
3011 with ui.configoverride(overrides, b'debugmergepatterns'):
3012 with ui.configoverride(overrides, b'debugmergepatterns'):
3012 hgmerge = encoding.environ.get(b"HGMERGE")
3013 hgmerge = encoding.environ.get(b"HGMERGE")
3013 if hgmerge is not None:
3014 if hgmerge is not None:
3014 ui.notenoi18n(b'with HGMERGE=%r\n' % (pycompat.bytestr(hgmerge)))
3015 ui.notenoi18n(b'with HGMERGE=%r\n' % (pycompat.bytestr(hgmerge)))
3015 uimerge = ui.config(b"ui", b"merge")
3016 uimerge = ui.config(b"ui", b"merge")
3016 if uimerge:
3017 if uimerge:
3017 ui.notenoi18n(b'with ui.merge=%r\n' % (pycompat.bytestr(uimerge)))
3018 ui.notenoi18n(b'with ui.merge=%r\n' % (pycompat.bytestr(uimerge)))
3018
3019
3019 ctx = scmutil.revsingle(repo, opts.get(b'rev'))
3020 ctx = scmutil.revsingle(repo, opts.get(b'rev'))
3020 m = scmutil.match(ctx, pats, opts)
3021 m = scmutil.match(ctx, pats, opts)
3021 changedelete = opts[b'changedelete']
3022 changedelete = opts[b'changedelete']
3022 for path in ctx.walk(m):
3023 for path in ctx.walk(m):
3023 fctx = ctx[path]
3024 fctx = ctx[path]
3024 with ui.silent(
3025 with ui.silent(
3025 error=True
3026 error=True
3026 ) if not ui.debugflag else util.nullcontextmanager():
3027 ) if not ui.debugflag else util.nullcontextmanager():
3027 tool, toolpath = filemerge._picktool(
3028 tool, toolpath = filemerge._picktool(
3028 repo,
3029 repo,
3029 ui,
3030 ui,
3030 path,
3031 path,
3031 fctx.isbinary(),
3032 fctx.isbinary(),
3032 b'l' in fctx.flags(),
3033 b'l' in fctx.flags(),
3033 changedelete,
3034 changedelete,
3034 )
3035 )
3035 ui.write(b'%s = %s\n' % (path, tool))
3036 ui.write(b'%s = %s\n' % (path, tool))
3036
3037
3037
3038
3038 @command(b'debugpushkey', [], _(b'REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
3039 @command(b'debugpushkey', [], _(b'REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
3039 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
3040 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
3040 """access the pushkey key/value protocol
3041 """access the pushkey key/value protocol
3041
3042
3042 With two args, list the keys in the given namespace.
3043 With two args, list the keys in the given namespace.
3043
3044
3044 With five args, set a key to new if it currently is set to old.
3045 With five args, set a key to new if it currently is set to old.
3045 Reports success or failure.
3046 Reports success or failure.
3046 """
3047 """
3047
3048
3048 target = hg.peer(ui, {}, repopath)
3049 target = hg.peer(ui, {}, repopath)
3049 try:
3050 try:
3050 if keyinfo:
3051 if keyinfo:
3051 key, old, new = keyinfo
3052 key, old, new = keyinfo
3052 with target.commandexecutor() as e:
3053 with target.commandexecutor() as e:
3053 r = e.callcommand(
3054 r = e.callcommand(
3054 b'pushkey',
3055 b'pushkey',
3055 {
3056 {
3056 b'namespace': namespace,
3057 b'namespace': namespace,
3057 b'key': key,
3058 b'key': key,
3058 b'old': old,
3059 b'old': old,
3059 b'new': new,
3060 b'new': new,
3060 },
3061 },
3061 ).result()
3062 ).result()
3062
3063
3063 ui.status(pycompat.bytestr(r) + b'\n')
3064 ui.status(pycompat.bytestr(r) + b'\n')
3064 return not r
3065 return not r
3065 else:
3066 else:
3066 for k, v in sorted(target.listkeys(namespace).items()):
3067 for k, v in sorted(target.listkeys(namespace).items()):
3067 ui.write(
3068 ui.write(
3068 b"%s\t%s\n"
3069 b"%s\t%s\n"
3069 % (stringutil.escapestr(k), stringutil.escapestr(v))
3070 % (stringutil.escapestr(k), stringutil.escapestr(v))
3070 )
3071 )
3071 finally:
3072 finally:
3072 target.close()
3073 target.close()
3073
3074
3074
3075
3075 @command(b'debugpvec', [], _(b'A B'))
3076 @command(b'debugpvec', [], _(b'A B'))
3076 def debugpvec(ui, repo, a, b=None):
3077 def debugpvec(ui, repo, a, b=None):
3077 ca = scmutil.revsingle(repo, a)
3078 ca = scmutil.revsingle(repo, a)
3078 cb = scmutil.revsingle(repo, b)
3079 cb = scmutil.revsingle(repo, b)
3079 pa = pvec.ctxpvec(ca)
3080 pa = pvec.ctxpvec(ca)
3080 pb = pvec.ctxpvec(cb)
3081 pb = pvec.ctxpvec(cb)
3081 if pa == pb:
3082 if pa == pb:
3082 rel = b"="
3083 rel = b"="
3083 elif pa > pb:
3084 elif pa > pb:
3084 rel = b">"
3085 rel = b">"
3085 elif pa < pb:
3086 elif pa < pb:
3086 rel = b"<"
3087 rel = b"<"
3087 elif pa | pb:
3088 elif pa | pb:
3088 rel = b"|"
3089 rel = b"|"
3089 ui.write(_(b"a: %s\n") % pa)
3090 ui.write(_(b"a: %s\n") % pa)
3090 ui.write(_(b"b: %s\n") % pb)
3091 ui.write(_(b"b: %s\n") % pb)
3091 ui.write(_(b"depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
3092 ui.write(_(b"depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
3092 ui.write(
3093 ui.write(
3093 _(b"delta: %d hdist: %d distance: %d relation: %s\n")
3094 _(b"delta: %d hdist: %d distance: %d relation: %s\n")
3094 % (
3095 % (
3095 abs(pa._depth - pb._depth),
3096 abs(pa._depth - pb._depth),
3096 pvec._hamming(pa._vec, pb._vec),
3097 pvec._hamming(pa._vec, pb._vec),
3097 pa.distance(pb),
3098 pa.distance(pb),
3098 rel,
3099 rel,
3099 )
3100 )
3100 )
3101 )
3101
3102
3102
3103
3103 @command(
3104 @command(
3104 b'debugrebuilddirstate|debugrebuildstate',
3105 b'debugrebuilddirstate|debugrebuildstate',
3105 [
3106 [
3106 (b'r', b'rev', b'', _(b'revision to rebuild to'), _(b'REV')),
3107 (b'r', b'rev', b'', _(b'revision to rebuild to'), _(b'REV')),
3107 (
3108 (
3108 b'',
3109 b'',
3109 b'minimal',
3110 b'minimal',
3110 None,
3111 None,
3111 _(
3112 _(
3112 b'only rebuild files that are inconsistent with '
3113 b'only rebuild files that are inconsistent with '
3113 b'the working copy parent'
3114 b'the working copy parent'
3114 ),
3115 ),
3115 ),
3116 ),
3116 ],
3117 ],
3117 _(b'[-r REV]'),
3118 _(b'[-r REV]'),
3118 )
3119 )
3119 def debugrebuilddirstate(ui, repo, rev, **opts):
3120 def debugrebuilddirstate(ui, repo, rev, **opts):
3120 """rebuild the dirstate as it would look like for the given revision
3121 """rebuild the dirstate as it would look like for the given revision
3121
3122
3122 If no revision is specified the first current parent will be used.
3123 If no revision is specified the first current parent will be used.
3123
3124
3124 The dirstate will be set to the files of the given revision.
3125 The dirstate will be set to the files of the given revision.
3125 The actual working directory content or existing dirstate
3126 The actual working directory content or existing dirstate
3126 information such as adds or removes is not considered.
3127 information such as adds or removes is not considered.
3127
3128
3128 ``minimal`` will only rebuild the dirstate status for files that claim to be
3129 ``minimal`` will only rebuild the dirstate status for files that claim to be
3129 tracked but are not in the parent manifest, or that exist in the parent
3130 tracked but are not in the parent manifest, or that exist in the parent
3130 manifest but are not in the dirstate. It will not change adds, removes, or
3131 manifest but are not in the dirstate. It will not change adds, removes, or
3131 modified files that are in the working copy parent.
3132 modified files that are in the working copy parent.
3132
3133
3133 One use of this command is to make the next :hg:`status` invocation
3134 One use of this command is to make the next :hg:`status` invocation
3134 check the actual file content.
3135 check the actual file content.
3135 """
3136 """
3136 ctx = scmutil.revsingle(repo, rev)
3137 ctx = scmutil.revsingle(repo, rev)
3137 with repo.wlock():
3138 with repo.wlock():
3138 if repo.currenttransaction() is not None:
3139 if repo.currenttransaction() is not None:
3139 msg = b'rebuild the dirstate outside of a transaction'
3140 msg = b'rebuild the dirstate outside of a transaction'
3140 raise error.ProgrammingError(msg)
3141 raise error.ProgrammingError(msg)
3141 dirstate = repo.dirstate
3142 dirstate = repo.dirstate
3142 changedfiles = None
3143 changedfiles = None
3143 # See command doc for what minimal does.
3144 # See command doc for what minimal does.
3144 if opts.get('minimal'):
3145 if opts.get('minimal'):
3145 manifestfiles = set(ctx.manifest().keys())
3146 manifestfiles = set(ctx.manifest().keys())
3146 dirstatefiles = set(dirstate)
3147 dirstatefiles = set(dirstate)
3147 manifestonly = manifestfiles - dirstatefiles
3148 manifestonly = manifestfiles - dirstatefiles
3148 dsonly = dirstatefiles - manifestfiles
3149 dsonly = dirstatefiles - manifestfiles
3149 dsnotadded = {f for f in dsonly if not dirstate.get_entry(f).added}
3150 dsnotadded = {f for f in dsonly if not dirstate.get_entry(f).added}
3150 changedfiles = manifestonly | dsnotadded
3151 changedfiles = manifestonly | dsnotadded
3151
3152
3152 with dirstate.changing_parents(repo):
3153 with dirstate.changing_parents(repo):
3153 dirstate.rebuild(ctx.node(), ctx.manifest(), changedfiles)
3154 dirstate.rebuild(ctx.node(), ctx.manifest(), changedfiles)
3154
3155
3155
3156
3156 @command(
3157 @command(
3157 b'debugrebuildfncache',
3158 b'debugrebuildfncache',
3158 [
3159 [
3159 (
3160 (
3160 b'',
3161 b'',
3161 b'only-data',
3162 b'only-data',
3162 False,
3163 False,
3163 _(b'only look for wrong .d files (much faster)'),
3164 _(b'only look for wrong .d files (much faster)'),
3164 )
3165 )
3165 ],
3166 ],
3166 b'',
3167 b'',
3167 )
3168 )
3168 def debugrebuildfncache(ui, repo, **opts):
3169 def debugrebuildfncache(ui, repo, **opts):
3169 """rebuild the fncache file"""
3170 """rebuild the fncache file"""
3170 opts = pycompat.byteskwargs(opts)
3171 opts = pycompat.byteskwargs(opts)
3171 repair.rebuildfncache(ui, repo, opts.get(b"only_data"))
3172 repair.rebuildfncache(ui, repo, opts.get(b"only_data"))
3172
3173
3173
3174
3174 @command(
3175 @command(
3175 b'debugrename',
3176 b'debugrename',
3176 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
3177 [(b'r', b'rev', b'', _(b'revision to debug'), _(b'REV'))],
3177 _(b'[-r REV] [FILE]...'),
3178 _(b'[-r REV] [FILE]...'),
3178 )
3179 )
3179 def debugrename(ui, repo, *pats, **opts):
3180 def debugrename(ui, repo, *pats, **opts):
3180 """dump rename information"""
3181 """dump rename information"""
3181
3182
3182 opts = pycompat.byteskwargs(opts)
3183 opts = pycompat.byteskwargs(opts)
3183 ctx = scmutil.revsingle(repo, opts.get(b'rev'))
3184 ctx = scmutil.revsingle(repo, opts.get(b'rev'))
3184 m = scmutil.match(ctx, pats, opts)
3185 m = scmutil.match(ctx, pats, opts)
3185 for abs in ctx.walk(m):
3186 for abs in ctx.walk(m):
3186 fctx = ctx[abs]
3187 fctx = ctx[abs]
3187 o = fctx.filelog().renamed(fctx.filenode())
3188 o = fctx.filelog().renamed(fctx.filenode())
3188 rel = repo.pathto(abs)
3189 rel = repo.pathto(abs)
3189 if o:
3190 if o:
3190 ui.write(_(b"%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
3191 ui.write(_(b"%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
3191 else:
3192 else:
3192 ui.write(_(b"%s not renamed\n") % rel)
3193 ui.write(_(b"%s not renamed\n") % rel)
3193
3194
3194
3195
3195 @command(b'debugrequires|debugrequirements', [], b'')
3196 @command(b'debugrequires|debugrequirements', [], b'')
3196 def debugrequirements(ui, repo):
3197 def debugrequirements(ui, repo):
3197 """print the current repo requirements"""
3198 """print the current repo requirements"""
3198 for r in sorted(repo.requirements):
3199 for r in sorted(repo.requirements):
3199 ui.write(b"%s\n" % r)
3200 ui.write(b"%s\n" % r)
3200
3201
3201
3202
3202 @command(
3203 @command(
3203 b'debugrevlog',
3204 b'debugrevlog',
3204 cmdutil.debugrevlogopts + [(b'd', b'dump', False, _(b'dump index data'))],
3205 cmdutil.debugrevlogopts + [(b'd', b'dump', False, _(b'dump index data'))],
3205 _(b'-c|-m|FILE'),
3206 _(b'-c|-m|FILE'),
3206 optionalrepo=True,
3207 optionalrepo=True,
3207 )
3208 )
3208 def debugrevlog(ui, repo, file_=None, **opts):
3209 def debugrevlog(ui, repo, file_=None, **opts):
3209 """show data and statistics about a revlog"""
3210 """show data and statistics about a revlog"""
3210 opts = pycompat.byteskwargs(opts)
3211 opts = pycompat.byteskwargs(opts)
3211 r = cmdutil.openrevlog(repo, b'debugrevlog', file_, opts)
3212 r = cmdutil.openrevlog(repo, b'debugrevlog', file_, opts)
3212
3213
3213 if opts.get(b"dump"):
3214 if opts.get(b"dump"):
3214 revlog_debug.dump(ui, r)
3215 revlog_debug.dump(ui, r)
3215 else:
3216 else:
3216 revlog_debug.debug_revlog(ui, r)
3217 revlog_debug.debug_revlog(ui, r)
3217 return 0
3218 return 0
3218
3219
3219
3220
3220 @command(
3221 @command(
3221 b'debugrevlogindex',
3222 b'debugrevlogindex',
3222 cmdutil.debugrevlogopts
3223 cmdutil.debugrevlogopts
3223 + [(b'f', b'format', 0, _(b'revlog format'), _(b'FORMAT'))],
3224 + [(b'f', b'format', 0, _(b'revlog format'), _(b'FORMAT'))],
3224 _(b'[-f FORMAT] -c|-m|FILE'),
3225 _(b'[-f FORMAT] -c|-m|FILE'),
3225 optionalrepo=True,
3226 optionalrepo=True,
3226 )
3227 )
3227 def debugrevlogindex(ui, repo, file_=None, **opts):
3228 def debugrevlogindex(ui, repo, file_=None, **opts):
3228 """dump the contents of a revlog index"""
3229 """dump the contents of a revlog index"""
3229 opts = pycompat.byteskwargs(opts)
3230 opts = pycompat.byteskwargs(opts)
3230 r = cmdutil.openrevlog(repo, b'debugrevlogindex', file_, opts)
3231 r = cmdutil.openrevlog(repo, b'debugrevlogindex', file_, opts)
3231 format = opts.get(b'format', 0)
3232 format = opts.get(b'format', 0)
3232 if format not in (0, 1):
3233 if format not in (0, 1):
3233 raise error.Abort(_(b"unknown format %d") % format)
3234 raise error.Abort(_(b"unknown format %d") % format)
3234
3235
3235 if ui.debugflag:
3236 if ui.debugflag:
3236 shortfn = hex
3237 shortfn = hex
3237 else:
3238 else:
3238 shortfn = short
3239 shortfn = short
3239
3240
3240 # There might not be anything in r, so have a sane default
3241 # There might not be anything in r, so have a sane default
3241 idlen = 12
3242 idlen = 12
3242 for i in r:
3243 for i in r:
3243 idlen = len(shortfn(r.node(i)))
3244 idlen = len(shortfn(r.node(i)))
3244 break
3245 break
3245
3246
3246 if format == 0:
3247 if format == 0:
3247 if ui.verbose:
3248 if ui.verbose:
3248 ui.writenoi18n(
3249 ui.writenoi18n(
3249 b" rev offset length linkrev %s %s p2\n"
3250 b" rev offset length linkrev %s %s p2\n"
3250 % (b"nodeid".ljust(idlen), b"p1".ljust(idlen))
3251 % (b"nodeid".ljust(idlen), b"p1".ljust(idlen))
3251 )
3252 )
3252 else:
3253 else:
3253 ui.writenoi18n(
3254 ui.writenoi18n(
3254 b" rev linkrev %s %s p2\n"
3255 b" rev linkrev %s %s p2\n"
3255 % (b"nodeid".ljust(idlen), b"p1".ljust(idlen))
3256 % (b"nodeid".ljust(idlen), b"p1".ljust(idlen))
3256 )
3257 )
3257 elif format == 1:
3258 elif format == 1:
3258 if ui.verbose:
3259 if ui.verbose:
3259 ui.writenoi18n(
3260 ui.writenoi18n(
3260 (
3261 (
3261 b" rev flag offset length size link p1"
3262 b" rev flag offset length size link p1"
3262 b" p2 %s\n"
3263 b" p2 %s\n"
3263 )
3264 )
3264 % b"nodeid".rjust(idlen)
3265 % b"nodeid".rjust(idlen)
3265 )
3266 )
3266 else:
3267 else:
3267 ui.writenoi18n(
3268 ui.writenoi18n(
3268 b" rev flag size link p1 p2 %s\n"
3269 b" rev flag size link p1 p2 %s\n"
3269 % b"nodeid".rjust(idlen)
3270 % b"nodeid".rjust(idlen)
3270 )
3271 )
3271
3272
3272 for i in r:
3273 for i in r:
3273 node = r.node(i)
3274 node = r.node(i)
3274 if format == 0:
3275 if format == 0:
3275 try:
3276 try:
3276 pp = r.parents(node)
3277 pp = r.parents(node)
3277 except Exception:
3278 except Exception:
3278 pp = [repo.nullid, repo.nullid]
3279 pp = [repo.nullid, repo.nullid]
3279 if ui.verbose:
3280 if ui.verbose:
3280 ui.write(
3281 ui.write(
3281 b"% 6d % 9d % 7d % 7d %s %s %s\n"
3282 b"% 6d % 9d % 7d % 7d %s %s %s\n"
3282 % (
3283 % (
3283 i,
3284 i,
3284 r.start(i),
3285 r.start(i),
3285 r.length(i),
3286 r.length(i),
3286 r.linkrev(i),
3287 r.linkrev(i),
3287 shortfn(node),
3288 shortfn(node),
3288 shortfn(pp[0]),
3289 shortfn(pp[0]),
3289 shortfn(pp[1]),
3290 shortfn(pp[1]),
3290 )
3291 )
3291 )
3292 )
3292 else:
3293 else:
3293 ui.write(
3294 ui.write(
3294 b"% 6d % 7d %s %s %s\n"
3295 b"% 6d % 7d %s %s %s\n"
3295 % (
3296 % (
3296 i,
3297 i,
3297 r.linkrev(i),
3298 r.linkrev(i),
3298 shortfn(node),
3299 shortfn(node),
3299 shortfn(pp[0]),
3300 shortfn(pp[0]),
3300 shortfn(pp[1]),
3301 shortfn(pp[1]),
3301 )
3302 )
3302 )
3303 )
3303 elif format == 1:
3304 elif format == 1:
3304 pr = r.parentrevs(i)
3305 pr = r.parentrevs(i)
3305 if ui.verbose:
3306 if ui.verbose:
3306 ui.write(
3307 ui.write(
3307 b"% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d %s\n"
3308 b"% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d %s\n"
3308 % (
3309 % (
3309 i,
3310 i,
3310 r.flags(i),
3311 r.flags(i),
3311 r.start(i),
3312 r.start(i),
3312 r.length(i),
3313 r.length(i),
3313 r.rawsize(i),
3314 r.rawsize(i),
3314 r.linkrev(i),
3315 r.linkrev(i),
3315 pr[0],
3316 pr[0],
3316 pr[1],
3317 pr[1],
3317 shortfn(node),
3318 shortfn(node),
3318 )
3319 )
3319 )
3320 )
3320 else:
3321 else:
3321 ui.write(
3322 ui.write(
3322 b"% 6d %04x % 8d % 6d % 6d % 6d %s\n"
3323 b"% 6d %04x % 8d % 6d % 6d % 6d %s\n"
3323 % (
3324 % (
3324 i,
3325 i,
3325 r.flags(i),
3326 r.flags(i),
3326 r.rawsize(i),
3327 r.rawsize(i),
3327 r.linkrev(i),
3328 r.linkrev(i),
3328 pr[0],
3329 pr[0],
3329 pr[1],
3330 pr[1],
3330 shortfn(node),
3331 shortfn(node),
3331 )
3332 )
3332 )
3333 )
3333
3334
3334
3335
3335 @command(
3336 @command(
3336 b'debugrevspec',
3337 b'debugrevspec',
3337 [
3338 [
3338 (
3339 (
3339 b'',
3340 b'',
3340 b'optimize',
3341 b'optimize',
3341 None,
3342 None,
3342 _(b'print parsed tree after optimizing (DEPRECATED)'),
3343 _(b'print parsed tree after optimizing (DEPRECATED)'),
3343 ),
3344 ),
3344 (
3345 (
3345 b'',
3346 b'',
3346 b'show-revs',
3347 b'show-revs',
3347 True,
3348 True,
3348 _(b'print list of result revisions (default)'),
3349 _(b'print list of result revisions (default)'),
3349 ),
3350 ),
3350 (
3351 (
3351 b's',
3352 b's',
3352 b'show-set',
3353 b'show-set',
3353 None,
3354 None,
3354 _(b'print internal representation of result set'),
3355 _(b'print internal representation of result set'),
3355 ),
3356 ),
3356 (
3357 (
3357 b'p',
3358 b'p',
3358 b'show-stage',
3359 b'show-stage',
3359 [],
3360 [],
3360 _(b'print parsed tree at the given stage'),
3361 _(b'print parsed tree at the given stage'),
3361 _(b'NAME'),
3362 _(b'NAME'),
3362 ),
3363 ),
3363 (b'', b'no-optimized', False, _(b'evaluate tree without optimization')),
3364 (b'', b'no-optimized', False, _(b'evaluate tree without optimization')),
3364 (b'', b'verify-optimized', False, _(b'verify optimized result')),
3365 (b'', b'verify-optimized', False, _(b'verify optimized result')),
3365 ],
3366 ],
3366 b'REVSPEC',
3367 b'REVSPEC',
3367 )
3368 )
3368 def debugrevspec(ui, repo, expr, **opts):
3369 def debugrevspec(ui, repo, expr, **opts):
3369 """parse and apply a revision specification
3370 """parse and apply a revision specification
3370
3371
3371 Use -p/--show-stage option to print the parsed tree at the given stages.
3372 Use -p/--show-stage option to print the parsed tree at the given stages.
3372 Use -p all to print tree at every stage.
3373 Use -p all to print tree at every stage.
3373
3374
3374 Use --no-show-revs option with -s or -p to print only the set
3375 Use --no-show-revs option with -s or -p to print only the set
3375 representation or the parsed tree respectively.
3376 representation or the parsed tree respectively.
3376
3377
3377 Use --verify-optimized to compare the optimized result with the unoptimized
3378 Use --verify-optimized to compare the optimized result with the unoptimized
3378 one. Returns 1 if the optimized result differs.
3379 one. Returns 1 if the optimized result differs.
3379 """
3380 """
3380 opts = pycompat.byteskwargs(opts)
3381 opts = pycompat.byteskwargs(opts)
3381 aliases = ui.configitems(b'revsetalias')
3382 aliases = ui.configitems(b'revsetalias')
3382 stages = [
3383 stages = [
3383 (b'parsed', lambda tree: tree),
3384 (b'parsed', lambda tree: tree),
3384 (
3385 (
3385 b'expanded',
3386 b'expanded',
3386 lambda tree: revsetlang.expandaliases(tree, aliases, ui.warn),
3387 lambda tree: revsetlang.expandaliases(tree, aliases, ui.warn),
3387 ),
3388 ),
3388 (b'concatenated', revsetlang.foldconcat),
3389 (b'concatenated', revsetlang.foldconcat),
3389 (b'analyzed', revsetlang.analyze),
3390 (b'analyzed', revsetlang.analyze),
3390 (b'optimized', revsetlang.optimize),
3391 (b'optimized', revsetlang.optimize),
3391 ]
3392 ]
3392 if opts[b'no_optimized']:
3393 if opts[b'no_optimized']:
3393 stages = stages[:-1]
3394 stages = stages[:-1]
3394 if opts[b'verify_optimized'] and opts[b'no_optimized']:
3395 if opts[b'verify_optimized'] and opts[b'no_optimized']:
3395 raise error.Abort(
3396 raise error.Abort(
3396 _(b'cannot use --verify-optimized with --no-optimized')
3397 _(b'cannot use --verify-optimized with --no-optimized')
3397 )
3398 )
3398 stagenames = {n for n, f in stages}
3399 stagenames = {n for n, f in stages}
3399
3400
3400 showalways = set()
3401 showalways = set()
3401 showchanged = set()
3402 showchanged = set()
3402 if ui.verbose and not opts[b'show_stage']:
3403 if ui.verbose and not opts[b'show_stage']:
3403 # show parsed tree by --verbose (deprecated)
3404 # show parsed tree by --verbose (deprecated)
3404 showalways.add(b'parsed')
3405 showalways.add(b'parsed')
3405 showchanged.update([b'expanded', b'concatenated'])
3406 showchanged.update([b'expanded', b'concatenated'])
3406 if opts[b'optimize']:
3407 if opts[b'optimize']:
3407 showalways.add(b'optimized')
3408 showalways.add(b'optimized')
3408 if opts[b'show_stage'] and opts[b'optimize']:
3409 if opts[b'show_stage'] and opts[b'optimize']:
3409 raise error.Abort(_(b'cannot use --optimize with --show-stage'))
3410 raise error.Abort(_(b'cannot use --optimize with --show-stage'))
3410 if opts[b'show_stage'] == [b'all']:
3411 if opts[b'show_stage'] == [b'all']:
3411 showalways.update(stagenames)
3412 showalways.update(stagenames)
3412 else:
3413 else:
3413 for n in opts[b'show_stage']:
3414 for n in opts[b'show_stage']:
3414 if n not in stagenames:
3415 if n not in stagenames:
3415 raise error.Abort(_(b'invalid stage name: %s') % n)
3416 raise error.Abort(_(b'invalid stage name: %s') % n)
3416 showalways.update(opts[b'show_stage'])
3417 showalways.update(opts[b'show_stage'])
3417
3418
3418 treebystage = {}
3419 treebystage = {}
3419 printedtree = None
3420 printedtree = None
3420 tree = revsetlang.parse(expr, lookup=revset.lookupfn(repo))
3421 tree = revsetlang.parse(expr, lookup=revset.lookupfn(repo))
3421 for n, f in stages:
3422 for n, f in stages:
3422 treebystage[n] = tree = f(tree)
3423 treebystage[n] = tree = f(tree)
3423 if n in showalways or (n in showchanged and tree != printedtree):
3424 if n in showalways or (n in showchanged and tree != printedtree):
3424 if opts[b'show_stage'] or n != b'parsed':
3425 if opts[b'show_stage'] or n != b'parsed':
3425 ui.write(b"* %s:\n" % n)
3426 ui.write(b"* %s:\n" % n)
3426 ui.write(revsetlang.prettyformat(tree), b"\n")
3427 ui.write(revsetlang.prettyformat(tree), b"\n")
3427 printedtree = tree
3428 printedtree = tree
3428
3429
3429 if opts[b'verify_optimized']:
3430 if opts[b'verify_optimized']:
3430 arevs = revset.makematcher(treebystage[b'analyzed'])(repo)
3431 arevs = revset.makematcher(treebystage[b'analyzed'])(repo)
3431 brevs = revset.makematcher(treebystage[b'optimized'])(repo)
3432 brevs = revset.makematcher(treebystage[b'optimized'])(repo)
3432 if opts[b'show_set'] or (opts[b'show_set'] is None and ui.verbose):
3433 if opts[b'show_set'] or (opts[b'show_set'] is None and ui.verbose):
3433 ui.writenoi18n(
3434 ui.writenoi18n(
3434 b"* analyzed set:\n", stringutil.prettyrepr(arevs), b"\n"
3435 b"* analyzed set:\n", stringutil.prettyrepr(arevs), b"\n"
3435 )
3436 )
3436 ui.writenoi18n(
3437 ui.writenoi18n(
3437 b"* optimized set:\n", stringutil.prettyrepr(brevs), b"\n"
3438 b"* optimized set:\n", stringutil.prettyrepr(brevs), b"\n"
3438 )
3439 )
3439 arevs = list(arevs)
3440 arevs = list(arevs)
3440 brevs = list(brevs)
3441 brevs = list(brevs)
3441 if arevs == brevs:
3442 if arevs == brevs:
3442 return 0
3443 return 0
3443 ui.writenoi18n(b'--- analyzed\n', label=b'diff.file_a')
3444 ui.writenoi18n(b'--- analyzed\n', label=b'diff.file_a')
3444 ui.writenoi18n(b'+++ optimized\n', label=b'diff.file_b')
3445 ui.writenoi18n(b'+++ optimized\n', label=b'diff.file_b')
3445 sm = difflib.SequenceMatcher(None, arevs, brevs)
3446 sm = difflib.SequenceMatcher(None, arevs, brevs)
3446 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3447 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3447 if tag in ('delete', 'replace'):
3448 if tag in ('delete', 'replace'):
3448 for c in arevs[alo:ahi]:
3449 for c in arevs[alo:ahi]:
3449 ui.write(b'-%d\n' % c, label=b'diff.deleted')
3450 ui.write(b'-%d\n' % c, label=b'diff.deleted')
3450 if tag in ('insert', 'replace'):
3451 if tag in ('insert', 'replace'):
3451 for c in brevs[blo:bhi]:
3452 for c in brevs[blo:bhi]:
3452 ui.write(b'+%d\n' % c, label=b'diff.inserted')
3453 ui.write(b'+%d\n' % c, label=b'diff.inserted')
3453 if tag == 'equal':
3454 if tag == 'equal':
3454 for c in arevs[alo:ahi]:
3455 for c in arevs[alo:ahi]:
3455 ui.write(b' %d\n' % c)
3456 ui.write(b' %d\n' % c)
3456 return 1
3457 return 1
3457
3458
3458 func = revset.makematcher(tree)
3459 func = revset.makematcher(tree)
3459 revs = func(repo)
3460 revs = func(repo)
3460 if opts[b'show_set'] or (opts[b'show_set'] is None and ui.verbose):
3461 if opts[b'show_set'] or (opts[b'show_set'] is None and ui.verbose):
3461 ui.writenoi18n(b"* set:\n", stringutil.prettyrepr(revs), b"\n")
3462 ui.writenoi18n(b"* set:\n", stringutil.prettyrepr(revs), b"\n")
3462 if not opts[b'show_revs']:
3463 if not opts[b'show_revs']:
3463 return
3464 return
3464 for c in revs:
3465 for c in revs:
3465 ui.write(b"%d\n" % c)
3466 ui.write(b"%d\n" % c)
3466
3467
3467
3468
3468 @command(
3469 @command(
3469 b'debugserve',
3470 b'debugserve',
3470 [
3471 [
3471 (
3472 (
3472 b'',
3473 b'',
3473 b'sshstdio',
3474 b'sshstdio',
3474 False,
3475 False,
3475 _(b'run an SSH server bound to process handles'),
3476 _(b'run an SSH server bound to process handles'),
3476 ),
3477 ),
3477 (b'', b'logiofd', b'', _(b'file descriptor to log server I/O to')),
3478 (b'', b'logiofd', b'', _(b'file descriptor to log server I/O to')),
3478 (b'', b'logiofile', b'', _(b'file to log server I/O to')),
3479 (b'', b'logiofile', b'', _(b'file to log server I/O to')),
3479 ],
3480 ],
3480 b'',
3481 b'',
3481 )
3482 )
3482 def debugserve(ui, repo, **opts):
3483 def debugserve(ui, repo, **opts):
3483 """run a server with advanced settings
3484 """run a server with advanced settings
3484
3485
3485 This command is similar to :hg:`serve`. It exists partially as a
3486 This command is similar to :hg:`serve`. It exists partially as a
3486 workaround to the fact that ``hg serve --stdio`` must have specific
3487 workaround to the fact that ``hg serve --stdio`` must have specific
3487 arguments for security reasons.
3488 arguments for security reasons.
3488 """
3489 """
3489 opts = pycompat.byteskwargs(opts)
3490 opts = pycompat.byteskwargs(opts)
3490
3491
3491 if not opts[b'sshstdio']:
3492 if not opts[b'sshstdio']:
3492 raise error.Abort(_(b'only --sshstdio is currently supported'))
3493 raise error.Abort(_(b'only --sshstdio is currently supported'))
3493
3494
3494 logfh = None
3495 logfh = None
3495
3496
3496 if opts[b'logiofd'] and opts[b'logiofile']:
3497 if opts[b'logiofd'] and opts[b'logiofile']:
3497 raise error.Abort(_(b'cannot use both --logiofd and --logiofile'))
3498 raise error.Abort(_(b'cannot use both --logiofd and --logiofile'))
3498
3499
3499 if opts[b'logiofd']:
3500 if opts[b'logiofd']:
3500 # Ideally we would be line buffered. But line buffering in binary
3501 # Ideally we would be line buffered. But line buffering in binary
3501 # mode isn't supported and emits a warning in Python 3.8+. Disabling
3502 # mode isn't supported and emits a warning in Python 3.8+. Disabling
3502 # buffering could have performance impacts. But since this isn't
3503 # buffering could have performance impacts. But since this isn't
3503 # performance critical code, it should be fine.
3504 # performance critical code, it should be fine.
3504 try:
3505 try:
3505 logfh = os.fdopen(int(opts[b'logiofd']), 'ab', 0)
3506 logfh = os.fdopen(int(opts[b'logiofd']), 'ab', 0)
3506 except OSError as e:
3507 except OSError as e:
3507 if e.errno != errno.ESPIPE:
3508 if e.errno != errno.ESPIPE:
3508 raise
3509 raise
3509 # can't seek a pipe, so `ab` mode fails on py3
3510 # can't seek a pipe, so `ab` mode fails on py3
3510 logfh = os.fdopen(int(opts[b'logiofd']), 'wb', 0)
3511 logfh = os.fdopen(int(opts[b'logiofd']), 'wb', 0)
3511 elif opts[b'logiofile']:
3512 elif opts[b'logiofile']:
3512 logfh = open(opts[b'logiofile'], b'ab', 0)
3513 logfh = open(opts[b'logiofile'], b'ab', 0)
3513
3514
3514 s = wireprotoserver.sshserver(ui, repo, logfh=logfh)
3515 s = wireprotoserver.sshserver(ui, repo, logfh=logfh)
3515 s.serve_forever()
3516 s.serve_forever()
3516
3517
3517
3518
3518 @command(b'debugsetparents', [], _(b'REV1 [REV2]'))
3519 @command(b'debugsetparents', [], _(b'REV1 [REV2]'))
3519 def debugsetparents(ui, repo, rev1, rev2=None):
3520 def debugsetparents(ui, repo, rev1, rev2=None):
3520 """manually set the parents of the current working directory (DANGEROUS)
3521 """manually set the parents of the current working directory (DANGEROUS)
3521
3522
3522 This command is not what you are looking for and should not be used. Using
3523 This command is not what you are looking for and should not be used. Using
3523 this command will most certainly results in slight corruption of the file
3524 this command will most certainly results in slight corruption of the file
3524 level histories withing your repository. DO NOT USE THIS COMMAND.
3525 level histories withing your repository. DO NOT USE THIS COMMAND.
3525
3526
3526 The command update the p1 and p2 field in the dirstate, and not touching
3527 The command update the p1 and p2 field in the dirstate, and not touching
3527 anything else. This useful for writing repository conversion tools, but
3528 anything else. This useful for writing repository conversion tools, but
3528 should be used with extreme care. For example, neither the working
3529 should be used with extreme care. For example, neither the working
3529 directory nor the dirstate is updated, so file status may be incorrect
3530 directory nor the dirstate is updated, so file status may be incorrect
3530 after running this command. Only used if you are one of the few people that
3531 after running this command. Only used if you are one of the few people that
3531 deeply unstand both conversion tools and file level histories. If you are
3532 deeply unstand both conversion tools and file level histories. If you are
3532 reading this help, you are not one of this people (most of them sailed west
3533 reading this help, you are not one of this people (most of them sailed west
3533 from Mithlond anyway.
3534 from Mithlond anyway.
3534
3535
3535 So one last time DO NOT USE THIS COMMAND.
3536 So one last time DO NOT USE THIS COMMAND.
3536
3537
3537 Returns 0 on success.
3538 Returns 0 on success.
3538 """
3539 """
3539
3540
3540 node1 = scmutil.revsingle(repo, rev1).node()
3541 node1 = scmutil.revsingle(repo, rev1).node()
3541 node2 = scmutil.revsingle(repo, rev2, b'null').node()
3542 node2 = scmutil.revsingle(repo, rev2, b'null').node()
3542
3543
3543 with repo.wlock():
3544 with repo.wlock():
3544 repo.setparents(node1, node2)
3545 repo.setparents(node1, node2)
3545
3546
3546
3547
3547 @command(b'debugsidedata', cmdutil.debugrevlogopts, _(b'-c|-m|FILE REV'))
3548 @command(b'debugsidedata', cmdutil.debugrevlogopts, _(b'-c|-m|FILE REV'))
3548 def debugsidedata(ui, repo, file_, rev=None, **opts):
3549 def debugsidedata(ui, repo, file_, rev=None, **opts):
3549 """dump the side data for a cl/manifest/file revision
3550 """dump the side data for a cl/manifest/file revision
3550
3551
3551 Use --verbose to dump the sidedata content."""
3552 Use --verbose to dump the sidedata content."""
3552 opts = pycompat.byteskwargs(opts)
3553 opts = pycompat.byteskwargs(opts)
3553 if opts.get(b'changelog') or opts.get(b'manifest') or opts.get(b'dir'):
3554 if opts.get(b'changelog') or opts.get(b'manifest') or opts.get(b'dir'):
3554 if rev is not None:
3555 if rev is not None:
3555 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
3556 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
3556 file_, rev = None, file_
3557 file_, rev = None, file_
3557 elif rev is None:
3558 elif rev is None:
3558 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
3559 raise error.CommandError(b'debugdata', _(b'invalid arguments'))
3559 r = cmdutil.openstorage(repo, b'debugdata', file_, opts)
3560 r = cmdutil.openstorage(repo, b'debugdata', file_, opts)
3560 r = getattr(r, '_revlog', r)
3561 r = getattr(r, '_revlog', r)
3561 try:
3562 try:
3562 sidedata = r.sidedata(r.lookup(rev))
3563 sidedata = r.sidedata(r.lookup(rev))
3563 except KeyError:
3564 except KeyError:
3564 raise error.Abort(_(b'invalid revision identifier %s') % rev)
3565 raise error.Abort(_(b'invalid revision identifier %s') % rev)
3565 if sidedata:
3566 if sidedata:
3566 sidedata = list(sidedata.items())
3567 sidedata = list(sidedata.items())
3567 sidedata.sort()
3568 sidedata.sort()
3568 ui.writenoi18n(b'%d sidedata entries\n' % len(sidedata))
3569 ui.writenoi18n(b'%d sidedata entries\n' % len(sidedata))
3569 for key, value in sidedata:
3570 for key, value in sidedata:
3570 ui.writenoi18n(b' entry-%04o size %d\n' % (key, len(value)))
3571 ui.writenoi18n(b' entry-%04o size %d\n' % (key, len(value)))
3571 if ui.verbose:
3572 if ui.verbose:
3572 ui.writenoi18n(b' %s\n' % stringutil.pprint(value))
3573 ui.writenoi18n(b' %s\n' % stringutil.pprint(value))
3573
3574
3574
3575
3575 @command(b'debugssl', [], b'[SOURCE]', optionalrepo=True)
3576 @command(b'debugssl', [], b'[SOURCE]', optionalrepo=True)
3576 def debugssl(ui, repo, source=None, **opts):
3577 def debugssl(ui, repo, source=None, **opts):
3577 """test a secure connection to a server
3578 """test a secure connection to a server
3578
3579
3579 This builds the certificate chain for the server on Windows, installing the
3580 This builds the certificate chain for the server on Windows, installing the
3580 missing intermediates and trusted root via Windows Update if necessary. It
3581 missing intermediates and trusted root via Windows Update if necessary. It
3581 does nothing on other platforms.
3582 does nothing on other platforms.
3582
3583
3583 If SOURCE is omitted, the 'default' path will be used. If a URL is given,
3584 If SOURCE is omitted, the 'default' path will be used. If a URL is given,
3584 that server is used. See :hg:`help urls` for more information.
3585 that server is used. See :hg:`help urls` for more information.
3585
3586
3586 If the update succeeds, retry the original operation. Otherwise, the cause
3587 If the update succeeds, retry the original operation. Otherwise, the cause
3587 of the SSL error is likely another issue.
3588 of the SSL error is likely another issue.
3588 """
3589 """
3589 if not pycompat.iswindows:
3590 if not pycompat.iswindows:
3590 raise error.Abort(
3591 raise error.Abort(
3591 _(b'certificate chain building is only possible on Windows')
3592 _(b'certificate chain building is only possible on Windows')
3592 )
3593 )
3593
3594
3594 if not source:
3595 if not source:
3595 if not repo:
3596 if not repo:
3596 raise error.Abort(
3597 raise error.Abort(
3597 _(
3598 _(
3598 b"there is no Mercurial repository here, and no "
3599 b"there is no Mercurial repository here, and no "
3599 b"server specified"
3600 b"server specified"
3600 )
3601 )
3601 )
3602 )
3602 source = b"default"
3603 source = b"default"
3603
3604
3604 path = urlutil.get_unique_pull_path_obj(b'debugssl', ui, source)
3605 path = urlutil.get_unique_pull_path_obj(b'debugssl', ui, source)
3605 url = path.url
3606 url = path.url
3606
3607
3607 defaultport = {b'https': 443, b'ssh': 22}
3608 defaultport = {b'https': 443, b'ssh': 22}
3608 if url.scheme in defaultport:
3609 if url.scheme in defaultport:
3609 try:
3610 try:
3610 addr = (url.host, int(url.port or defaultport[url.scheme]))
3611 addr = (url.host, int(url.port or defaultport[url.scheme]))
3611 except ValueError:
3612 except ValueError:
3612 raise error.Abort(_(b"malformed port number in URL"))
3613 raise error.Abort(_(b"malformed port number in URL"))
3613 else:
3614 else:
3614 raise error.Abort(_(b"only https and ssh connections are supported"))
3615 raise error.Abort(_(b"only https and ssh connections are supported"))
3615
3616
3616 from . import win32
3617 from . import win32
3617
3618
3618 s = ssl.wrap_socket(
3619 s = ssl.wrap_socket(
3619 socket.socket(),
3620 socket.socket(),
3620 ssl_version=ssl.PROTOCOL_TLS,
3621 ssl_version=ssl.PROTOCOL_TLS,
3621 cert_reqs=ssl.CERT_NONE,
3622 cert_reqs=ssl.CERT_NONE,
3622 ca_certs=None,
3623 ca_certs=None,
3623 )
3624 )
3624
3625
3625 try:
3626 try:
3626 s.connect(addr)
3627 s.connect(addr)
3627 cert = s.getpeercert(True)
3628 cert = s.getpeercert(True)
3628
3629
3629 ui.status(_(b'checking the certificate chain for %s\n') % url.host)
3630 ui.status(_(b'checking the certificate chain for %s\n') % url.host)
3630
3631
3631 complete = win32.checkcertificatechain(cert, build=False)
3632 complete = win32.checkcertificatechain(cert, build=False)
3632
3633
3633 if not complete:
3634 if not complete:
3634 ui.status(_(b'certificate chain is incomplete, updating... '))
3635 ui.status(_(b'certificate chain is incomplete, updating... '))
3635
3636
3636 if not win32.checkcertificatechain(cert):
3637 if not win32.checkcertificatechain(cert):
3637 ui.status(_(b'failed.\n'))
3638 ui.status(_(b'failed.\n'))
3638 else:
3639 else:
3639 ui.status(_(b'done.\n'))
3640 ui.status(_(b'done.\n'))
3640 else:
3641 else:
3641 ui.status(_(b'full certificate chain is available\n'))
3642 ui.status(_(b'full certificate chain is available\n'))
3642 finally:
3643 finally:
3643 s.close()
3644 s.close()
3644
3645
3645
3646
3646 @command(
3647 @command(
3648 b'debug::stable-tail-sort',
3649 [
3650 (
3651 b'T',
3652 b'template',
3653 b'{rev}\n',
3654 _(b'display with template'),
3655 _(b'TEMPLATE'),
3656 ),
3657 ],
3658 b'REV',
3659 )
3660 def debug_stable_tail_sort(ui, repo, revspec, template, **opts):
3661 """display the stable-tail sort of the ancestors of a given node"""
3662 rev = logcmdutil.revsingle(repo, revspec).rev()
3663 cl = repo.changelog
3664
3665 displayer = logcmdutil.maketemplater(ui, repo, template)
3666 sorted_revs = stabletailsort._stable_tail_sort(cl, rev)
3667 for ancestor_rev in sorted_revs:
3668 displayer.show(repo[ancestor_rev])
3669
3670
3671 @command(
3647 b"debugbackupbundle",
3672 b"debugbackupbundle",
3648 [
3673 [
3649 (
3674 (
3650 b"",
3675 b"",
3651 b"recover",
3676 b"recover",
3652 b"",
3677 b"",
3653 b"brings the specified changeset back into the repository",
3678 b"brings the specified changeset back into the repository",
3654 )
3679 )
3655 ]
3680 ]
3656 + cmdutil.logopts,
3681 + cmdutil.logopts,
3657 _(b"hg debugbackupbundle [--recover HASH]"),
3682 _(b"hg debugbackupbundle [--recover HASH]"),
3658 )
3683 )
3659 def debugbackupbundle(ui, repo, *pats, **opts):
3684 def debugbackupbundle(ui, repo, *pats, **opts):
3660 """lists the changesets available in backup bundles
3685 """lists the changesets available in backup bundles
3661
3686
3662 Without any arguments, this command prints a list of the changesets in each
3687 Without any arguments, this command prints a list of the changesets in each
3663 backup bundle.
3688 backup bundle.
3664
3689
3665 --recover takes a changeset hash and unbundles the first bundle that
3690 --recover takes a changeset hash and unbundles the first bundle that
3666 contains that hash, which puts that changeset back in your repository.
3691 contains that hash, which puts that changeset back in your repository.
3667
3692
3668 --verbose will print the entire commit message and the bundle path for that
3693 --verbose will print the entire commit message and the bundle path for that
3669 backup.
3694 backup.
3670 """
3695 """
3671 backups = list(
3696 backups = list(
3672 filter(
3697 filter(
3673 os.path.isfile, glob.glob(repo.vfs.join(b"strip-backup") + b"/*.hg")
3698 os.path.isfile, glob.glob(repo.vfs.join(b"strip-backup") + b"/*.hg")
3674 )
3699 )
3675 )
3700 )
3676 backups.sort(key=lambda x: os.path.getmtime(x), reverse=True)
3701 backups.sort(key=lambda x: os.path.getmtime(x), reverse=True)
3677
3702
3678 opts = pycompat.byteskwargs(opts)
3703 opts = pycompat.byteskwargs(opts)
3679 opts[b"bundle"] = b""
3704 opts[b"bundle"] = b""
3680 opts[b"force"] = None
3705 opts[b"force"] = None
3681 limit = logcmdutil.getlimit(opts)
3706 limit = logcmdutil.getlimit(opts)
3682
3707
3683 def display(other, chlist, displayer):
3708 def display(other, chlist, displayer):
3684 if opts.get(b"newest_first"):
3709 if opts.get(b"newest_first"):
3685 chlist.reverse()
3710 chlist.reverse()
3686 count = 0
3711 count = 0
3687 for n in chlist:
3712 for n in chlist:
3688 if limit is not None and count >= limit:
3713 if limit is not None and count >= limit:
3689 break
3714 break
3690 parents = [
3715 parents = [
3691 True for p in other.changelog.parents(n) if p != repo.nullid
3716 True for p in other.changelog.parents(n) if p != repo.nullid
3692 ]
3717 ]
3693 if opts.get(b"no_merges") and len(parents) == 2:
3718 if opts.get(b"no_merges") and len(parents) == 2:
3694 continue
3719 continue
3695 count += 1
3720 count += 1
3696 displayer.show(other[n])
3721 displayer.show(other[n])
3697
3722
3698 recovernode = opts.get(b"recover")
3723 recovernode = opts.get(b"recover")
3699 if recovernode:
3724 if recovernode:
3700 if scmutil.isrevsymbol(repo, recovernode):
3725 if scmutil.isrevsymbol(repo, recovernode):
3701 ui.warn(_(b"%s already exists in the repo\n") % recovernode)
3726 ui.warn(_(b"%s already exists in the repo\n") % recovernode)
3702 return
3727 return
3703 elif backups:
3728 elif backups:
3704 msg = _(
3729 msg = _(
3705 b"Recover changesets using: hg debugbackupbundle --recover "
3730 b"Recover changesets using: hg debugbackupbundle --recover "
3706 b"<changeset hash>\n\nAvailable backup changesets:"
3731 b"<changeset hash>\n\nAvailable backup changesets:"
3707 )
3732 )
3708 ui.status(msg, label=b"status.removed")
3733 ui.status(msg, label=b"status.removed")
3709 else:
3734 else:
3710 ui.status(_(b"no backup changesets found\n"))
3735 ui.status(_(b"no backup changesets found\n"))
3711 return
3736 return
3712
3737
3713 for backup in backups:
3738 for backup in backups:
3714 # Much of this is copied from the hg incoming logic
3739 # Much of this is copied from the hg incoming logic
3715 source = os.path.relpath(backup, encoding.getcwd())
3740 source = os.path.relpath(backup, encoding.getcwd())
3716 path = urlutil.get_unique_pull_path_obj(
3741 path = urlutil.get_unique_pull_path_obj(
3717 b'debugbackupbundle',
3742 b'debugbackupbundle',
3718 ui,
3743 ui,
3719 source,
3744 source,
3720 )
3745 )
3721 try:
3746 try:
3722 other = hg.peer(repo, opts, path)
3747 other = hg.peer(repo, opts, path)
3723 except error.LookupError as ex:
3748 except error.LookupError as ex:
3724 msg = _(b"\nwarning: unable to open bundle %s") % path.loc
3749 msg = _(b"\nwarning: unable to open bundle %s") % path.loc
3725 hint = _(b"\n(missing parent rev %s)\n") % short(ex.name)
3750 hint = _(b"\n(missing parent rev %s)\n") % short(ex.name)
3726 ui.warn(msg, hint=hint)
3751 ui.warn(msg, hint=hint)
3727 continue
3752 continue
3728 branches = (path.branch, opts.get(b'branch', []))
3753 branches = (path.branch, opts.get(b'branch', []))
3729 revs, checkout = hg.addbranchrevs(
3754 revs, checkout = hg.addbranchrevs(
3730 repo, other, branches, opts.get(b"rev")
3755 repo, other, branches, opts.get(b"rev")
3731 )
3756 )
3732
3757
3733 if revs:
3758 if revs:
3734 revs = [other.lookup(rev) for rev in revs]
3759 revs = [other.lookup(rev) for rev in revs]
3735
3760
3736 with ui.silent():
3761 with ui.silent():
3737 try:
3762 try:
3738 other, chlist, cleanupfn = bundlerepo.getremotechanges(
3763 other, chlist, cleanupfn = bundlerepo.getremotechanges(
3739 ui, repo, other, revs, opts[b"bundle"], opts[b"force"]
3764 ui, repo, other, revs, opts[b"bundle"], opts[b"force"]
3740 )
3765 )
3741 except error.LookupError:
3766 except error.LookupError:
3742 continue
3767 continue
3743
3768
3744 try:
3769 try:
3745 if not chlist:
3770 if not chlist:
3746 continue
3771 continue
3747 if recovernode:
3772 if recovernode:
3748 with repo.lock(), repo.transaction(b"unbundle") as tr:
3773 with repo.lock(), repo.transaction(b"unbundle") as tr:
3749 if scmutil.isrevsymbol(other, recovernode):
3774 if scmutil.isrevsymbol(other, recovernode):
3750 ui.status(_(b"Unbundling %s\n") % (recovernode))
3775 ui.status(_(b"Unbundling %s\n") % (recovernode))
3751 f = hg.openpath(ui, path.loc)
3776 f = hg.openpath(ui, path.loc)
3752 gen = exchange.readbundle(ui, f, path.loc)
3777 gen = exchange.readbundle(ui, f, path.loc)
3753 if isinstance(gen, bundle2.unbundle20):
3778 if isinstance(gen, bundle2.unbundle20):
3754 bundle2.applybundle(
3779 bundle2.applybundle(
3755 repo,
3780 repo,
3756 gen,
3781 gen,
3757 tr,
3782 tr,
3758 source=b"unbundle",
3783 source=b"unbundle",
3759 url=b"bundle:" + path.loc,
3784 url=b"bundle:" + path.loc,
3760 )
3785 )
3761 else:
3786 else:
3762 gen.apply(repo, b"unbundle", b"bundle:" + path.loc)
3787 gen.apply(repo, b"unbundle", b"bundle:" + path.loc)
3763 break
3788 break
3764 else:
3789 else:
3765 backupdate = encoding.strtolocal(
3790 backupdate = encoding.strtolocal(
3766 time.strftime(
3791 time.strftime(
3767 "%a %H:%M, %Y-%m-%d",
3792 "%a %H:%M, %Y-%m-%d",
3768 time.localtime(os.path.getmtime(path.loc)),
3793 time.localtime(os.path.getmtime(path.loc)),
3769 )
3794 )
3770 )
3795 )
3771 ui.status(b"\n%s\n" % (backupdate.ljust(50)))
3796 ui.status(b"\n%s\n" % (backupdate.ljust(50)))
3772 if ui.verbose:
3797 if ui.verbose:
3773 ui.status(b"%s%s\n" % (b"bundle:".ljust(13), path.loc))
3798 ui.status(b"%s%s\n" % (b"bundle:".ljust(13), path.loc))
3774 else:
3799 else:
3775 opts[
3800 opts[
3776 b"template"
3801 b"template"
3777 ] = b"{label('status.modified', node|short)} {desc|firstline}\n"
3802 ] = b"{label('status.modified', node|short)} {desc|firstline}\n"
3778 displayer = logcmdutil.changesetdisplayer(
3803 displayer = logcmdutil.changesetdisplayer(
3779 ui, other, opts, False
3804 ui, other, opts, False
3780 )
3805 )
3781 display(other, chlist, displayer)
3806 display(other, chlist, displayer)
3782 displayer.close()
3807 displayer.close()
3783 finally:
3808 finally:
3784 cleanupfn()
3809 cleanupfn()
3785
3810
3786
3811
3787 @command(
3812 @command(
3788 b'debugsub',
3813 b'debugsub',
3789 [(b'r', b'rev', b'', _(b'revision to check'), _(b'REV'))],
3814 [(b'r', b'rev', b'', _(b'revision to check'), _(b'REV'))],
3790 _(b'[-r REV] [REV]'),
3815 _(b'[-r REV] [REV]'),
3791 )
3816 )
3792 def debugsub(ui, repo, rev=None):
3817 def debugsub(ui, repo, rev=None):
3793 ctx = scmutil.revsingle(repo, rev, None)
3818 ctx = scmutil.revsingle(repo, rev, None)
3794 for k, v in sorted(ctx.substate.items()):
3819 for k, v in sorted(ctx.substate.items()):
3795 ui.writenoi18n(b'path %s\n' % k)
3820 ui.writenoi18n(b'path %s\n' % k)
3796 ui.writenoi18n(b' source %s\n' % v[0])
3821 ui.writenoi18n(b' source %s\n' % v[0])
3797 ui.writenoi18n(b' revision %s\n' % v[1])
3822 ui.writenoi18n(b' revision %s\n' % v[1])
3798
3823
3799
3824
3800 @command(
3825 @command(
3801 b'debugshell',
3826 b'debugshell',
3802 [
3827 [
3803 (
3828 (
3804 b'c',
3829 b'c',
3805 b'command',
3830 b'command',
3806 b'',
3831 b'',
3807 _(b'program passed in as a string'),
3832 _(b'program passed in as a string'),
3808 _(b'COMMAND'),
3833 _(b'COMMAND'),
3809 )
3834 )
3810 ],
3835 ],
3811 _(b'[-c COMMAND]'),
3836 _(b'[-c COMMAND]'),
3812 optionalrepo=True,
3837 optionalrepo=True,
3813 )
3838 )
3814 def debugshell(ui, repo, **opts):
3839 def debugshell(ui, repo, **opts):
3815 """run an interactive Python interpreter
3840 """run an interactive Python interpreter
3816
3841
3817 The local namespace is provided with a reference to the ui and
3842 The local namespace is provided with a reference to the ui and
3818 the repo instance (if available).
3843 the repo instance (if available).
3819 """
3844 """
3820 import code
3845 import code
3821
3846
3822 imported_objects = {
3847 imported_objects = {
3823 'ui': ui,
3848 'ui': ui,
3824 'repo': repo,
3849 'repo': repo,
3825 }
3850 }
3826
3851
3827 # py2exe disables initialization of the site module, which is responsible
3852 # py2exe disables initialization of the site module, which is responsible
3828 # for arranging for ``quit()`` to exit the interpreter. Manually initialize
3853 # for arranging for ``quit()`` to exit the interpreter. Manually initialize
3829 # the stuff that site normally does here, so that the interpreter can be
3854 # the stuff that site normally does here, so that the interpreter can be
3830 # quit in a consistent manner, whether run with pyoxidizer, exewrapper.c,
3855 # quit in a consistent manner, whether run with pyoxidizer, exewrapper.c,
3831 # py.exe, or py2exe.
3856 # py.exe, or py2exe.
3832 if getattr(sys, "frozen", None) == 'console_exe':
3857 if getattr(sys, "frozen", None) == 'console_exe':
3833 try:
3858 try:
3834 import site
3859 import site
3835
3860
3836 site.setcopyright()
3861 site.setcopyright()
3837 site.sethelper()
3862 site.sethelper()
3838 site.setquit()
3863 site.setquit()
3839 except ImportError:
3864 except ImportError:
3840 site = None # Keep PyCharm happy
3865 site = None # Keep PyCharm happy
3841
3866
3842 command = opts.get('command')
3867 command = opts.get('command')
3843 if command:
3868 if command:
3844 compiled = code.compile_command(encoding.strfromlocal(command))
3869 compiled = code.compile_command(encoding.strfromlocal(command))
3845 code.InteractiveInterpreter(locals=imported_objects).runcode(compiled)
3870 code.InteractiveInterpreter(locals=imported_objects).runcode(compiled)
3846 return
3871 return
3847
3872
3848 code.interact(local=imported_objects)
3873 code.interact(local=imported_objects)
3849
3874
3850
3875
3851 @command(
3876 @command(
3852 b'debug-revlog-stats',
3877 b'debug-revlog-stats',
3853 [
3878 [
3854 (b'c', b'changelog', None, _(b'Display changelog statistics')),
3879 (b'c', b'changelog', None, _(b'Display changelog statistics')),
3855 (b'm', b'manifest', None, _(b'Display manifest statistics')),
3880 (b'm', b'manifest', None, _(b'Display manifest statistics')),
3856 (b'f', b'filelogs', None, _(b'Display filelogs statistics')),
3881 (b'f', b'filelogs', None, _(b'Display filelogs statistics')),
3857 ]
3882 ]
3858 + cmdutil.formatteropts,
3883 + cmdutil.formatteropts,
3859 )
3884 )
3860 def debug_revlog_stats(ui, repo, **opts):
3885 def debug_revlog_stats(ui, repo, **opts):
3861 """display statistics about revlogs in the store"""
3886 """display statistics about revlogs in the store"""
3862 opts = pycompat.byteskwargs(opts)
3887 opts = pycompat.byteskwargs(opts)
3863 changelog = opts[b"changelog"]
3888 changelog = opts[b"changelog"]
3864 manifest = opts[b"manifest"]
3889 manifest = opts[b"manifest"]
3865 filelogs = opts[b"filelogs"]
3890 filelogs = opts[b"filelogs"]
3866
3891
3867 if changelog is None and manifest is None and filelogs is None:
3892 if changelog is None and manifest is None and filelogs is None:
3868 changelog = True
3893 changelog = True
3869 manifest = True
3894 manifest = True
3870 filelogs = True
3895 filelogs = True
3871
3896
3872 repo = repo.unfiltered()
3897 repo = repo.unfiltered()
3873 fm = ui.formatter(b'debug-revlog-stats', opts)
3898 fm = ui.formatter(b'debug-revlog-stats', opts)
3874 revlog_debug.debug_revlog_stats(repo, fm, changelog, manifest, filelogs)
3899 revlog_debug.debug_revlog_stats(repo, fm, changelog, manifest, filelogs)
3875 fm.end()
3900 fm.end()
3876
3901
3877
3902
3878 @command(
3903 @command(
3879 b'debugsuccessorssets',
3904 b'debugsuccessorssets',
3880 [(b'', b'closest', False, _(b'return closest successors sets only'))],
3905 [(b'', b'closest', False, _(b'return closest successors sets only'))],
3881 _(b'[REV]'),
3906 _(b'[REV]'),
3882 )
3907 )
3883 def debugsuccessorssets(ui, repo, *revs, **opts):
3908 def debugsuccessorssets(ui, repo, *revs, **opts):
3884 """show set of successors for revision
3909 """show set of successors for revision
3885
3910
3886 A successors set of changeset A is a consistent group of revisions that
3911 A successors set of changeset A is a consistent group of revisions that
3887 succeed A. It contains non-obsolete changesets only unless closests
3912 succeed A. It contains non-obsolete changesets only unless closests
3888 successors set is set.
3913 successors set is set.
3889
3914
3890 In most cases a changeset A has a single successors set containing a single
3915 In most cases a changeset A has a single successors set containing a single
3891 successor (changeset A replaced by A').
3916 successor (changeset A replaced by A').
3892
3917
3893 A changeset that is made obsolete with no successors are called "pruned".
3918 A changeset that is made obsolete with no successors are called "pruned".
3894 Such changesets have no successors sets at all.
3919 Such changesets have no successors sets at all.
3895
3920
3896 A changeset that has been "split" will have a successors set containing
3921 A changeset that has been "split" will have a successors set containing
3897 more than one successor.
3922 more than one successor.
3898
3923
3899 A changeset that has been rewritten in multiple different ways is called
3924 A changeset that has been rewritten in multiple different ways is called
3900 "divergent". Such changesets have multiple successor sets (each of which
3925 "divergent". Such changesets have multiple successor sets (each of which
3901 may also be split, i.e. have multiple successors).
3926 may also be split, i.e. have multiple successors).
3902
3927
3903 Results are displayed as follows::
3928 Results are displayed as follows::
3904
3929
3905 <rev1>
3930 <rev1>
3906 <successors-1A>
3931 <successors-1A>
3907 <rev2>
3932 <rev2>
3908 <successors-2A>
3933 <successors-2A>
3909 <successors-2B1> <successors-2B2> <successors-2B3>
3934 <successors-2B1> <successors-2B2> <successors-2B3>
3910
3935
3911 Here rev2 has two possible (i.e. divergent) successors sets. The first
3936 Here rev2 has two possible (i.e. divergent) successors sets. The first
3912 holds one element, whereas the second holds three (i.e. the changeset has
3937 holds one element, whereas the second holds three (i.e. the changeset has
3913 been split).
3938 been split).
3914 """
3939 """
3915 # passed to successorssets caching computation from one call to another
3940 # passed to successorssets caching computation from one call to another
3916 cache = {}
3941 cache = {}
3917 ctx2str = bytes
3942 ctx2str = bytes
3918 node2str = short
3943 node2str = short
3919 for rev in logcmdutil.revrange(repo, revs):
3944 for rev in logcmdutil.revrange(repo, revs):
3920 ctx = repo[rev]
3945 ctx = repo[rev]
3921 ui.write(b'%s\n' % ctx2str(ctx))
3946 ui.write(b'%s\n' % ctx2str(ctx))
3922 for succsset in obsutil.successorssets(
3947 for succsset in obsutil.successorssets(
3923 repo, ctx.node(), closest=opts['closest'], cache=cache
3948 repo, ctx.node(), closest=opts['closest'], cache=cache
3924 ):
3949 ):
3925 if succsset:
3950 if succsset:
3926 ui.write(b' ')
3951 ui.write(b' ')
3927 ui.write(node2str(succsset[0]))
3952 ui.write(node2str(succsset[0]))
3928 for node in succsset[1:]:
3953 for node in succsset[1:]:
3929 ui.write(b' ')
3954 ui.write(b' ')
3930 ui.write(node2str(node))
3955 ui.write(node2str(node))
3931 ui.write(b'\n')
3956 ui.write(b'\n')
3932
3957
3933
3958
3934 @command(b'debugtagscache', [])
3959 @command(b'debugtagscache', [])
3935 def debugtagscache(ui, repo):
3960 def debugtagscache(ui, repo):
3936 """display the contents of .hg/cache/hgtagsfnodes1"""
3961 """display the contents of .hg/cache/hgtagsfnodes1"""
3937 cache = tagsmod.hgtagsfnodescache(repo.unfiltered())
3962 cache = tagsmod.hgtagsfnodescache(repo.unfiltered())
3938 flog = repo.file(b'.hgtags')
3963 flog = repo.file(b'.hgtags')
3939 for r in repo:
3964 for r in repo:
3940 node = repo[r].node()
3965 node = repo[r].node()
3941 tagsnode = cache.getfnode(node, computemissing=False)
3966 tagsnode = cache.getfnode(node, computemissing=False)
3942 if tagsnode:
3967 if tagsnode:
3943 tagsnodedisplay = hex(tagsnode)
3968 tagsnodedisplay = hex(tagsnode)
3944 if not flog.hasnode(tagsnode):
3969 if not flog.hasnode(tagsnode):
3945 tagsnodedisplay += b' (unknown node)'
3970 tagsnodedisplay += b' (unknown node)'
3946 elif tagsnode is None:
3971 elif tagsnode is None:
3947 tagsnodedisplay = b'missing'
3972 tagsnodedisplay = b'missing'
3948 else:
3973 else:
3949 tagsnodedisplay = b'invalid'
3974 tagsnodedisplay = b'invalid'
3950
3975
3951 ui.write(b'%d %s %s\n' % (r, hex(node), tagsnodedisplay))
3976 ui.write(b'%d %s %s\n' % (r, hex(node), tagsnodedisplay))
3952
3977
3953
3978
3954 @command(
3979 @command(
3955 b'debugtemplate',
3980 b'debugtemplate',
3956 [
3981 [
3957 (b'r', b'rev', [], _(b'apply template on changesets'), _(b'REV')),
3982 (b'r', b'rev', [], _(b'apply template on changesets'), _(b'REV')),
3958 (b'D', b'define', [], _(b'define template keyword'), _(b'KEY=VALUE')),
3983 (b'D', b'define', [], _(b'define template keyword'), _(b'KEY=VALUE')),
3959 ],
3984 ],
3960 _(b'[-r REV]... [-D KEY=VALUE]... TEMPLATE'),
3985 _(b'[-r REV]... [-D KEY=VALUE]... TEMPLATE'),
3961 optionalrepo=True,
3986 optionalrepo=True,
3962 )
3987 )
3963 def debugtemplate(ui, repo, tmpl, **opts):
3988 def debugtemplate(ui, repo, tmpl, **opts):
3964 """parse and apply a template
3989 """parse and apply a template
3965
3990
3966 If -r/--rev is given, the template is processed as a log template and
3991 If -r/--rev is given, the template is processed as a log template and
3967 applied to the given changesets. Otherwise, it is processed as a generic
3992 applied to the given changesets. Otherwise, it is processed as a generic
3968 template.
3993 template.
3969
3994
3970 Use --verbose to print the parsed tree.
3995 Use --verbose to print the parsed tree.
3971 """
3996 """
3972 revs = None
3997 revs = None
3973 if opts['rev']:
3998 if opts['rev']:
3974 if repo is None:
3999 if repo is None:
3975 raise error.RepoError(
4000 raise error.RepoError(
3976 _(b'there is no Mercurial repository here (.hg not found)')
4001 _(b'there is no Mercurial repository here (.hg not found)')
3977 )
4002 )
3978 revs = logcmdutil.revrange(repo, opts['rev'])
4003 revs = logcmdutil.revrange(repo, opts['rev'])
3979
4004
3980 props = {}
4005 props = {}
3981 for d in opts['define']:
4006 for d in opts['define']:
3982 try:
4007 try:
3983 k, v = (e.strip() for e in d.split(b'=', 1))
4008 k, v = (e.strip() for e in d.split(b'=', 1))
3984 if not k or k == b'ui':
4009 if not k or k == b'ui':
3985 raise ValueError
4010 raise ValueError
3986 props[k] = v
4011 props[k] = v
3987 except ValueError:
4012 except ValueError:
3988 raise error.Abort(_(b'malformed keyword definition: %s') % d)
4013 raise error.Abort(_(b'malformed keyword definition: %s') % d)
3989
4014
3990 if ui.verbose:
4015 if ui.verbose:
3991 aliases = ui.configitems(b'templatealias')
4016 aliases = ui.configitems(b'templatealias')
3992 tree = templater.parse(tmpl)
4017 tree = templater.parse(tmpl)
3993 ui.note(templater.prettyformat(tree), b'\n')
4018 ui.note(templater.prettyformat(tree), b'\n')
3994 newtree = templater.expandaliases(tree, aliases)
4019 newtree = templater.expandaliases(tree, aliases)
3995 if newtree != tree:
4020 if newtree != tree:
3996 ui.notenoi18n(
4021 ui.notenoi18n(
3997 b"* expanded:\n", templater.prettyformat(newtree), b'\n'
4022 b"* expanded:\n", templater.prettyformat(newtree), b'\n'
3998 )
4023 )
3999
4024
4000 if revs is None:
4025 if revs is None:
4001 tres = formatter.templateresources(ui, repo)
4026 tres = formatter.templateresources(ui, repo)
4002 t = formatter.maketemplater(ui, tmpl, resources=tres)
4027 t = formatter.maketemplater(ui, tmpl, resources=tres)
4003 if ui.verbose:
4028 if ui.verbose:
4004 kwds, funcs = t.symbolsuseddefault()
4029 kwds, funcs = t.symbolsuseddefault()
4005 ui.writenoi18n(b"* keywords: %s\n" % b', '.join(sorted(kwds)))
4030 ui.writenoi18n(b"* keywords: %s\n" % b', '.join(sorted(kwds)))
4006 ui.writenoi18n(b"* functions: %s\n" % b', '.join(sorted(funcs)))
4031 ui.writenoi18n(b"* functions: %s\n" % b', '.join(sorted(funcs)))
4007 ui.write(t.renderdefault(props))
4032 ui.write(t.renderdefault(props))
4008 else:
4033 else:
4009 displayer = logcmdutil.maketemplater(ui, repo, tmpl)
4034 displayer = logcmdutil.maketemplater(ui, repo, tmpl)
4010 if ui.verbose:
4035 if ui.verbose:
4011 kwds, funcs = displayer.t.symbolsuseddefault()
4036 kwds, funcs = displayer.t.symbolsuseddefault()
4012 ui.writenoi18n(b"* keywords: %s\n" % b', '.join(sorted(kwds)))
4037 ui.writenoi18n(b"* keywords: %s\n" % b', '.join(sorted(kwds)))
4013 ui.writenoi18n(b"* functions: %s\n" % b', '.join(sorted(funcs)))
4038 ui.writenoi18n(b"* functions: %s\n" % b', '.join(sorted(funcs)))
4014 for r in revs:
4039 for r in revs:
4015 displayer.show(repo[r], **pycompat.strkwargs(props))
4040 displayer.show(repo[r], **pycompat.strkwargs(props))
4016 displayer.close()
4041 displayer.close()
4017
4042
4018
4043
4019 @command(
4044 @command(
4020 b'debuguigetpass',
4045 b'debuguigetpass',
4021 [
4046 [
4022 (b'p', b'prompt', b'', _(b'prompt text'), _(b'TEXT')),
4047 (b'p', b'prompt', b'', _(b'prompt text'), _(b'TEXT')),
4023 ],
4048 ],
4024 _(b'[-p TEXT]'),
4049 _(b'[-p TEXT]'),
4025 norepo=True,
4050 norepo=True,
4026 )
4051 )
4027 def debuguigetpass(ui, prompt=b''):
4052 def debuguigetpass(ui, prompt=b''):
4028 """show prompt to type password"""
4053 """show prompt to type password"""
4029 r = ui.getpass(prompt)
4054 r = ui.getpass(prompt)
4030 if r is None:
4055 if r is None:
4031 r = b"<default response>"
4056 r = b"<default response>"
4032 ui.writenoi18n(b'response: %s\n' % r)
4057 ui.writenoi18n(b'response: %s\n' % r)
4033
4058
4034
4059
4035 @command(
4060 @command(
4036 b'debuguiprompt',
4061 b'debuguiprompt',
4037 [
4062 [
4038 (b'p', b'prompt', b'', _(b'prompt text'), _(b'TEXT')),
4063 (b'p', b'prompt', b'', _(b'prompt text'), _(b'TEXT')),
4039 ],
4064 ],
4040 _(b'[-p TEXT]'),
4065 _(b'[-p TEXT]'),
4041 norepo=True,
4066 norepo=True,
4042 )
4067 )
4043 def debuguiprompt(ui, prompt=b''):
4068 def debuguiprompt(ui, prompt=b''):
4044 """show plain prompt"""
4069 """show plain prompt"""
4045 r = ui.prompt(prompt)
4070 r = ui.prompt(prompt)
4046 ui.writenoi18n(b'response: %s\n' % r)
4071 ui.writenoi18n(b'response: %s\n' % r)
4047
4072
4048
4073
4049 @command(b'debugupdatecaches', [])
4074 @command(b'debugupdatecaches', [])
4050 def debugupdatecaches(ui, repo, *pats, **opts):
4075 def debugupdatecaches(ui, repo, *pats, **opts):
4051 """warm all known caches in the repository"""
4076 """warm all known caches in the repository"""
4052 with repo.wlock(), repo.lock():
4077 with repo.wlock(), repo.lock():
4053 repo.updatecaches(caches=repository.CACHES_ALL)
4078 repo.updatecaches(caches=repository.CACHES_ALL)
4054
4079
4055
4080
4056 @command(
4081 @command(
4057 b'debugupgraderepo',
4082 b'debugupgraderepo',
4058 [
4083 [
4059 (
4084 (
4060 b'o',
4085 b'o',
4061 b'optimize',
4086 b'optimize',
4062 [],
4087 [],
4063 _(b'extra optimization to perform'),
4088 _(b'extra optimization to perform'),
4064 _(b'NAME'),
4089 _(b'NAME'),
4065 ),
4090 ),
4066 (b'', b'run', False, _(b'performs an upgrade')),
4091 (b'', b'run', False, _(b'performs an upgrade')),
4067 (b'', b'backup', True, _(b'keep the old repository content around')),
4092 (b'', b'backup', True, _(b'keep the old repository content around')),
4068 (b'', b'changelog', None, _(b'select the changelog for upgrade')),
4093 (b'', b'changelog', None, _(b'select the changelog for upgrade')),
4069 (b'', b'manifest', None, _(b'select the manifest for upgrade')),
4094 (b'', b'manifest', None, _(b'select the manifest for upgrade')),
4070 (b'', b'filelogs', None, _(b'select all filelogs for upgrade')),
4095 (b'', b'filelogs', None, _(b'select all filelogs for upgrade')),
4071 ],
4096 ],
4072 )
4097 )
4073 def debugupgraderepo(ui, repo, run=False, optimize=None, backup=True, **opts):
4098 def debugupgraderepo(ui, repo, run=False, optimize=None, backup=True, **opts):
4074 """upgrade a repository to use different features
4099 """upgrade a repository to use different features
4075
4100
4076 If no arguments are specified, the repository is evaluated for upgrade
4101 If no arguments are specified, the repository is evaluated for upgrade
4077 and a list of problems and potential optimizations is printed.
4102 and a list of problems and potential optimizations is printed.
4078
4103
4079 With ``--run``, a repository upgrade is performed. Behavior of the upgrade
4104 With ``--run``, a repository upgrade is performed. Behavior of the upgrade
4080 can be influenced via additional arguments. More details will be provided
4105 can be influenced via additional arguments. More details will be provided
4081 by the command output when run without ``--run``.
4106 by the command output when run without ``--run``.
4082
4107
4083 During the upgrade, the repository will be locked and no writes will be
4108 During the upgrade, the repository will be locked and no writes will be
4084 allowed.
4109 allowed.
4085
4110
4086 At the end of the upgrade, the repository may not be readable while new
4111 At the end of the upgrade, the repository may not be readable while new
4087 repository data is swapped in. This window will be as long as it takes to
4112 repository data is swapped in. This window will be as long as it takes to
4088 rename some directories inside the ``.hg`` directory. On most machines, this
4113 rename some directories inside the ``.hg`` directory. On most machines, this
4089 should complete almost instantaneously and the chances of a consumer being
4114 should complete almost instantaneously and the chances of a consumer being
4090 unable to access the repository should be low.
4115 unable to access the repository should be low.
4091
4116
4092 By default, all revlogs will be upgraded. You can restrict this using flags
4117 By default, all revlogs will be upgraded. You can restrict this using flags
4093 such as `--manifest`:
4118 such as `--manifest`:
4094
4119
4095 * `--manifest`: only optimize the manifest
4120 * `--manifest`: only optimize the manifest
4096 * `--no-manifest`: optimize all revlog but the manifest
4121 * `--no-manifest`: optimize all revlog but the manifest
4097 * `--changelog`: optimize the changelog only
4122 * `--changelog`: optimize the changelog only
4098 * `--no-changelog --no-manifest`: optimize filelogs only
4123 * `--no-changelog --no-manifest`: optimize filelogs only
4099 * `--filelogs`: optimize the filelogs only
4124 * `--filelogs`: optimize the filelogs only
4100 * `--no-changelog --no-manifest --no-filelogs`: skip all revlog optimizations
4125 * `--no-changelog --no-manifest --no-filelogs`: skip all revlog optimizations
4101 """
4126 """
4102 return upgrade.upgraderepo(
4127 return upgrade.upgraderepo(
4103 ui, repo, run=run, optimize=set(optimize), backup=backup, **opts
4128 ui, repo, run=run, optimize=set(optimize), backup=backup, **opts
4104 )
4129 )
4105
4130
4106
4131
4107 @command(
4132 @command(
4108 b'debugwalk', cmdutil.walkopts, _(b'[OPTION]... [FILE]...'), inferrepo=True
4133 b'debugwalk', cmdutil.walkopts, _(b'[OPTION]... [FILE]...'), inferrepo=True
4109 )
4134 )
4110 def debugwalk(ui, repo, *pats, **opts):
4135 def debugwalk(ui, repo, *pats, **opts):
4111 """show how files match on given patterns"""
4136 """show how files match on given patterns"""
4112 opts = pycompat.byteskwargs(opts)
4137 opts = pycompat.byteskwargs(opts)
4113 m = scmutil.match(repo[None], pats, opts)
4138 m = scmutil.match(repo[None], pats, opts)
4114 if ui.verbose:
4139 if ui.verbose:
4115 ui.writenoi18n(b'* matcher:\n', stringutil.prettyrepr(m), b'\n')
4140 ui.writenoi18n(b'* matcher:\n', stringutil.prettyrepr(m), b'\n')
4116 items = list(repo[None].walk(m))
4141 items = list(repo[None].walk(m))
4117 if not items:
4142 if not items:
4118 return
4143 return
4119 f = lambda fn: fn
4144 f = lambda fn: fn
4120 if ui.configbool(b'ui', b'slash') and pycompat.ossep != b'/':
4145 if ui.configbool(b'ui', b'slash') and pycompat.ossep != b'/':
4121 f = lambda fn: util.normpath(fn)
4146 f = lambda fn: util.normpath(fn)
4122 fmt = b'f %%-%ds %%-%ds %%s' % (
4147 fmt = b'f %%-%ds %%-%ds %%s' % (
4123 max([len(abs) for abs in items]),
4148 max([len(abs) for abs in items]),
4124 max([len(repo.pathto(abs)) for abs in items]),
4149 max([len(repo.pathto(abs)) for abs in items]),
4125 )
4150 )
4126 for abs in items:
4151 for abs in items:
4127 line = fmt % (
4152 line = fmt % (
4128 abs,
4153 abs,
4129 f(repo.pathto(abs)),
4154 f(repo.pathto(abs)),
4130 m.exact(abs) and b'exact' or b'',
4155 m.exact(abs) and b'exact' or b'',
4131 )
4156 )
4132 ui.write(b"%s\n" % line.rstrip())
4157 ui.write(b"%s\n" % line.rstrip())
4133
4158
4134
4159
4135 @command(b'debugwhyunstable', [], _(b'REV'))
4160 @command(b'debugwhyunstable', [], _(b'REV'))
4136 def debugwhyunstable(ui, repo, rev):
4161 def debugwhyunstable(ui, repo, rev):
4137 """explain instabilities of a changeset"""
4162 """explain instabilities of a changeset"""
4138 for entry in obsutil.whyunstable(repo, scmutil.revsingle(repo, rev)):
4163 for entry in obsutil.whyunstable(repo, scmutil.revsingle(repo, rev)):
4139 dnodes = b''
4164 dnodes = b''
4140 if entry.get(b'divergentnodes'):
4165 if entry.get(b'divergentnodes'):
4141 dnodes = (
4166 dnodes = (
4142 b' '.join(
4167 b' '.join(
4143 b'%s (%s)' % (ctx.hex(), ctx.phasestr())
4168 b'%s (%s)' % (ctx.hex(), ctx.phasestr())
4144 for ctx in entry[b'divergentnodes']
4169 for ctx in entry[b'divergentnodes']
4145 )
4170 )
4146 + b' '
4171 + b' '
4147 )
4172 )
4148 ui.write(
4173 ui.write(
4149 b'%s: %s%s %s\n'
4174 b'%s: %s%s %s\n'
4150 % (entry[b'instability'], dnodes, entry[b'reason'], entry[b'node'])
4175 % (entry[b'instability'], dnodes, entry[b'reason'], entry[b'node'])
4151 )
4176 )
4152
4177
4153
4178
4154 @command(
4179 @command(
4155 b'debugwireargs',
4180 b'debugwireargs',
4156 [
4181 [
4157 (b'', b'three', b'', b'three'),
4182 (b'', b'three', b'', b'three'),
4158 (b'', b'four', b'', b'four'),
4183 (b'', b'four', b'', b'four'),
4159 (b'', b'five', b'', b'five'),
4184 (b'', b'five', b'', b'five'),
4160 ]
4185 ]
4161 + cmdutil.remoteopts,
4186 + cmdutil.remoteopts,
4162 _(b'REPO [OPTIONS]... [ONE [TWO]]'),
4187 _(b'REPO [OPTIONS]... [ONE [TWO]]'),
4163 norepo=True,
4188 norepo=True,
4164 )
4189 )
4165 def debugwireargs(ui, repopath, *vals, **opts):
4190 def debugwireargs(ui, repopath, *vals, **opts):
4166 opts = pycompat.byteskwargs(opts)
4191 opts = pycompat.byteskwargs(opts)
4167 repo = hg.peer(ui, opts, repopath)
4192 repo = hg.peer(ui, opts, repopath)
4168 try:
4193 try:
4169 for opt in cmdutil.remoteopts:
4194 for opt in cmdutil.remoteopts:
4170 del opts[opt[1]]
4195 del opts[opt[1]]
4171 args = {}
4196 args = {}
4172 for k, v in opts.items():
4197 for k, v in opts.items():
4173 if v:
4198 if v:
4174 args[k] = v
4199 args[k] = v
4175 args = pycompat.strkwargs(args)
4200 args = pycompat.strkwargs(args)
4176 # run twice to check that we don't mess up the stream for the next command
4201 # run twice to check that we don't mess up the stream for the next command
4177 res1 = repo.debugwireargs(*vals, **args)
4202 res1 = repo.debugwireargs(*vals, **args)
4178 res2 = repo.debugwireargs(*vals, **args)
4203 res2 = repo.debugwireargs(*vals, **args)
4179 ui.write(b"%s\n" % res1)
4204 ui.write(b"%s\n" % res1)
4180 if res1 != res2:
4205 if res1 != res2:
4181 ui.warn(b"%s\n" % res2)
4206 ui.warn(b"%s\n" % res2)
4182 finally:
4207 finally:
4183 repo.close()
4208 repo.close()
4184
4209
4185
4210
4186 def _parsewirelangblocks(fh):
4211 def _parsewirelangblocks(fh):
4187 activeaction = None
4212 activeaction = None
4188 blocklines = []
4213 blocklines = []
4189 lastindent = 0
4214 lastindent = 0
4190
4215
4191 for line in fh:
4216 for line in fh:
4192 line = line.rstrip()
4217 line = line.rstrip()
4193 if not line:
4218 if not line:
4194 continue
4219 continue
4195
4220
4196 if line.startswith(b'#'):
4221 if line.startswith(b'#'):
4197 continue
4222 continue
4198
4223
4199 if not line.startswith(b' '):
4224 if not line.startswith(b' '):
4200 # New block. Flush previous one.
4225 # New block. Flush previous one.
4201 if activeaction:
4226 if activeaction:
4202 yield activeaction, blocklines
4227 yield activeaction, blocklines
4203
4228
4204 activeaction = line
4229 activeaction = line
4205 blocklines = []
4230 blocklines = []
4206 lastindent = 0
4231 lastindent = 0
4207 continue
4232 continue
4208
4233
4209 # Else we start with an indent.
4234 # Else we start with an indent.
4210
4235
4211 if not activeaction:
4236 if not activeaction:
4212 raise error.Abort(_(b'indented line outside of block'))
4237 raise error.Abort(_(b'indented line outside of block'))
4213
4238
4214 indent = len(line) - len(line.lstrip())
4239 indent = len(line) - len(line.lstrip())
4215
4240
4216 # If this line is indented more than the last line, concatenate it.
4241 # If this line is indented more than the last line, concatenate it.
4217 if indent > lastindent and blocklines:
4242 if indent > lastindent and blocklines:
4218 blocklines[-1] += line.lstrip()
4243 blocklines[-1] += line.lstrip()
4219 else:
4244 else:
4220 blocklines.append(line)
4245 blocklines.append(line)
4221 lastindent = indent
4246 lastindent = indent
4222
4247
4223 # Flush last block.
4248 # Flush last block.
4224 if activeaction:
4249 if activeaction:
4225 yield activeaction, blocklines
4250 yield activeaction, blocklines
4226
4251
4227
4252
4228 @command(
4253 @command(
4229 b'debugwireproto',
4254 b'debugwireproto',
4230 [
4255 [
4231 (b'', b'localssh', False, _(b'start an SSH server for this repo')),
4256 (b'', b'localssh', False, _(b'start an SSH server for this repo')),
4232 (b'', b'peer', b'', _(b'construct a specific version of the peer')),
4257 (b'', b'peer', b'', _(b'construct a specific version of the peer')),
4233 (
4258 (
4234 b'',
4259 b'',
4235 b'noreadstderr',
4260 b'noreadstderr',
4236 False,
4261 False,
4237 _(b'do not read from stderr of the remote'),
4262 _(b'do not read from stderr of the remote'),
4238 ),
4263 ),
4239 (
4264 (
4240 b'',
4265 b'',
4241 b'nologhandshake',
4266 b'nologhandshake',
4242 False,
4267 False,
4243 _(b'do not log I/O related to the peer handshake'),
4268 _(b'do not log I/O related to the peer handshake'),
4244 ),
4269 ),
4245 ]
4270 ]
4246 + cmdutil.remoteopts,
4271 + cmdutil.remoteopts,
4247 _(b'[PATH]'),
4272 _(b'[PATH]'),
4248 optionalrepo=True,
4273 optionalrepo=True,
4249 )
4274 )
4250 def debugwireproto(ui, repo, path=None, **opts):
4275 def debugwireproto(ui, repo, path=None, **opts):
4251 """send wire protocol commands to a server
4276 """send wire protocol commands to a server
4252
4277
4253 This command can be used to issue wire protocol commands to remote
4278 This command can be used to issue wire protocol commands to remote
4254 peers and to debug the raw data being exchanged.
4279 peers and to debug the raw data being exchanged.
4255
4280
4256 ``--localssh`` will start an SSH server against the current repository
4281 ``--localssh`` will start an SSH server against the current repository
4257 and connect to that. By default, the connection will perform a handshake
4282 and connect to that. By default, the connection will perform a handshake
4258 and establish an appropriate peer instance.
4283 and establish an appropriate peer instance.
4259
4284
4260 ``--peer`` can be used to bypass the handshake protocol and construct a
4285 ``--peer`` can be used to bypass the handshake protocol and construct a
4261 peer instance using the specified class type. Valid values are ``raw``,
4286 peer instance using the specified class type. Valid values are ``raw``,
4262 ``ssh1``. ``raw`` instances only allow sending raw data payloads and
4287 ``ssh1``. ``raw`` instances only allow sending raw data payloads and
4263 don't support higher-level command actions.
4288 don't support higher-level command actions.
4264
4289
4265 ``--noreadstderr`` can be used to disable automatic reading from stderr
4290 ``--noreadstderr`` can be used to disable automatic reading from stderr
4266 of the peer (for SSH connections only). Disabling automatic reading of
4291 of the peer (for SSH connections only). Disabling automatic reading of
4267 stderr is useful for making output more deterministic.
4292 stderr is useful for making output more deterministic.
4268
4293
4269 Commands are issued via a mini language which is specified via stdin.
4294 Commands are issued via a mini language which is specified via stdin.
4270 The language consists of individual actions to perform. An action is
4295 The language consists of individual actions to perform. An action is
4271 defined by a block. A block is defined as a line with no leading
4296 defined by a block. A block is defined as a line with no leading
4272 space followed by 0 or more lines with leading space. Blocks are
4297 space followed by 0 or more lines with leading space. Blocks are
4273 effectively a high-level command with additional metadata.
4298 effectively a high-level command with additional metadata.
4274
4299
4275 Lines beginning with ``#`` are ignored.
4300 Lines beginning with ``#`` are ignored.
4276
4301
4277 The following sections denote available actions.
4302 The following sections denote available actions.
4278
4303
4279 raw
4304 raw
4280 ---
4305 ---
4281
4306
4282 Send raw data to the server.
4307 Send raw data to the server.
4283
4308
4284 The block payload contains the raw data to send as one atomic send
4309 The block payload contains the raw data to send as one atomic send
4285 operation. The data may not actually be delivered in a single system
4310 operation. The data may not actually be delivered in a single system
4286 call: it depends on the abilities of the transport being used.
4311 call: it depends on the abilities of the transport being used.
4287
4312
4288 Each line in the block is de-indented and concatenated. Then, that
4313 Each line in the block is de-indented and concatenated. Then, that
4289 value is evaluated as a Python b'' literal. This allows the use of
4314 value is evaluated as a Python b'' literal. This allows the use of
4290 backslash escaping, etc.
4315 backslash escaping, etc.
4291
4316
4292 raw+
4317 raw+
4293 ----
4318 ----
4294
4319
4295 Behaves like ``raw`` except flushes output afterwards.
4320 Behaves like ``raw`` except flushes output afterwards.
4296
4321
4297 command <X>
4322 command <X>
4298 -----------
4323 -----------
4299
4324
4300 Send a request to run a named command, whose name follows the ``command``
4325 Send a request to run a named command, whose name follows the ``command``
4301 string.
4326 string.
4302
4327
4303 Arguments to the command are defined as lines in this block. The format of
4328 Arguments to the command are defined as lines in this block. The format of
4304 each line is ``<key> <value>``. e.g.::
4329 each line is ``<key> <value>``. e.g.::
4305
4330
4306 command listkeys
4331 command listkeys
4307 namespace bookmarks
4332 namespace bookmarks
4308
4333
4309 If the value begins with ``eval:``, it will be interpreted as a Python
4334 If the value begins with ``eval:``, it will be interpreted as a Python
4310 literal expression. Otherwise values are interpreted as Python b'' literals.
4335 literal expression. Otherwise values are interpreted as Python b'' literals.
4311 This allows sending complex types and encoding special byte sequences via
4336 This allows sending complex types and encoding special byte sequences via
4312 backslash escaping.
4337 backslash escaping.
4313
4338
4314 The following arguments have special meaning:
4339 The following arguments have special meaning:
4315
4340
4316 ``PUSHFILE``
4341 ``PUSHFILE``
4317 When defined, the *push* mechanism of the peer will be used instead
4342 When defined, the *push* mechanism of the peer will be used instead
4318 of the static request-response mechanism and the content of the
4343 of the static request-response mechanism and the content of the
4319 file specified in the value of this argument will be sent as the
4344 file specified in the value of this argument will be sent as the
4320 command payload.
4345 command payload.
4321
4346
4322 This can be used to submit a local bundle file to the remote.
4347 This can be used to submit a local bundle file to the remote.
4323
4348
4324 batchbegin
4349 batchbegin
4325 ----------
4350 ----------
4326
4351
4327 Instruct the peer to begin a batched send.
4352 Instruct the peer to begin a batched send.
4328
4353
4329 All ``command`` blocks are queued for execution until the next
4354 All ``command`` blocks are queued for execution until the next
4330 ``batchsubmit`` block.
4355 ``batchsubmit`` block.
4331
4356
4332 batchsubmit
4357 batchsubmit
4333 -----------
4358 -----------
4334
4359
4335 Submit previously queued ``command`` blocks as a batch request.
4360 Submit previously queued ``command`` blocks as a batch request.
4336
4361
4337 This action MUST be paired with a ``batchbegin`` action.
4362 This action MUST be paired with a ``batchbegin`` action.
4338
4363
4339 httprequest <method> <path>
4364 httprequest <method> <path>
4340 ---------------------------
4365 ---------------------------
4341
4366
4342 (HTTP peer only)
4367 (HTTP peer only)
4343
4368
4344 Send an HTTP request to the peer.
4369 Send an HTTP request to the peer.
4345
4370
4346 The HTTP request line follows the ``httprequest`` action. e.g. ``GET /foo``.
4371 The HTTP request line follows the ``httprequest`` action. e.g. ``GET /foo``.
4347
4372
4348 Arguments of the form ``<key>: <value>`` are interpreted as HTTP request
4373 Arguments of the form ``<key>: <value>`` are interpreted as HTTP request
4349 headers to add to the request. e.g. ``Accept: foo``.
4374 headers to add to the request. e.g. ``Accept: foo``.
4350
4375
4351 The following arguments are special:
4376 The following arguments are special:
4352
4377
4353 ``BODYFILE``
4378 ``BODYFILE``
4354 The content of the file defined as the value to this argument will be
4379 The content of the file defined as the value to this argument will be
4355 transferred verbatim as the HTTP request body.
4380 transferred verbatim as the HTTP request body.
4356
4381
4357 ``frame <type> <flags> <payload>``
4382 ``frame <type> <flags> <payload>``
4358 Send a unified protocol frame as part of the request body.
4383 Send a unified protocol frame as part of the request body.
4359
4384
4360 All frames will be collected and sent as the body to the HTTP
4385 All frames will be collected and sent as the body to the HTTP
4361 request.
4386 request.
4362
4387
4363 close
4388 close
4364 -----
4389 -----
4365
4390
4366 Close the connection to the server.
4391 Close the connection to the server.
4367
4392
4368 flush
4393 flush
4369 -----
4394 -----
4370
4395
4371 Flush data written to the server.
4396 Flush data written to the server.
4372
4397
4373 readavailable
4398 readavailable
4374 -------------
4399 -------------
4375
4400
4376 Close the write end of the connection and read all available data from
4401 Close the write end of the connection and read all available data from
4377 the server.
4402 the server.
4378
4403
4379 If the connection to the server encompasses multiple pipes, we poll both
4404 If the connection to the server encompasses multiple pipes, we poll both
4380 pipes and read available data.
4405 pipes and read available data.
4381
4406
4382 readline
4407 readline
4383 --------
4408 --------
4384
4409
4385 Read a line of output from the server. If there are multiple output
4410 Read a line of output from the server. If there are multiple output
4386 pipes, reads only the main pipe.
4411 pipes, reads only the main pipe.
4387
4412
4388 ereadline
4413 ereadline
4389 ---------
4414 ---------
4390
4415
4391 Like ``readline``, but read from the stderr pipe, if available.
4416 Like ``readline``, but read from the stderr pipe, if available.
4392
4417
4393 read <X>
4418 read <X>
4394 --------
4419 --------
4395
4420
4396 ``read()`` N bytes from the server's main output pipe.
4421 ``read()`` N bytes from the server's main output pipe.
4397
4422
4398 eread <X>
4423 eread <X>
4399 ---------
4424 ---------
4400
4425
4401 ``read()`` N bytes from the server's stderr pipe, if available.
4426 ``read()`` N bytes from the server's stderr pipe, if available.
4402
4427
4403 Specifying Unified Frame-Based Protocol Frames
4428 Specifying Unified Frame-Based Protocol Frames
4404 ----------------------------------------------
4429 ----------------------------------------------
4405
4430
4406 It is possible to emit a *Unified Frame-Based Protocol* by using special
4431 It is possible to emit a *Unified Frame-Based Protocol* by using special
4407 syntax.
4432 syntax.
4408
4433
4409 A frame is composed as a type, flags, and payload. These can be parsed
4434 A frame is composed as a type, flags, and payload. These can be parsed
4410 from a string of the form:
4435 from a string of the form:
4411
4436
4412 <request-id> <stream-id> <stream-flags> <type> <flags> <payload>
4437 <request-id> <stream-id> <stream-flags> <type> <flags> <payload>
4413
4438
4414 ``request-id`` and ``stream-id`` are integers defining the request and
4439 ``request-id`` and ``stream-id`` are integers defining the request and
4415 stream identifiers.
4440 stream identifiers.
4416
4441
4417 ``type`` can be an integer value for the frame type or the string name
4442 ``type`` can be an integer value for the frame type or the string name
4418 of the type. The strings are defined in ``wireprotoframing.py``. e.g.
4443 of the type. The strings are defined in ``wireprotoframing.py``. e.g.
4419 ``command-name``.
4444 ``command-name``.
4420
4445
4421 ``stream-flags`` and ``flags`` are a ``|`` delimited list of flag
4446 ``stream-flags`` and ``flags`` are a ``|`` delimited list of flag
4422 components. Each component (and there can be just one) can be an integer
4447 components. Each component (and there can be just one) can be an integer
4423 or a flag name for stream flags or frame flags, respectively. Values are
4448 or a flag name for stream flags or frame flags, respectively. Values are
4424 resolved to integers and then bitwise OR'd together.
4449 resolved to integers and then bitwise OR'd together.
4425
4450
4426 ``payload`` represents the raw frame payload. If it begins with
4451 ``payload`` represents the raw frame payload. If it begins with
4427 ``cbor:``, the following string is evaluated as Python code and the
4452 ``cbor:``, the following string is evaluated as Python code and the
4428 resulting object is fed into a CBOR encoder. Otherwise it is interpreted
4453 resulting object is fed into a CBOR encoder. Otherwise it is interpreted
4429 as a Python byte string literal.
4454 as a Python byte string literal.
4430 """
4455 """
4431 opts = pycompat.byteskwargs(opts)
4456 opts = pycompat.byteskwargs(opts)
4432
4457
4433 if opts[b'localssh'] and not repo:
4458 if opts[b'localssh'] and not repo:
4434 raise error.Abort(_(b'--localssh requires a repository'))
4459 raise error.Abort(_(b'--localssh requires a repository'))
4435
4460
4436 if opts[b'peer'] and opts[b'peer'] not in (
4461 if opts[b'peer'] and opts[b'peer'] not in (
4437 b'raw',
4462 b'raw',
4438 b'ssh1',
4463 b'ssh1',
4439 ):
4464 ):
4440 raise error.Abort(
4465 raise error.Abort(
4441 _(b'invalid value for --peer'),
4466 _(b'invalid value for --peer'),
4442 hint=_(b'valid values are "raw" and "ssh1"'),
4467 hint=_(b'valid values are "raw" and "ssh1"'),
4443 )
4468 )
4444
4469
4445 if path and opts[b'localssh']:
4470 if path and opts[b'localssh']:
4446 raise error.Abort(_(b'cannot specify --localssh with an explicit path'))
4471 raise error.Abort(_(b'cannot specify --localssh with an explicit path'))
4447
4472
4448 if ui.interactive():
4473 if ui.interactive():
4449 ui.write(_(b'(waiting for commands on stdin)\n'))
4474 ui.write(_(b'(waiting for commands on stdin)\n'))
4450
4475
4451 blocks = list(_parsewirelangblocks(ui.fin))
4476 blocks = list(_parsewirelangblocks(ui.fin))
4452
4477
4453 proc = None
4478 proc = None
4454 stdin = None
4479 stdin = None
4455 stdout = None
4480 stdout = None
4456 stderr = None
4481 stderr = None
4457 opener = None
4482 opener = None
4458
4483
4459 if opts[b'localssh']:
4484 if opts[b'localssh']:
4460 # We start the SSH server in its own process so there is process
4485 # We start the SSH server in its own process so there is process
4461 # separation. This prevents a whole class of potential bugs around
4486 # separation. This prevents a whole class of potential bugs around
4462 # shared state from interfering with server operation.
4487 # shared state from interfering with server operation.
4463 args = procutil.hgcmd() + [
4488 args = procutil.hgcmd() + [
4464 b'-R',
4489 b'-R',
4465 repo.root,
4490 repo.root,
4466 b'debugserve',
4491 b'debugserve',
4467 b'--sshstdio',
4492 b'--sshstdio',
4468 ]
4493 ]
4469 proc = subprocess.Popen(
4494 proc = subprocess.Popen(
4470 pycompat.rapply(procutil.tonativestr, args),
4495 pycompat.rapply(procutil.tonativestr, args),
4471 stdin=subprocess.PIPE,
4496 stdin=subprocess.PIPE,
4472 stdout=subprocess.PIPE,
4497 stdout=subprocess.PIPE,
4473 stderr=subprocess.PIPE,
4498 stderr=subprocess.PIPE,
4474 bufsize=0,
4499 bufsize=0,
4475 )
4500 )
4476
4501
4477 stdin = proc.stdin
4502 stdin = proc.stdin
4478 stdout = proc.stdout
4503 stdout = proc.stdout
4479 stderr = proc.stderr
4504 stderr = proc.stderr
4480
4505
4481 # We turn the pipes into observers so we can log I/O.
4506 # We turn the pipes into observers so we can log I/O.
4482 if ui.verbose or opts[b'peer'] == b'raw':
4507 if ui.verbose or opts[b'peer'] == b'raw':
4483 stdin = util.makeloggingfileobject(
4508 stdin = util.makeloggingfileobject(
4484 ui, proc.stdin, b'i', logdata=True
4509 ui, proc.stdin, b'i', logdata=True
4485 )
4510 )
4486 stdout = util.makeloggingfileobject(
4511 stdout = util.makeloggingfileobject(
4487 ui, proc.stdout, b'o', logdata=True
4512 ui, proc.stdout, b'o', logdata=True
4488 )
4513 )
4489 stderr = util.makeloggingfileobject(
4514 stderr = util.makeloggingfileobject(
4490 ui, proc.stderr, b'e', logdata=True
4515 ui, proc.stderr, b'e', logdata=True
4491 )
4516 )
4492
4517
4493 # --localssh also implies the peer connection settings.
4518 # --localssh also implies the peer connection settings.
4494
4519
4495 url = b'ssh://localserver'
4520 url = b'ssh://localserver'
4496 autoreadstderr = not opts[b'noreadstderr']
4521 autoreadstderr = not opts[b'noreadstderr']
4497
4522
4498 if opts[b'peer'] == b'ssh1':
4523 if opts[b'peer'] == b'ssh1':
4499 ui.write(_(b'creating ssh peer for wire protocol version 1\n'))
4524 ui.write(_(b'creating ssh peer for wire protocol version 1\n'))
4500 peer = sshpeer.sshv1peer(
4525 peer = sshpeer.sshv1peer(
4501 ui,
4526 ui,
4502 url,
4527 url,
4503 proc,
4528 proc,
4504 stdin,
4529 stdin,
4505 stdout,
4530 stdout,
4506 stderr,
4531 stderr,
4507 None,
4532 None,
4508 autoreadstderr=autoreadstderr,
4533 autoreadstderr=autoreadstderr,
4509 )
4534 )
4510 elif opts[b'peer'] == b'raw':
4535 elif opts[b'peer'] == b'raw':
4511 ui.write(_(b'using raw connection to peer\n'))
4536 ui.write(_(b'using raw connection to peer\n'))
4512 peer = None
4537 peer = None
4513 else:
4538 else:
4514 ui.write(_(b'creating ssh peer from handshake results\n'))
4539 ui.write(_(b'creating ssh peer from handshake results\n'))
4515 peer = sshpeer._make_peer(
4540 peer = sshpeer._make_peer(
4516 ui,
4541 ui,
4517 url,
4542 url,
4518 proc,
4543 proc,
4519 stdin,
4544 stdin,
4520 stdout,
4545 stdout,
4521 stderr,
4546 stderr,
4522 autoreadstderr=autoreadstderr,
4547 autoreadstderr=autoreadstderr,
4523 )
4548 )
4524
4549
4525 elif path:
4550 elif path:
4526 # We bypass hg.peer() so we can proxy the sockets.
4551 # We bypass hg.peer() so we can proxy the sockets.
4527 # TODO consider not doing this because we skip
4552 # TODO consider not doing this because we skip
4528 # ``hg.wirepeersetupfuncs`` and potentially other useful functionality.
4553 # ``hg.wirepeersetupfuncs`` and potentially other useful functionality.
4529 u = urlutil.url(path)
4554 u = urlutil.url(path)
4530 if u.scheme != b'http':
4555 if u.scheme != b'http':
4531 raise error.Abort(_(b'only http:// paths are currently supported'))
4556 raise error.Abort(_(b'only http:// paths are currently supported'))
4532
4557
4533 url, authinfo = u.authinfo()
4558 url, authinfo = u.authinfo()
4534 openerargs = {
4559 openerargs = {
4535 'useragent': b'Mercurial debugwireproto',
4560 'useragent': b'Mercurial debugwireproto',
4536 }
4561 }
4537
4562
4538 # Turn pipes/sockets into observers so we can log I/O.
4563 # Turn pipes/sockets into observers so we can log I/O.
4539 if ui.verbose:
4564 if ui.verbose:
4540 openerargs.update(
4565 openerargs.update(
4541 {
4566 {
4542 'loggingfh': ui,
4567 'loggingfh': ui,
4543 'loggingname': b's',
4568 'loggingname': b's',
4544 'loggingopts': {
4569 'loggingopts': {
4545 'logdata': True,
4570 'logdata': True,
4546 'logdataapis': False,
4571 'logdataapis': False,
4547 },
4572 },
4548 }
4573 }
4549 )
4574 )
4550
4575
4551 if ui.debugflag:
4576 if ui.debugflag:
4552 openerargs['loggingopts']['logdataapis'] = True
4577 openerargs['loggingopts']['logdataapis'] = True
4553
4578
4554 # Don't send default headers when in raw mode. This allows us to
4579 # Don't send default headers when in raw mode. This allows us to
4555 # bypass most of the behavior of our URL handling code so we can
4580 # bypass most of the behavior of our URL handling code so we can
4556 # have near complete control over what's sent on the wire.
4581 # have near complete control over what's sent on the wire.
4557 if opts[b'peer'] == b'raw':
4582 if opts[b'peer'] == b'raw':
4558 openerargs['sendaccept'] = False
4583 openerargs['sendaccept'] = False
4559
4584
4560 opener = urlmod.opener(ui, authinfo, **openerargs)
4585 opener = urlmod.opener(ui, authinfo, **openerargs)
4561
4586
4562 if opts[b'peer'] == b'raw':
4587 if opts[b'peer'] == b'raw':
4563 ui.write(_(b'using raw connection to peer\n'))
4588 ui.write(_(b'using raw connection to peer\n'))
4564 peer = None
4589 peer = None
4565 elif opts[b'peer']:
4590 elif opts[b'peer']:
4566 raise error.Abort(
4591 raise error.Abort(
4567 _(b'--peer %s not supported with HTTP peers') % opts[b'peer']
4592 _(b'--peer %s not supported with HTTP peers') % opts[b'peer']
4568 )
4593 )
4569 else:
4594 else:
4570 peer_path = urlutil.try_path(ui, path)
4595 peer_path = urlutil.try_path(ui, path)
4571 peer = httppeer._make_peer(ui, peer_path, opener=opener)
4596 peer = httppeer._make_peer(ui, peer_path, opener=opener)
4572
4597
4573 # We /could/ populate stdin/stdout with sock.makefile()...
4598 # We /could/ populate stdin/stdout with sock.makefile()...
4574 else:
4599 else:
4575 raise error.Abort(_(b'unsupported connection configuration'))
4600 raise error.Abort(_(b'unsupported connection configuration'))
4576
4601
4577 batchedcommands = None
4602 batchedcommands = None
4578
4603
4579 # Now perform actions based on the parsed wire language instructions.
4604 # Now perform actions based on the parsed wire language instructions.
4580 for action, lines in blocks:
4605 for action, lines in blocks:
4581 if action in (b'raw', b'raw+'):
4606 if action in (b'raw', b'raw+'):
4582 if not stdin:
4607 if not stdin:
4583 raise error.Abort(_(b'cannot call raw/raw+ on this peer'))
4608 raise error.Abort(_(b'cannot call raw/raw+ on this peer'))
4584
4609
4585 # Concatenate the data together.
4610 # Concatenate the data together.
4586 data = b''.join(l.lstrip() for l in lines)
4611 data = b''.join(l.lstrip() for l in lines)
4587 data = stringutil.unescapestr(data)
4612 data = stringutil.unescapestr(data)
4588 stdin.write(data)
4613 stdin.write(data)
4589
4614
4590 if action == b'raw+':
4615 if action == b'raw+':
4591 stdin.flush()
4616 stdin.flush()
4592 elif action == b'flush':
4617 elif action == b'flush':
4593 if not stdin:
4618 if not stdin:
4594 raise error.Abort(_(b'cannot call flush on this peer'))
4619 raise error.Abort(_(b'cannot call flush on this peer'))
4595 stdin.flush()
4620 stdin.flush()
4596 elif action.startswith(b'command'):
4621 elif action.startswith(b'command'):
4597 if not peer:
4622 if not peer:
4598 raise error.Abort(
4623 raise error.Abort(
4599 _(
4624 _(
4600 b'cannot send commands unless peer instance '
4625 b'cannot send commands unless peer instance '
4601 b'is available'
4626 b'is available'
4602 )
4627 )
4603 )
4628 )
4604
4629
4605 command = action.split(b' ', 1)[1]
4630 command = action.split(b' ', 1)[1]
4606
4631
4607 args = {}
4632 args = {}
4608 for line in lines:
4633 for line in lines:
4609 # We need to allow empty values.
4634 # We need to allow empty values.
4610 fields = line.lstrip().split(b' ', 1)
4635 fields = line.lstrip().split(b' ', 1)
4611 if len(fields) == 1:
4636 if len(fields) == 1:
4612 key = fields[0]
4637 key = fields[0]
4613 value = b''
4638 value = b''
4614 else:
4639 else:
4615 key, value = fields
4640 key, value = fields
4616
4641
4617 if value.startswith(b'eval:'):
4642 if value.startswith(b'eval:'):
4618 value = stringutil.evalpythonliteral(value[5:])
4643 value = stringutil.evalpythonliteral(value[5:])
4619 else:
4644 else:
4620 value = stringutil.unescapestr(value)
4645 value = stringutil.unescapestr(value)
4621
4646
4622 args[key] = value
4647 args[key] = value
4623
4648
4624 if batchedcommands is not None:
4649 if batchedcommands is not None:
4625 batchedcommands.append((command, args))
4650 batchedcommands.append((command, args))
4626 continue
4651 continue
4627
4652
4628 ui.status(_(b'sending %s command\n') % command)
4653 ui.status(_(b'sending %s command\n') % command)
4629
4654
4630 if b'PUSHFILE' in args:
4655 if b'PUSHFILE' in args:
4631 with open(args[b'PUSHFILE'], 'rb') as fh:
4656 with open(args[b'PUSHFILE'], 'rb') as fh:
4632 del args[b'PUSHFILE']
4657 del args[b'PUSHFILE']
4633 res, output = peer._callpush(
4658 res, output = peer._callpush(
4634 command, fh, **pycompat.strkwargs(args)
4659 command, fh, **pycompat.strkwargs(args)
4635 )
4660 )
4636 ui.status(_(b'result: %s\n') % stringutil.escapestr(res))
4661 ui.status(_(b'result: %s\n') % stringutil.escapestr(res))
4637 ui.status(
4662 ui.status(
4638 _(b'remote output: %s\n') % stringutil.escapestr(output)
4663 _(b'remote output: %s\n') % stringutil.escapestr(output)
4639 )
4664 )
4640 else:
4665 else:
4641 with peer.commandexecutor() as e:
4666 with peer.commandexecutor() as e:
4642 res = e.callcommand(command, args).result()
4667 res = e.callcommand(command, args).result()
4643
4668
4644 ui.status(
4669 ui.status(
4645 _(b'response: %s\n')
4670 _(b'response: %s\n')
4646 % stringutil.pprint(res, bprefix=True, indent=2)
4671 % stringutil.pprint(res, bprefix=True, indent=2)
4647 )
4672 )
4648
4673
4649 elif action == b'batchbegin':
4674 elif action == b'batchbegin':
4650 if batchedcommands is not None:
4675 if batchedcommands is not None:
4651 raise error.Abort(_(b'nested batchbegin not allowed'))
4676 raise error.Abort(_(b'nested batchbegin not allowed'))
4652
4677
4653 batchedcommands = []
4678 batchedcommands = []
4654 elif action == b'batchsubmit':
4679 elif action == b'batchsubmit':
4655 # There is a batching API we could go through. But it would be
4680 # There is a batching API we could go through. But it would be
4656 # difficult to normalize requests into function calls. It is easier
4681 # difficult to normalize requests into function calls. It is easier
4657 # to bypass this layer and normalize to commands + args.
4682 # to bypass this layer and normalize to commands + args.
4658 ui.status(
4683 ui.status(
4659 _(b'sending batch with %d sub-commands\n')
4684 _(b'sending batch with %d sub-commands\n')
4660 % len(batchedcommands)
4685 % len(batchedcommands)
4661 )
4686 )
4662 assert peer is not None
4687 assert peer is not None
4663 for i, chunk in enumerate(peer._submitbatch(batchedcommands)):
4688 for i, chunk in enumerate(peer._submitbatch(batchedcommands)):
4664 ui.status(
4689 ui.status(
4665 _(b'response #%d: %s\n') % (i, stringutil.escapestr(chunk))
4690 _(b'response #%d: %s\n') % (i, stringutil.escapestr(chunk))
4666 )
4691 )
4667
4692
4668 batchedcommands = None
4693 batchedcommands = None
4669
4694
4670 elif action.startswith(b'httprequest '):
4695 elif action.startswith(b'httprequest '):
4671 if not opener:
4696 if not opener:
4672 raise error.Abort(
4697 raise error.Abort(
4673 _(b'cannot use httprequest without an HTTP peer')
4698 _(b'cannot use httprequest without an HTTP peer')
4674 )
4699 )
4675
4700
4676 request = action.split(b' ', 2)
4701 request = action.split(b' ', 2)
4677 if len(request) != 3:
4702 if len(request) != 3:
4678 raise error.Abort(
4703 raise error.Abort(
4679 _(
4704 _(
4680 b'invalid httprequest: expected format is '
4705 b'invalid httprequest: expected format is '
4681 b'"httprequest <method> <path>'
4706 b'"httprequest <method> <path>'
4682 )
4707 )
4683 )
4708 )
4684
4709
4685 method, httppath = request[1:]
4710 method, httppath = request[1:]
4686 headers = {}
4711 headers = {}
4687 body = None
4712 body = None
4688 frames = []
4713 frames = []
4689 for line in lines:
4714 for line in lines:
4690 line = line.lstrip()
4715 line = line.lstrip()
4691 m = re.match(b'^([a-zA-Z0-9_-]+): (.*)$', line)
4716 m = re.match(b'^([a-zA-Z0-9_-]+): (.*)$', line)
4692 if m:
4717 if m:
4693 # Headers need to use native strings.
4718 # Headers need to use native strings.
4694 key = pycompat.strurl(m.group(1))
4719 key = pycompat.strurl(m.group(1))
4695 value = pycompat.strurl(m.group(2))
4720 value = pycompat.strurl(m.group(2))
4696 headers[key] = value
4721 headers[key] = value
4697 continue
4722 continue
4698
4723
4699 if line.startswith(b'BODYFILE '):
4724 if line.startswith(b'BODYFILE '):
4700 with open(line.split(b' ', 1), b'rb') as fh:
4725 with open(line.split(b' ', 1), b'rb') as fh:
4701 body = fh.read()
4726 body = fh.read()
4702 elif line.startswith(b'frame '):
4727 elif line.startswith(b'frame '):
4703 frame = wireprotoframing.makeframefromhumanstring(
4728 frame = wireprotoframing.makeframefromhumanstring(
4704 line[len(b'frame ') :]
4729 line[len(b'frame ') :]
4705 )
4730 )
4706
4731
4707 frames.append(frame)
4732 frames.append(frame)
4708 else:
4733 else:
4709 raise error.Abort(
4734 raise error.Abort(
4710 _(b'unknown argument to httprequest: %s') % line
4735 _(b'unknown argument to httprequest: %s') % line
4711 )
4736 )
4712
4737
4713 url = path + httppath
4738 url = path + httppath
4714
4739
4715 if frames:
4740 if frames:
4716 body = b''.join(bytes(f) for f in frames)
4741 body = b''.join(bytes(f) for f in frames)
4717
4742
4718 req = urlmod.urlreq.request(pycompat.strurl(url), body, headers)
4743 req = urlmod.urlreq.request(pycompat.strurl(url), body, headers)
4719
4744
4720 # urllib.Request insists on using has_data() as a proxy for
4745 # urllib.Request insists on using has_data() as a proxy for
4721 # determining the request method. Override that to use our
4746 # determining the request method. Override that to use our
4722 # explicitly requested method.
4747 # explicitly requested method.
4723 req.get_method = lambda: pycompat.sysstr(method)
4748 req.get_method = lambda: pycompat.sysstr(method)
4724
4749
4725 try:
4750 try:
4726 res = opener.open(req)
4751 res = opener.open(req)
4727 body = res.read()
4752 body = res.read()
4728 except util.urlerr.urlerror as e:
4753 except util.urlerr.urlerror as e:
4729 # read() method must be called, but only exists in Python 2
4754 # read() method must be called, but only exists in Python 2
4730 getattr(e, 'read', lambda: None)()
4755 getattr(e, 'read', lambda: None)()
4731 continue
4756 continue
4732
4757
4733 ct = res.headers.get('Content-Type')
4758 ct = res.headers.get('Content-Type')
4734 if ct == 'application/mercurial-cbor':
4759 if ct == 'application/mercurial-cbor':
4735 ui.write(
4760 ui.write(
4736 _(b'cbor> %s\n')
4761 _(b'cbor> %s\n')
4737 % stringutil.pprint(
4762 % stringutil.pprint(
4738 cborutil.decodeall(body), bprefix=True, indent=2
4763 cborutil.decodeall(body), bprefix=True, indent=2
4739 )
4764 )
4740 )
4765 )
4741
4766
4742 elif action == b'close':
4767 elif action == b'close':
4743 assert peer is not None
4768 assert peer is not None
4744 peer.close()
4769 peer.close()
4745 elif action == b'readavailable':
4770 elif action == b'readavailable':
4746 if not stdout or not stderr:
4771 if not stdout or not stderr:
4747 raise error.Abort(
4772 raise error.Abort(
4748 _(b'readavailable not available on this peer')
4773 _(b'readavailable not available on this peer')
4749 )
4774 )
4750
4775
4751 stdin.close()
4776 stdin.close()
4752 stdout.read()
4777 stdout.read()
4753 stderr.read()
4778 stderr.read()
4754
4779
4755 elif action == b'readline':
4780 elif action == b'readline':
4756 if not stdout:
4781 if not stdout:
4757 raise error.Abort(_(b'readline not available on this peer'))
4782 raise error.Abort(_(b'readline not available on this peer'))
4758 stdout.readline()
4783 stdout.readline()
4759 elif action == b'ereadline':
4784 elif action == b'ereadline':
4760 if not stderr:
4785 if not stderr:
4761 raise error.Abort(_(b'ereadline not available on this peer'))
4786 raise error.Abort(_(b'ereadline not available on this peer'))
4762 stderr.readline()
4787 stderr.readline()
4763 elif action.startswith(b'read '):
4788 elif action.startswith(b'read '):
4764 count = int(action.split(b' ', 1)[1])
4789 count = int(action.split(b' ', 1)[1])
4765 if not stdout:
4790 if not stdout:
4766 raise error.Abort(_(b'read not available on this peer'))
4791 raise error.Abort(_(b'read not available on this peer'))
4767 stdout.read(count)
4792 stdout.read(count)
4768 elif action.startswith(b'eread '):
4793 elif action.startswith(b'eread '):
4769 count = int(action.split(b' ', 1)[1])
4794 count = int(action.split(b' ', 1)[1])
4770 if not stderr:
4795 if not stderr:
4771 raise error.Abort(_(b'eread not available on this peer'))
4796 raise error.Abort(_(b'eread not available on this peer'))
4772 stderr.read(count)
4797 stderr.read(count)
4773 else:
4798 else:
4774 raise error.Abort(_(b'unknown action: %s') % action)
4799 raise error.Abort(_(b'unknown action: %s') % action)
4775
4800
4776 if batchedcommands is not None:
4801 if batchedcommands is not None:
4777 raise error.Abort(_(b'unclosed "batchbegin" request'))
4802 raise error.Abort(_(b'unclosed "batchbegin" request'))
4778
4803
4779 if peer:
4804 if peer:
4780 peer.close()
4805 peer.close()
4781
4806
4782 if proc:
4807 if proc:
4783 proc.kill()
4808 proc.kill()
@@ -1,1804 +1,1805 b''
1 #
1 #
2 # This is the mercurial setup script.
2 # This is the mercurial setup script.
3 #
3 #
4 # 'python setup.py install', or
4 # 'python setup.py install', or
5 # 'python setup.py --help' for more options
5 # 'python setup.py --help' for more options
6 import os
6 import os
7
7
8 # Mercurial can't work on 3.6.0 or 3.6.1 due to a bug in % formatting
8 # Mercurial can't work on 3.6.0 or 3.6.1 due to a bug in % formatting
9 # in bytestrings.
9 # in bytestrings.
10 supportedpy = ','.join(
10 supportedpy = ','.join(
11 [
11 [
12 '>=3.6.2',
12 '>=3.6.2',
13 ]
13 ]
14 )
14 )
15
15
16 import sys, platform
16 import sys, platform
17 import sysconfig
17 import sysconfig
18
18
19
19
20 def sysstr(s):
20 def sysstr(s):
21 return s.decode('latin-1')
21 return s.decode('latin-1')
22
22
23
23
24 def eprint(*args, **kwargs):
24 def eprint(*args, **kwargs):
25 kwargs['file'] = sys.stderr
25 kwargs['file'] = sys.stderr
26 print(*args, **kwargs)
26 print(*args, **kwargs)
27
27
28
28
29 import ssl
29 import ssl
30
30
31 # ssl.HAS_TLSv1* are preferred to check support but they were added in Python
31 # ssl.HAS_TLSv1* are preferred to check support but they were added in Python
32 # 3.7. Prior to CPython commit 6e8cda91d92da72800d891b2fc2073ecbc134d98
32 # 3.7. Prior to CPython commit 6e8cda91d92da72800d891b2fc2073ecbc134d98
33 # (backported to the 3.7 branch), ssl.PROTOCOL_TLSv1_1 / ssl.PROTOCOL_TLSv1_2
33 # (backported to the 3.7 branch), ssl.PROTOCOL_TLSv1_1 / ssl.PROTOCOL_TLSv1_2
34 # were defined only if compiled against a OpenSSL version with TLS 1.1 / 1.2
34 # were defined only if compiled against a OpenSSL version with TLS 1.1 / 1.2
35 # support. At the mentioned commit, they were unconditionally defined.
35 # support. At the mentioned commit, they were unconditionally defined.
36 _notset = object()
36 _notset = object()
37 has_tlsv1_1 = getattr(ssl, 'HAS_TLSv1_1', _notset)
37 has_tlsv1_1 = getattr(ssl, 'HAS_TLSv1_1', _notset)
38 if has_tlsv1_1 is _notset:
38 if has_tlsv1_1 is _notset:
39 has_tlsv1_1 = getattr(ssl, 'PROTOCOL_TLSv1_1', _notset) is not _notset
39 has_tlsv1_1 = getattr(ssl, 'PROTOCOL_TLSv1_1', _notset) is not _notset
40 has_tlsv1_2 = getattr(ssl, 'HAS_TLSv1_2', _notset)
40 has_tlsv1_2 = getattr(ssl, 'HAS_TLSv1_2', _notset)
41 if has_tlsv1_2 is _notset:
41 if has_tlsv1_2 is _notset:
42 has_tlsv1_2 = getattr(ssl, 'PROTOCOL_TLSv1_2', _notset) is not _notset
42 has_tlsv1_2 = getattr(ssl, 'PROTOCOL_TLSv1_2', _notset) is not _notset
43 if not (has_tlsv1_1 or has_tlsv1_2):
43 if not (has_tlsv1_1 or has_tlsv1_2):
44 error = """
44 error = """
45 The `ssl` module does not advertise support for TLS 1.1 or TLS 1.2.
45 The `ssl` module does not advertise support for TLS 1.1 or TLS 1.2.
46 Please make sure that your Python installation was compiled against an OpenSSL
46 Please make sure that your Python installation was compiled against an OpenSSL
47 version enabling these features (likely this requires the OpenSSL version to
47 version enabling these features (likely this requires the OpenSSL version to
48 be at least 1.0.1).
48 be at least 1.0.1).
49 """
49 """
50 print(error, file=sys.stderr)
50 print(error, file=sys.stderr)
51 sys.exit(1)
51 sys.exit(1)
52
52
53 DYLIB_SUFFIX = sysconfig.get_config_vars()['EXT_SUFFIX']
53 DYLIB_SUFFIX = sysconfig.get_config_vars()['EXT_SUFFIX']
54
54
55 # Solaris Python packaging brain damage
55 # Solaris Python packaging brain damage
56 try:
56 try:
57 import hashlib
57 import hashlib
58
58
59 sha = hashlib.sha1()
59 sha = hashlib.sha1()
60 except ImportError:
60 except ImportError:
61 try:
61 try:
62 import sha
62 import sha
63
63
64 sha.sha # silence unused import warning
64 sha.sha # silence unused import warning
65 except ImportError:
65 except ImportError:
66 raise SystemExit(
66 raise SystemExit(
67 "Couldn't import standard hashlib (incomplete Python install)."
67 "Couldn't import standard hashlib (incomplete Python install)."
68 )
68 )
69
69
70 try:
70 try:
71 import zlib
71 import zlib
72
72
73 zlib.compressobj # silence unused import warning
73 zlib.compressobj # silence unused import warning
74 except ImportError:
74 except ImportError:
75 raise SystemExit(
75 raise SystemExit(
76 "Couldn't import standard zlib (incomplete Python install)."
76 "Couldn't import standard zlib (incomplete Python install)."
77 )
77 )
78
78
79 # The base IronPython distribution (as of 2.7.1) doesn't support bz2
79 # The base IronPython distribution (as of 2.7.1) doesn't support bz2
80 isironpython = False
80 isironpython = False
81 try:
81 try:
82 isironpython = (
82 isironpython = (
83 platform.python_implementation().lower().find("ironpython") != -1
83 platform.python_implementation().lower().find("ironpython") != -1
84 )
84 )
85 except AttributeError:
85 except AttributeError:
86 pass
86 pass
87
87
88 if isironpython:
88 if isironpython:
89 sys.stderr.write("warning: IronPython detected (no bz2 support)\n")
89 sys.stderr.write("warning: IronPython detected (no bz2 support)\n")
90 else:
90 else:
91 try:
91 try:
92 import bz2
92 import bz2
93
93
94 bz2.BZ2Compressor # silence unused import warning
94 bz2.BZ2Compressor # silence unused import warning
95 except ImportError:
95 except ImportError:
96 raise SystemExit(
96 raise SystemExit(
97 "Couldn't import standard bz2 (incomplete Python install)."
97 "Couldn't import standard bz2 (incomplete Python install)."
98 )
98 )
99
99
100 ispypy = "PyPy" in sys.version
100 ispypy = "PyPy" in sys.version
101
101
102 import ctypes
102 import ctypes
103 import stat, subprocess, time
103 import stat, subprocess, time
104 import re
104 import re
105 import shutil
105 import shutil
106 import tempfile
106 import tempfile
107
107
108 # We have issues with setuptools on some platforms and builders. Until
108 # We have issues with setuptools on some platforms and builders. Until
109 # those are resolved, setuptools is opt-in except for platforms where
109 # those are resolved, setuptools is opt-in except for platforms where
110 # we don't have issues.
110 # we don't have issues.
111 issetuptools = os.name == 'nt' or 'FORCE_SETUPTOOLS' in os.environ
111 issetuptools = os.name == 'nt' or 'FORCE_SETUPTOOLS' in os.environ
112 if issetuptools:
112 if issetuptools:
113 from setuptools import setup
113 from setuptools import setup
114 else:
114 else:
115 from distutils.core import setup
115 from distutils.core import setup
116 from distutils.ccompiler import new_compiler
116 from distutils.ccompiler import new_compiler
117 from distutils.core import Command, Extension
117 from distutils.core import Command, Extension
118 from distutils.dist import Distribution
118 from distutils.dist import Distribution
119 from distutils.command.build import build
119 from distutils.command.build import build
120 from distutils.command.build_ext import build_ext
120 from distutils.command.build_ext import build_ext
121 from distutils.command.build_py import build_py
121 from distutils.command.build_py import build_py
122 from distutils.command.build_scripts import build_scripts
122 from distutils.command.build_scripts import build_scripts
123 from distutils.command.install import install
123 from distutils.command.install import install
124 from distutils.command.install_lib import install_lib
124 from distutils.command.install_lib import install_lib
125 from distutils.command.install_scripts import install_scripts
125 from distutils.command.install_scripts import install_scripts
126 from distutils import log
126 from distutils import log
127 from distutils.spawn import spawn, find_executable
127 from distutils.spawn import spawn, find_executable
128 from distutils import file_util
128 from distutils import file_util
129 from distutils.errors import (
129 from distutils.errors import (
130 CCompilerError,
130 CCompilerError,
131 DistutilsError,
131 DistutilsError,
132 DistutilsExecError,
132 DistutilsExecError,
133 )
133 )
134 from distutils.sysconfig import get_python_inc
134 from distutils.sysconfig import get_python_inc
135
135
136
136
137 def write_if_changed(path, content):
137 def write_if_changed(path, content):
138 """Write content to a file iff the content hasn't changed."""
138 """Write content to a file iff the content hasn't changed."""
139 if os.path.exists(path):
139 if os.path.exists(path):
140 with open(path, 'rb') as fh:
140 with open(path, 'rb') as fh:
141 current = fh.read()
141 current = fh.read()
142 else:
142 else:
143 current = b''
143 current = b''
144
144
145 if current != content:
145 if current != content:
146 with open(path, 'wb') as fh:
146 with open(path, 'wb') as fh:
147 fh.write(content)
147 fh.write(content)
148
148
149
149
150 scripts = ['hg']
150 scripts = ['hg']
151 if os.name == 'nt':
151 if os.name == 'nt':
152 # We remove hg.bat if we are able to build hg.exe.
152 # We remove hg.bat if we are able to build hg.exe.
153 scripts.append('contrib/win32/hg.bat')
153 scripts.append('contrib/win32/hg.bat')
154
154
155
155
156 def cancompile(cc, code):
156 def cancompile(cc, code):
157 tmpdir = tempfile.mkdtemp(prefix='hg-install-')
157 tmpdir = tempfile.mkdtemp(prefix='hg-install-')
158 devnull = oldstderr = None
158 devnull = oldstderr = None
159 try:
159 try:
160 fname = os.path.join(tmpdir, 'testcomp.c')
160 fname = os.path.join(tmpdir, 'testcomp.c')
161 f = open(fname, 'w')
161 f = open(fname, 'w')
162 f.write(code)
162 f.write(code)
163 f.close()
163 f.close()
164 # Redirect stderr to /dev/null to hide any error messages
164 # Redirect stderr to /dev/null to hide any error messages
165 # from the compiler.
165 # from the compiler.
166 # This will have to be changed if we ever have to check
166 # This will have to be changed if we ever have to check
167 # for a function on Windows.
167 # for a function on Windows.
168 devnull = open('/dev/null', 'w')
168 devnull = open('/dev/null', 'w')
169 oldstderr = os.dup(sys.stderr.fileno())
169 oldstderr = os.dup(sys.stderr.fileno())
170 os.dup2(devnull.fileno(), sys.stderr.fileno())
170 os.dup2(devnull.fileno(), sys.stderr.fileno())
171 objects = cc.compile([fname], output_dir=tmpdir)
171 objects = cc.compile([fname], output_dir=tmpdir)
172 cc.link_executable(objects, os.path.join(tmpdir, "a.out"))
172 cc.link_executable(objects, os.path.join(tmpdir, "a.out"))
173 return True
173 return True
174 except Exception:
174 except Exception:
175 return False
175 return False
176 finally:
176 finally:
177 if oldstderr is not None:
177 if oldstderr is not None:
178 os.dup2(oldstderr, sys.stderr.fileno())
178 os.dup2(oldstderr, sys.stderr.fileno())
179 if devnull is not None:
179 if devnull is not None:
180 devnull.close()
180 devnull.close()
181 shutil.rmtree(tmpdir)
181 shutil.rmtree(tmpdir)
182
182
183
183
184 # simplified version of distutils.ccompiler.CCompiler.has_function
184 # simplified version of distutils.ccompiler.CCompiler.has_function
185 # that actually removes its temporary files.
185 # that actually removes its temporary files.
186 def hasfunction(cc, funcname):
186 def hasfunction(cc, funcname):
187 code = 'int main(void) { %s(); }\n' % funcname
187 code = 'int main(void) { %s(); }\n' % funcname
188 return cancompile(cc, code)
188 return cancompile(cc, code)
189
189
190
190
191 def hasheader(cc, headername):
191 def hasheader(cc, headername):
192 code = '#include <%s>\nint main(void) { return 0; }\n' % headername
192 code = '#include <%s>\nint main(void) { return 0; }\n' % headername
193 return cancompile(cc, code)
193 return cancompile(cc, code)
194
194
195
195
196 # py2exe needs to be installed to work
196 # py2exe needs to be installed to work
197 try:
197 try:
198 import py2exe
198 import py2exe
199
199
200 py2exe.patch_distutils()
200 py2exe.patch_distutils()
201 py2exeloaded = True
201 py2exeloaded = True
202 # import py2exe's patched Distribution class
202 # import py2exe's patched Distribution class
203 from distutils.core import Distribution
203 from distutils.core import Distribution
204 except ImportError:
204 except ImportError:
205 py2exeloaded = False
205 py2exeloaded = False
206
206
207
207
208 def runcmd(cmd, env, cwd=None):
208 def runcmd(cmd, env, cwd=None):
209 p = subprocess.Popen(
209 p = subprocess.Popen(
210 cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=cwd
210 cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, cwd=cwd
211 )
211 )
212 out, err = p.communicate()
212 out, err = p.communicate()
213 return p.returncode, out, err
213 return p.returncode, out, err
214
214
215
215
216 class hgcommand:
216 class hgcommand:
217 def __init__(self, cmd, env):
217 def __init__(self, cmd, env):
218 self.cmd = cmd
218 self.cmd = cmd
219 self.env = env
219 self.env = env
220
220
221 def run(self, args):
221 def run(self, args):
222 cmd = self.cmd + args
222 cmd = self.cmd + args
223 returncode, out, err = runcmd(cmd, self.env)
223 returncode, out, err = runcmd(cmd, self.env)
224 err = filterhgerr(err)
224 err = filterhgerr(err)
225 if err:
225 if err:
226 print("stderr from '%s':" % (' '.join(cmd)), file=sys.stderr)
226 print("stderr from '%s':" % (' '.join(cmd)), file=sys.stderr)
227 print(err, file=sys.stderr)
227 print(err, file=sys.stderr)
228 if returncode != 0:
228 if returncode != 0:
229 return b''
229 return b''
230 return out
230 return out
231
231
232
232
233 def filterhgerr(err):
233 def filterhgerr(err):
234 # If root is executing setup.py, but the repository is owned by
234 # If root is executing setup.py, but the repository is owned by
235 # another user (as in "sudo python setup.py install") we will get
235 # another user (as in "sudo python setup.py install") we will get
236 # trust warnings since the .hg/hgrc file is untrusted. That is
236 # trust warnings since the .hg/hgrc file is untrusted. That is
237 # fine, we don't want to load it anyway. Python may warn about
237 # fine, we don't want to load it anyway. Python may warn about
238 # a missing __init__.py in mercurial/locale, we also ignore that.
238 # a missing __init__.py in mercurial/locale, we also ignore that.
239 err = [
239 err = [
240 e
240 e
241 for e in err.splitlines()
241 for e in err.splitlines()
242 if (
242 if (
243 not e.startswith(b'not trusting file')
243 not e.startswith(b'not trusting file')
244 and not e.startswith(b'warning: Not importing')
244 and not e.startswith(b'warning: Not importing')
245 and not e.startswith(b'obsolete feature not enabled')
245 and not e.startswith(b'obsolete feature not enabled')
246 and not e.startswith(b'*** failed to import extension')
246 and not e.startswith(b'*** failed to import extension')
247 and not e.startswith(b'devel-warn:')
247 and not e.startswith(b'devel-warn:')
248 and not (
248 and not (
249 e.startswith(b'(third party extension')
249 e.startswith(b'(third party extension')
250 and e.endswith(b'or newer of Mercurial; disabling)')
250 and e.endswith(b'or newer of Mercurial; disabling)')
251 )
251 )
252 )
252 )
253 ]
253 ]
254 return b'\n'.join(b' ' + e for e in err)
254 return b'\n'.join(b' ' + e for e in err)
255
255
256
256
257 def findhg():
257 def findhg():
258 """Try to figure out how we should invoke hg for examining the local
258 """Try to figure out how we should invoke hg for examining the local
259 repository contents.
259 repository contents.
260
260
261 Returns an hgcommand object."""
261 Returns an hgcommand object."""
262 # By default, prefer the "hg" command in the user's path. This was
262 # By default, prefer the "hg" command in the user's path. This was
263 # presumably the hg command that the user used to create this repository.
263 # presumably the hg command that the user used to create this repository.
264 #
264 #
265 # This repository may require extensions or other settings that would not
265 # This repository may require extensions or other settings that would not
266 # be enabled by running the hg script directly from this local repository.
266 # be enabled by running the hg script directly from this local repository.
267 hgenv = os.environ.copy()
267 hgenv = os.environ.copy()
268 # Use HGPLAIN to disable hgrc settings that would change output formatting,
268 # Use HGPLAIN to disable hgrc settings that would change output formatting,
269 # and disable localization for the same reasons.
269 # and disable localization for the same reasons.
270 hgenv['HGPLAIN'] = '1'
270 hgenv['HGPLAIN'] = '1'
271 hgenv['LANGUAGE'] = 'C'
271 hgenv['LANGUAGE'] = 'C'
272 hgcmd = ['hg']
272 hgcmd = ['hg']
273 # Run a simple "hg log" command just to see if using hg from the user's
273 # Run a simple "hg log" command just to see if using hg from the user's
274 # path works and can successfully interact with this repository. Windows
274 # path works and can successfully interact with this repository. Windows
275 # gives precedence to hg.exe in the current directory, so fall back to the
275 # gives precedence to hg.exe in the current directory, so fall back to the
276 # python invocation of local hg, where pythonXY.dll can always be found.
276 # python invocation of local hg, where pythonXY.dll can always be found.
277 check_cmd = ['log', '-r.', '-Ttest']
277 check_cmd = ['log', '-r.', '-Ttest']
278 if os.name != 'nt' or not os.path.exists("hg.exe"):
278 if os.name != 'nt' or not os.path.exists("hg.exe"):
279 try:
279 try:
280 retcode, out, err = runcmd(hgcmd + check_cmd, hgenv)
280 retcode, out, err = runcmd(hgcmd + check_cmd, hgenv)
281 except EnvironmentError:
281 except EnvironmentError:
282 retcode = -1
282 retcode = -1
283 if retcode == 0 and not filterhgerr(err):
283 if retcode == 0 and not filterhgerr(err):
284 return hgcommand(hgcmd, hgenv)
284 return hgcommand(hgcmd, hgenv)
285
285
286 # Fall back to trying the local hg installation.
286 # Fall back to trying the local hg installation.
287 hgenv = localhgenv()
287 hgenv = localhgenv()
288 hgcmd = [sys.executable, 'hg']
288 hgcmd = [sys.executable, 'hg']
289 try:
289 try:
290 retcode, out, err = runcmd(hgcmd + check_cmd, hgenv)
290 retcode, out, err = runcmd(hgcmd + check_cmd, hgenv)
291 except EnvironmentError:
291 except EnvironmentError:
292 retcode = -1
292 retcode = -1
293 if retcode == 0 and not filterhgerr(err):
293 if retcode == 0 and not filterhgerr(err):
294 return hgcommand(hgcmd, hgenv)
294 return hgcommand(hgcmd, hgenv)
295
295
296 eprint("/!\\")
296 eprint("/!\\")
297 eprint(r"/!\ Unable to find a working hg binary")
297 eprint(r"/!\ Unable to find a working hg binary")
298 eprint(r"/!\ Version cannot be extract from the repository")
298 eprint(r"/!\ Version cannot be extract from the repository")
299 eprint(r"/!\ Re-run the setup once a first version is built")
299 eprint(r"/!\ Re-run the setup once a first version is built")
300 return None
300 return None
301
301
302
302
303 def localhgenv():
303 def localhgenv():
304 """Get an environment dictionary to use for invoking or importing
304 """Get an environment dictionary to use for invoking or importing
305 mercurial from the local repository."""
305 mercurial from the local repository."""
306 # Execute hg out of this directory with a custom environment which takes
306 # Execute hg out of this directory with a custom environment which takes
307 # care to not use any hgrc files and do no localization.
307 # care to not use any hgrc files and do no localization.
308 env = {
308 env = {
309 'HGMODULEPOLICY': 'py',
309 'HGMODULEPOLICY': 'py',
310 'HGRCPATH': '',
310 'HGRCPATH': '',
311 'LANGUAGE': 'C',
311 'LANGUAGE': 'C',
312 'PATH': '',
312 'PATH': '',
313 } # make pypi modules that use os.environ['PATH'] happy
313 } # make pypi modules that use os.environ['PATH'] happy
314 if 'LD_LIBRARY_PATH' in os.environ:
314 if 'LD_LIBRARY_PATH' in os.environ:
315 env['LD_LIBRARY_PATH'] = os.environ['LD_LIBRARY_PATH']
315 env['LD_LIBRARY_PATH'] = os.environ['LD_LIBRARY_PATH']
316 if 'SystemRoot' in os.environ:
316 if 'SystemRoot' in os.environ:
317 # SystemRoot is required by Windows to load various DLLs. See:
317 # SystemRoot is required by Windows to load various DLLs. See:
318 # https://bugs.python.org/issue13524#msg148850
318 # https://bugs.python.org/issue13524#msg148850
319 env['SystemRoot'] = os.environ['SystemRoot']
319 env['SystemRoot'] = os.environ['SystemRoot']
320 return env
320 return env
321
321
322
322
323 version = ''
323 version = ''
324
324
325
325
326 def _try_get_version():
326 def _try_get_version():
327 hg = findhg()
327 hg = findhg()
328 if hg is None:
328 if hg is None:
329 return ''
329 return ''
330 hgid = None
330 hgid = None
331 numerictags = []
331 numerictags = []
332 cmd = ['log', '-r', '.', '--template', '{tags}\n']
332 cmd = ['log', '-r', '.', '--template', '{tags}\n']
333 pieces = sysstr(hg.run(cmd)).split()
333 pieces = sysstr(hg.run(cmd)).split()
334 numerictags = [t for t in pieces if t[0:1].isdigit()]
334 numerictags = [t for t in pieces if t[0:1].isdigit()]
335 hgid = sysstr(hg.run(['id', '-i'])).strip()
335 hgid = sysstr(hg.run(['id', '-i'])).strip()
336 if hgid.count('+') == 2:
336 if hgid.count('+') == 2:
337 hgid = hgid.replace("+", ".", 1)
337 hgid = hgid.replace("+", ".", 1)
338 if not hgid:
338 if not hgid:
339 eprint("/!\\")
339 eprint("/!\\")
340 eprint(r"/!\ Unable to determine hg version from local repository")
340 eprint(r"/!\ Unable to determine hg version from local repository")
341 eprint(r"/!\ Failed to retrieve current revision tags")
341 eprint(r"/!\ Failed to retrieve current revision tags")
342 return ''
342 return ''
343 if numerictags: # tag(s) found
343 if numerictags: # tag(s) found
344 version = numerictags[-1]
344 version = numerictags[-1]
345 if hgid.endswith('+'): # propagate the dirty status to the tag
345 if hgid.endswith('+'): # propagate the dirty status to the tag
346 version += '+'
346 version += '+'
347 else: # no tag found on the checked out revision
347 else: # no tag found on the checked out revision
348 ltagcmd = ['log', '--rev', 'wdir()', '--template', '{latesttag}']
348 ltagcmd = ['log', '--rev', 'wdir()', '--template', '{latesttag}']
349 ltag = sysstr(hg.run(ltagcmd))
349 ltag = sysstr(hg.run(ltagcmd))
350 if not ltag:
350 if not ltag:
351 eprint("/!\\")
351 eprint("/!\\")
352 eprint(r"/!\ Unable to determine hg version from local repository")
352 eprint(r"/!\ Unable to determine hg version from local repository")
353 eprint(
353 eprint(
354 r"/!\ Failed to retrieve current revision distance to lated tag"
354 r"/!\ Failed to retrieve current revision distance to lated tag"
355 )
355 )
356 return ''
356 return ''
357 changessincecmd = [
357 changessincecmd = [
358 'log',
358 'log',
359 '-T',
359 '-T',
360 'x\n',
360 'x\n',
361 '-r',
361 '-r',
362 "only(parents(),'%s')" % ltag,
362 "only(parents(),'%s')" % ltag,
363 ]
363 ]
364 changessince = len(hg.run(changessincecmd).splitlines())
364 changessince = len(hg.run(changessincecmd).splitlines())
365 version = '%s+hg%s.%s' % (ltag, changessince, hgid)
365 version = '%s+hg%s.%s' % (ltag, changessince, hgid)
366 if version.endswith('+'):
366 if version.endswith('+'):
367 version = version[:-1] + 'local' + time.strftime('%Y%m%d')
367 version = version[:-1] + 'local' + time.strftime('%Y%m%d')
368 return version
368 return version
369
369
370
370
371 if os.path.isdir('.hg'):
371 if os.path.isdir('.hg'):
372 version = _try_get_version()
372 version = _try_get_version()
373 elif os.path.exists('.hg_archival.txt'):
373 elif os.path.exists('.hg_archival.txt'):
374 kw = dict(
374 kw = dict(
375 [[t.strip() for t in l.split(':', 1)] for l in open('.hg_archival.txt')]
375 [[t.strip() for t in l.split(':', 1)] for l in open('.hg_archival.txt')]
376 )
376 )
377 if 'tag' in kw:
377 if 'tag' in kw:
378 version = kw['tag']
378 version = kw['tag']
379 elif 'latesttag' in kw:
379 elif 'latesttag' in kw:
380 if 'changessincelatesttag' in kw:
380 if 'changessincelatesttag' in kw:
381 version = (
381 version = (
382 '%(latesttag)s+hg%(changessincelatesttag)s.%(node).12s' % kw
382 '%(latesttag)s+hg%(changessincelatesttag)s.%(node).12s' % kw
383 )
383 )
384 else:
384 else:
385 version = '%(latesttag)s+hg%(latesttagdistance)s.%(node).12s' % kw
385 version = '%(latesttag)s+hg%(latesttagdistance)s.%(node).12s' % kw
386 else:
386 else:
387 version = '0+hg' + kw.get('node', '')[:12]
387 version = '0+hg' + kw.get('node', '')[:12]
388 elif os.path.exists('mercurial/__version__.py'):
388 elif os.path.exists('mercurial/__version__.py'):
389 with open('mercurial/__version__.py') as f:
389 with open('mercurial/__version__.py') as f:
390 data = f.read()
390 data = f.read()
391 version = re.search('version = b"(.*)"', data).group(1)
391 version = re.search('version = b"(.*)"', data).group(1)
392 if not version:
392 if not version:
393 if os.environ.get("MERCURIAL_SETUP_MAKE_LOCAL") == "1":
393 if os.environ.get("MERCURIAL_SETUP_MAKE_LOCAL") == "1":
394 version = "0.0+0"
394 version = "0.0+0"
395 eprint("/!\\")
395 eprint("/!\\")
396 eprint(r"/!\ Using '0.0+0' as the default version")
396 eprint(r"/!\ Using '0.0+0' as the default version")
397 eprint(r"/!\ Re-run make local once that first version is built")
397 eprint(r"/!\ Re-run make local once that first version is built")
398 eprint("/!\\")
398 eprint("/!\\")
399 else:
399 else:
400 eprint("/!\\")
400 eprint("/!\\")
401 eprint(r"/!\ Could not determine the Mercurial version")
401 eprint(r"/!\ Could not determine the Mercurial version")
402 eprint(r"/!\ You need to build a local version first")
402 eprint(r"/!\ You need to build a local version first")
403 eprint(r"/!\ Run `make local` and try again")
403 eprint(r"/!\ Run `make local` and try again")
404 eprint("/!\\")
404 eprint("/!\\")
405 msg = "Run `make local` first to get a working local version"
405 msg = "Run `make local` first to get a working local version"
406 raise SystemExit(msg)
406 raise SystemExit(msg)
407
407
408 versionb = version
408 versionb = version
409 if not isinstance(versionb, bytes):
409 if not isinstance(versionb, bytes):
410 versionb = versionb.encode('ascii')
410 versionb = versionb.encode('ascii')
411
411
412 write_if_changed(
412 write_if_changed(
413 'mercurial/__version__.py',
413 'mercurial/__version__.py',
414 b''.join(
414 b''.join(
415 [
415 [
416 b'# this file is autogenerated by setup.py\n'
416 b'# this file is autogenerated by setup.py\n'
417 b'version = b"%s"\n' % versionb,
417 b'version = b"%s"\n' % versionb,
418 ]
418 ]
419 ),
419 ),
420 )
420 )
421
421
422
422
423 class hgbuild(build):
423 class hgbuild(build):
424 # Insert hgbuildmo first so that files in mercurial/locale/ are found
424 # Insert hgbuildmo first so that files in mercurial/locale/ are found
425 # when build_py is run next.
425 # when build_py is run next.
426 sub_commands = [('build_mo', None)] + build.sub_commands
426 sub_commands = [('build_mo', None)] + build.sub_commands
427
427
428
428
429 class hgbuildmo(build):
429 class hgbuildmo(build):
430
430
431 description = "build translations (.mo files)"
431 description = "build translations (.mo files)"
432
432
433 def run(self):
433 def run(self):
434 if not find_executable('msgfmt'):
434 if not find_executable('msgfmt'):
435 self.warn(
435 self.warn(
436 "could not find msgfmt executable, no translations "
436 "could not find msgfmt executable, no translations "
437 "will be built"
437 "will be built"
438 )
438 )
439 return
439 return
440
440
441 podir = 'i18n'
441 podir = 'i18n'
442 if not os.path.isdir(podir):
442 if not os.path.isdir(podir):
443 self.warn("could not find %s/ directory" % podir)
443 self.warn("could not find %s/ directory" % podir)
444 return
444 return
445
445
446 join = os.path.join
446 join = os.path.join
447 for po in os.listdir(podir):
447 for po in os.listdir(podir):
448 if not po.endswith('.po'):
448 if not po.endswith('.po'):
449 continue
449 continue
450 pofile = join(podir, po)
450 pofile = join(podir, po)
451 modir = join('locale', po[:-3], 'LC_MESSAGES')
451 modir = join('locale', po[:-3], 'LC_MESSAGES')
452 mofile = join(modir, 'hg.mo')
452 mofile = join(modir, 'hg.mo')
453 mobuildfile = join('mercurial', mofile)
453 mobuildfile = join('mercurial', mofile)
454 cmd = ['msgfmt', '-v', '-o', mobuildfile, pofile]
454 cmd = ['msgfmt', '-v', '-o', mobuildfile, pofile]
455 if sys.platform != 'sunos5':
455 if sys.platform != 'sunos5':
456 # msgfmt on Solaris does not know about -c
456 # msgfmt on Solaris does not know about -c
457 cmd.append('-c')
457 cmd.append('-c')
458 self.mkpath(join('mercurial', modir))
458 self.mkpath(join('mercurial', modir))
459 self.make_file([pofile], mobuildfile, spawn, (cmd,))
459 self.make_file([pofile], mobuildfile, spawn, (cmd,))
460
460
461
461
462 class hgdist(Distribution):
462 class hgdist(Distribution):
463 pure = False
463 pure = False
464 rust = False
464 rust = False
465 no_rust = False
465 no_rust = False
466 cffi = ispypy
466 cffi = ispypy
467
467
468 global_options = Distribution.global_options + [
468 global_options = Distribution.global_options + [
469 ('pure', None, "use pure (slow) Python code instead of C extensions"),
469 ('pure', None, "use pure (slow) Python code instead of C extensions"),
470 ('rust', None, "use Rust extensions additionally to C extensions"),
470 ('rust', None, "use Rust extensions additionally to C extensions"),
471 (
471 (
472 'no-rust',
472 'no-rust',
473 None,
473 None,
474 "do not use Rust extensions additionally to C extensions",
474 "do not use Rust extensions additionally to C extensions",
475 ),
475 ),
476 ]
476 ]
477
477
478 negative_opt = Distribution.negative_opt.copy()
478 negative_opt = Distribution.negative_opt.copy()
479 boolean_options = ['pure', 'rust', 'no-rust']
479 boolean_options = ['pure', 'rust', 'no-rust']
480 negative_opt['no-rust'] = 'rust'
480 negative_opt['no-rust'] = 'rust'
481
481
482 def _set_command_options(self, command_obj, option_dict=None):
482 def _set_command_options(self, command_obj, option_dict=None):
483 # Not all distutils versions in the wild have boolean_options.
483 # Not all distutils versions in the wild have boolean_options.
484 # This should be cleaned up when we're Python 3 only.
484 # This should be cleaned up when we're Python 3 only.
485 command_obj.boolean_options = (
485 command_obj.boolean_options = (
486 getattr(command_obj, 'boolean_options', []) + self.boolean_options
486 getattr(command_obj, 'boolean_options', []) + self.boolean_options
487 )
487 )
488 return Distribution._set_command_options(
488 return Distribution._set_command_options(
489 self, command_obj, option_dict=option_dict
489 self, command_obj, option_dict=option_dict
490 )
490 )
491
491
492 def parse_command_line(self):
492 def parse_command_line(self):
493 ret = Distribution.parse_command_line(self)
493 ret = Distribution.parse_command_line(self)
494 if not (self.rust or self.no_rust):
494 if not (self.rust or self.no_rust):
495 hgrustext = os.environ.get('HGWITHRUSTEXT')
495 hgrustext = os.environ.get('HGWITHRUSTEXT')
496 # TODO record it for proper rebuild upon changes
496 # TODO record it for proper rebuild upon changes
497 # (see mercurial/__modulepolicy__.py)
497 # (see mercurial/__modulepolicy__.py)
498 if hgrustext != 'cpython' and hgrustext is not None:
498 if hgrustext != 'cpython' and hgrustext is not None:
499 if hgrustext:
499 if hgrustext:
500 msg = 'unknown HGWITHRUSTEXT value: %s' % hgrustext
500 msg = 'unknown HGWITHRUSTEXT value: %s' % hgrustext
501 print(msg, file=sys.stderr)
501 print(msg, file=sys.stderr)
502 hgrustext = None
502 hgrustext = None
503 self.rust = hgrustext is not None
503 self.rust = hgrustext is not None
504 self.no_rust = not self.rust
504 self.no_rust = not self.rust
505 return ret
505 return ret
506
506
507 def has_ext_modules(self):
507 def has_ext_modules(self):
508 # self.ext_modules is emptied in hgbuildpy.finalize_options which is
508 # self.ext_modules is emptied in hgbuildpy.finalize_options which is
509 # too late for some cases
509 # too late for some cases
510 return not self.pure and Distribution.has_ext_modules(self)
510 return not self.pure and Distribution.has_ext_modules(self)
511
511
512
512
513 # This is ugly as a one-liner. So use a variable.
513 # This is ugly as a one-liner. So use a variable.
514 buildextnegops = dict(getattr(build_ext, 'negative_options', {}))
514 buildextnegops = dict(getattr(build_ext, 'negative_options', {}))
515 buildextnegops['no-zstd'] = 'zstd'
515 buildextnegops['no-zstd'] = 'zstd'
516 buildextnegops['no-rust'] = 'rust'
516 buildextnegops['no-rust'] = 'rust'
517
517
518
518
519 class hgbuildext(build_ext):
519 class hgbuildext(build_ext):
520 user_options = build_ext.user_options + [
520 user_options = build_ext.user_options + [
521 ('zstd', None, 'compile zstd bindings [default]'),
521 ('zstd', None, 'compile zstd bindings [default]'),
522 ('no-zstd', None, 'do not compile zstd bindings'),
522 ('no-zstd', None, 'do not compile zstd bindings'),
523 (
523 (
524 'rust',
524 'rust',
525 None,
525 None,
526 'compile Rust extensions if they are in use '
526 'compile Rust extensions if they are in use '
527 '(requires Cargo) [default]',
527 '(requires Cargo) [default]',
528 ),
528 ),
529 ('no-rust', None, 'do not compile Rust extensions'),
529 ('no-rust', None, 'do not compile Rust extensions'),
530 ]
530 ]
531
531
532 boolean_options = build_ext.boolean_options + ['zstd', 'rust']
532 boolean_options = build_ext.boolean_options + ['zstd', 'rust']
533 negative_opt = buildextnegops
533 negative_opt = buildextnegops
534
534
535 def initialize_options(self):
535 def initialize_options(self):
536 self.zstd = True
536 self.zstd = True
537 self.rust = True
537 self.rust = True
538
538
539 return build_ext.initialize_options(self)
539 return build_ext.initialize_options(self)
540
540
541 def finalize_options(self):
541 def finalize_options(self):
542 # Unless overridden by the end user, build extensions in parallel.
542 # Unless overridden by the end user, build extensions in parallel.
543 # Only influences behavior on Python 3.5+.
543 # Only influences behavior on Python 3.5+.
544 if getattr(self, 'parallel', None) is None:
544 if getattr(self, 'parallel', None) is None:
545 self.parallel = True
545 self.parallel = True
546
546
547 return build_ext.finalize_options(self)
547 return build_ext.finalize_options(self)
548
548
549 def build_extensions(self):
549 def build_extensions(self):
550 ruststandalones = [
550 ruststandalones = [
551 e for e in self.extensions if isinstance(e, RustStandaloneExtension)
551 e for e in self.extensions if isinstance(e, RustStandaloneExtension)
552 ]
552 ]
553 self.extensions = [
553 self.extensions = [
554 e for e in self.extensions if e not in ruststandalones
554 e for e in self.extensions if e not in ruststandalones
555 ]
555 ]
556 # Filter out zstd if disabled via argument.
556 # Filter out zstd if disabled via argument.
557 if not self.zstd:
557 if not self.zstd:
558 self.extensions = [
558 self.extensions = [
559 e for e in self.extensions if e.name != 'mercurial.zstd'
559 e for e in self.extensions if e.name != 'mercurial.zstd'
560 ]
560 ]
561
561
562 # Build Rust standalone extensions if it'll be used
562 # Build Rust standalone extensions if it'll be used
563 # and its build is not explicitly disabled (for external build
563 # and its build is not explicitly disabled (for external build
564 # as Linux distributions would do)
564 # as Linux distributions would do)
565 if self.distribution.rust and self.rust:
565 if self.distribution.rust and self.rust:
566 if not sys.platform.startswith('linux'):
566 if not sys.platform.startswith('linux'):
567 self.warn(
567 self.warn(
568 "rust extensions have only been tested on Linux "
568 "rust extensions have only been tested on Linux "
569 "and may not behave correctly on other platforms"
569 "and may not behave correctly on other platforms"
570 )
570 )
571
571
572 for rustext in ruststandalones:
572 for rustext in ruststandalones:
573 rustext.build('' if self.inplace else self.build_lib)
573 rustext.build('' if self.inplace else self.build_lib)
574
574
575 return build_ext.build_extensions(self)
575 return build_ext.build_extensions(self)
576
576
577 def build_extension(self, ext):
577 def build_extension(self, ext):
578 if (
578 if (
579 self.distribution.rust
579 self.distribution.rust
580 and self.rust
580 and self.rust
581 and isinstance(ext, RustExtension)
581 and isinstance(ext, RustExtension)
582 ):
582 ):
583 ext.rustbuild()
583 ext.rustbuild()
584 try:
584 try:
585 build_ext.build_extension(self, ext)
585 build_ext.build_extension(self, ext)
586 except CCompilerError:
586 except CCompilerError:
587 if not getattr(ext, 'optional', False):
587 if not getattr(ext, 'optional', False):
588 raise
588 raise
589 log.warn(
589 log.warn(
590 "Failed to build optional extension '%s' (skipping)", ext.name
590 "Failed to build optional extension '%s' (skipping)", ext.name
591 )
591 )
592
592
593
593
594 class hgbuildscripts(build_scripts):
594 class hgbuildscripts(build_scripts):
595 def run(self):
595 def run(self):
596 if os.name != 'nt' or self.distribution.pure:
596 if os.name != 'nt' or self.distribution.pure:
597 return build_scripts.run(self)
597 return build_scripts.run(self)
598
598
599 exebuilt = False
599 exebuilt = False
600 try:
600 try:
601 self.run_command('build_hgexe')
601 self.run_command('build_hgexe')
602 exebuilt = True
602 exebuilt = True
603 except (DistutilsError, CCompilerError):
603 except (DistutilsError, CCompilerError):
604 log.warn('failed to build optional hg.exe')
604 log.warn('failed to build optional hg.exe')
605
605
606 if exebuilt:
606 if exebuilt:
607 # Copying hg.exe to the scripts build directory ensures it is
607 # Copying hg.exe to the scripts build directory ensures it is
608 # installed by the install_scripts command.
608 # installed by the install_scripts command.
609 hgexecommand = self.get_finalized_command('build_hgexe')
609 hgexecommand = self.get_finalized_command('build_hgexe')
610 dest = os.path.join(self.build_dir, 'hg.exe')
610 dest = os.path.join(self.build_dir, 'hg.exe')
611 self.mkpath(self.build_dir)
611 self.mkpath(self.build_dir)
612 self.copy_file(hgexecommand.hgexepath, dest)
612 self.copy_file(hgexecommand.hgexepath, dest)
613
613
614 # Remove hg.bat because it is redundant with hg.exe.
614 # Remove hg.bat because it is redundant with hg.exe.
615 self.scripts.remove('contrib/win32/hg.bat')
615 self.scripts.remove('contrib/win32/hg.bat')
616
616
617 return build_scripts.run(self)
617 return build_scripts.run(self)
618
618
619
619
620 class hgbuildpy(build_py):
620 class hgbuildpy(build_py):
621 def finalize_options(self):
621 def finalize_options(self):
622 build_py.finalize_options(self)
622 build_py.finalize_options(self)
623
623
624 if self.distribution.pure:
624 if self.distribution.pure:
625 self.distribution.ext_modules = []
625 self.distribution.ext_modules = []
626 elif self.distribution.cffi:
626 elif self.distribution.cffi:
627 from mercurial.cffi import (
627 from mercurial.cffi import (
628 bdiffbuild,
628 bdiffbuild,
629 mpatchbuild,
629 mpatchbuild,
630 )
630 )
631
631
632 exts = [
632 exts = [
633 mpatchbuild.ffi.distutils_extension(),
633 mpatchbuild.ffi.distutils_extension(),
634 bdiffbuild.ffi.distutils_extension(),
634 bdiffbuild.ffi.distutils_extension(),
635 ]
635 ]
636 # cffi modules go here
636 # cffi modules go here
637 if sys.platform == 'darwin':
637 if sys.platform == 'darwin':
638 from mercurial.cffi import osutilbuild
638 from mercurial.cffi import osutilbuild
639
639
640 exts.append(osutilbuild.ffi.distutils_extension())
640 exts.append(osutilbuild.ffi.distutils_extension())
641 self.distribution.ext_modules = exts
641 self.distribution.ext_modules = exts
642 else:
642 else:
643 h = os.path.join(get_python_inc(), 'Python.h')
643 h = os.path.join(get_python_inc(), 'Python.h')
644 if not os.path.exists(h):
644 if not os.path.exists(h):
645 raise SystemExit(
645 raise SystemExit(
646 'Python headers are required to build '
646 'Python headers are required to build '
647 'Mercurial but weren\'t found in %s' % h
647 'Mercurial but weren\'t found in %s' % h
648 )
648 )
649
649
650 def run(self):
650 def run(self):
651 basepath = os.path.join(self.build_lib, 'mercurial')
651 basepath = os.path.join(self.build_lib, 'mercurial')
652 self.mkpath(basepath)
652 self.mkpath(basepath)
653
653
654 rust = self.distribution.rust
654 rust = self.distribution.rust
655 if self.distribution.pure:
655 if self.distribution.pure:
656 modulepolicy = 'py'
656 modulepolicy = 'py'
657 elif self.build_lib == '.':
657 elif self.build_lib == '.':
658 # in-place build should run without rebuilding and Rust extensions
658 # in-place build should run without rebuilding and Rust extensions
659 modulepolicy = 'rust+c-allow' if rust else 'allow'
659 modulepolicy = 'rust+c-allow' if rust else 'allow'
660 else:
660 else:
661 modulepolicy = 'rust+c' if rust else 'c'
661 modulepolicy = 'rust+c' if rust else 'c'
662
662
663 content = b''.join(
663 content = b''.join(
664 [
664 [
665 b'# this file is autogenerated by setup.py\n',
665 b'# this file is autogenerated by setup.py\n',
666 b'modulepolicy = b"%s"\n' % modulepolicy.encode('ascii'),
666 b'modulepolicy = b"%s"\n' % modulepolicy.encode('ascii'),
667 ]
667 ]
668 )
668 )
669 write_if_changed(os.path.join(basepath, '__modulepolicy__.py'), content)
669 write_if_changed(os.path.join(basepath, '__modulepolicy__.py'), content)
670
670
671 build_py.run(self)
671 build_py.run(self)
672
672
673
673
674 class buildhgextindex(Command):
674 class buildhgextindex(Command):
675 description = 'generate prebuilt index of hgext (for frozen package)'
675 description = 'generate prebuilt index of hgext (for frozen package)'
676 user_options = []
676 user_options = []
677 _indexfilename = 'hgext/__index__.py'
677 _indexfilename = 'hgext/__index__.py'
678
678
679 def initialize_options(self):
679 def initialize_options(self):
680 pass
680 pass
681
681
682 def finalize_options(self):
682 def finalize_options(self):
683 pass
683 pass
684
684
685 def run(self):
685 def run(self):
686 if os.path.exists(self._indexfilename):
686 if os.path.exists(self._indexfilename):
687 with open(self._indexfilename, 'w') as f:
687 with open(self._indexfilename, 'w') as f:
688 f.write('# empty\n')
688 f.write('# empty\n')
689
689
690 # here no extension enabled, disabled() lists up everything
690 # here no extension enabled, disabled() lists up everything
691 code = (
691 code = (
692 'import pprint; from mercurial import extensions; '
692 'import pprint; from mercurial import extensions; '
693 'ext = extensions.disabled();'
693 'ext = extensions.disabled();'
694 'ext.pop("__index__", None);'
694 'ext.pop("__index__", None);'
695 'pprint.pprint(ext)'
695 'pprint.pprint(ext)'
696 )
696 )
697 returncode, out, err = runcmd(
697 returncode, out, err = runcmd(
698 [sys.executable, '-c', code], localhgenv()
698 [sys.executable, '-c', code], localhgenv()
699 )
699 )
700 if err or returncode != 0:
700 if err or returncode != 0:
701 raise DistutilsExecError(err)
701 raise DistutilsExecError(err)
702
702
703 with open(self._indexfilename, 'wb') as f:
703 with open(self._indexfilename, 'wb') as f:
704 f.write(b'# this file is autogenerated by setup.py\n')
704 f.write(b'# this file is autogenerated by setup.py\n')
705 f.write(b'docs = ')
705 f.write(b'docs = ')
706 f.write(out)
706 f.write(out)
707
707
708
708
709 class buildhgexe(build_ext):
709 class buildhgexe(build_ext):
710 description = 'compile hg.exe from mercurial/exewrapper.c'
710 description = 'compile hg.exe from mercurial/exewrapper.c'
711
711
712 LONG_PATHS_MANIFEST = """\
712 LONG_PATHS_MANIFEST = """\
713 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
713 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
714 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
714 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
715 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
715 <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
716 <security>
716 <security>
717 <requestedPrivileges>
717 <requestedPrivileges>
718 <requestedExecutionLevel
718 <requestedExecutionLevel
719 level="asInvoker"
719 level="asInvoker"
720 uiAccess="false"
720 uiAccess="false"
721 />
721 />
722 </requestedPrivileges>
722 </requestedPrivileges>
723 </security>
723 </security>
724 </trustInfo>
724 </trustInfo>
725 <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
725 <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
726 <application>
726 <application>
727 <!-- Windows Vista -->
727 <!-- Windows Vista -->
728 <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
728 <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
729 <!-- Windows 7 -->
729 <!-- Windows 7 -->
730 <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
730 <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
731 <!-- Windows 8 -->
731 <!-- Windows 8 -->
732 <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
732 <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
733 <!-- Windows 8.1 -->
733 <!-- Windows 8.1 -->
734 <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
734 <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
735 <!-- Windows 10 and Windows 11 -->
735 <!-- Windows 10 and Windows 11 -->
736 <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
736 <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
737 </application>
737 </application>
738 </compatibility>
738 </compatibility>
739 <application xmlns="urn:schemas-microsoft-com:asm.v3">
739 <application xmlns="urn:schemas-microsoft-com:asm.v3">
740 <windowsSettings
740 <windowsSettings
741 xmlns:ws2="http://schemas.microsoft.com/SMI/2016/WindowsSettings">
741 xmlns:ws2="http://schemas.microsoft.com/SMI/2016/WindowsSettings">
742 <ws2:longPathAware>true</ws2:longPathAware>
742 <ws2:longPathAware>true</ws2:longPathAware>
743 </windowsSettings>
743 </windowsSettings>
744 </application>
744 </application>
745 <dependency>
745 <dependency>
746 <dependentAssembly>
746 <dependentAssembly>
747 <assemblyIdentity type="win32"
747 <assemblyIdentity type="win32"
748 name="Microsoft.Windows.Common-Controls"
748 name="Microsoft.Windows.Common-Controls"
749 version="6.0.0.0"
749 version="6.0.0.0"
750 processorArchitecture="*"
750 processorArchitecture="*"
751 publicKeyToken="6595b64144ccf1df"
751 publicKeyToken="6595b64144ccf1df"
752 language="*" />
752 language="*" />
753 </dependentAssembly>
753 </dependentAssembly>
754 </dependency>
754 </dependency>
755 </assembly>
755 </assembly>
756 """
756 """
757
757
758 def initialize_options(self):
758 def initialize_options(self):
759 build_ext.initialize_options(self)
759 build_ext.initialize_options(self)
760
760
761 def build_extensions(self):
761 def build_extensions(self):
762 if os.name != 'nt':
762 if os.name != 'nt':
763 return
763 return
764 if isinstance(self.compiler, HackedMingw32CCompiler):
764 if isinstance(self.compiler, HackedMingw32CCompiler):
765 self.compiler.compiler_so = self.compiler.compiler # no -mdll
765 self.compiler.compiler_so = self.compiler.compiler # no -mdll
766 self.compiler.dll_libraries = [] # no -lmsrvc90
766 self.compiler.dll_libraries = [] # no -lmsrvc90
767
767
768 pythonlib = None
768 pythonlib = None
769
769
770 dirname = os.path.dirname(self.get_ext_fullpath('dummy'))
770 dirname = os.path.dirname(self.get_ext_fullpath('dummy'))
771 self.hgtarget = os.path.join(dirname, 'hg')
771 self.hgtarget = os.path.join(dirname, 'hg')
772
772
773 if getattr(sys, 'dllhandle', None):
773 if getattr(sys, 'dllhandle', None):
774 # Different Python installs can have different Python library
774 # Different Python installs can have different Python library
775 # names. e.g. the official CPython distribution uses pythonXY.dll
775 # names. e.g. the official CPython distribution uses pythonXY.dll
776 # and MinGW uses libpythonX.Y.dll.
776 # and MinGW uses libpythonX.Y.dll.
777 _kernel32 = ctypes.windll.kernel32
777 _kernel32 = ctypes.windll.kernel32
778 _kernel32.GetModuleFileNameA.argtypes = [
778 _kernel32.GetModuleFileNameA.argtypes = [
779 ctypes.c_void_p,
779 ctypes.c_void_p,
780 ctypes.c_void_p,
780 ctypes.c_void_p,
781 ctypes.c_ulong,
781 ctypes.c_ulong,
782 ]
782 ]
783 _kernel32.GetModuleFileNameA.restype = ctypes.c_ulong
783 _kernel32.GetModuleFileNameA.restype = ctypes.c_ulong
784 size = 1000
784 size = 1000
785 buf = ctypes.create_string_buffer(size + 1)
785 buf = ctypes.create_string_buffer(size + 1)
786 filelen = _kernel32.GetModuleFileNameA(
786 filelen = _kernel32.GetModuleFileNameA(
787 sys.dllhandle, ctypes.byref(buf), size
787 sys.dllhandle, ctypes.byref(buf), size
788 )
788 )
789
789
790 if filelen > 0 and filelen != size:
790 if filelen > 0 and filelen != size:
791 dllbasename = os.path.basename(buf.value)
791 dllbasename = os.path.basename(buf.value)
792 if not dllbasename.lower().endswith(b'.dll'):
792 if not dllbasename.lower().endswith(b'.dll'):
793 raise SystemExit(
793 raise SystemExit(
794 'Python DLL does not end with .dll: %s' % dllbasename
794 'Python DLL does not end with .dll: %s' % dllbasename
795 )
795 )
796 pythonlib = dllbasename[:-4]
796 pythonlib = dllbasename[:-4]
797
797
798 # Copy the pythonXY.dll next to the binary so that it runs
798 # Copy the pythonXY.dll next to the binary so that it runs
799 # without tampering with PATH.
799 # without tampering with PATH.
800 dest = os.path.join(
800 dest = os.path.join(
801 os.path.dirname(self.hgtarget),
801 os.path.dirname(self.hgtarget),
802 os.fsdecode(dllbasename),
802 os.fsdecode(dllbasename),
803 )
803 )
804
804
805 if not os.path.exists(dest):
805 if not os.path.exists(dest):
806 shutil.copy(buf.value, dest)
806 shutil.copy(buf.value, dest)
807
807
808 # Also overwrite python3.dll so that hgext.git is usable.
808 # Also overwrite python3.dll so that hgext.git is usable.
809 # TODO: also handle the MSYS flavor
809 # TODO: also handle the MSYS flavor
810 python_x = os.path.join(
810 python_x = os.path.join(
811 os.path.dirname(os.fsdecode(buf.value)),
811 os.path.dirname(os.fsdecode(buf.value)),
812 "python3.dll",
812 "python3.dll",
813 )
813 )
814
814
815 if os.path.exists(python_x):
815 if os.path.exists(python_x):
816 dest = os.path.join(
816 dest = os.path.join(
817 os.path.dirname(self.hgtarget),
817 os.path.dirname(self.hgtarget),
818 os.path.basename(python_x),
818 os.path.basename(python_x),
819 )
819 )
820
820
821 shutil.copy(python_x, dest)
821 shutil.copy(python_x, dest)
822
822
823 if not pythonlib:
823 if not pythonlib:
824 log.warn(
824 log.warn(
825 'could not determine Python DLL filename; assuming pythonXY'
825 'could not determine Python DLL filename; assuming pythonXY'
826 )
826 )
827
827
828 hv = sys.hexversion
828 hv = sys.hexversion
829 pythonlib = b'python%d%d' % (hv >> 24, (hv >> 16) & 0xFF)
829 pythonlib = b'python%d%d' % (hv >> 24, (hv >> 16) & 0xFF)
830
830
831 log.info('using %s as Python library name' % pythonlib)
831 log.info('using %s as Python library name' % pythonlib)
832 with open('mercurial/hgpythonlib.h', 'wb') as f:
832 with open('mercurial/hgpythonlib.h', 'wb') as f:
833 f.write(b'/* this file is autogenerated by setup.py */\n')
833 f.write(b'/* this file is autogenerated by setup.py */\n')
834 f.write(b'#define HGPYTHONLIB "%s"\n' % pythonlib)
834 f.write(b'#define HGPYTHONLIB "%s"\n' % pythonlib)
835
835
836 objects = self.compiler.compile(
836 objects = self.compiler.compile(
837 ['mercurial/exewrapper.c'],
837 ['mercurial/exewrapper.c'],
838 output_dir=self.build_temp,
838 output_dir=self.build_temp,
839 macros=[('_UNICODE', None), ('UNICODE', None)],
839 macros=[('_UNICODE', None), ('UNICODE', None)],
840 )
840 )
841 self.compiler.link_executable(
841 self.compiler.link_executable(
842 objects, self.hgtarget, libraries=[], output_dir=self.build_temp
842 objects, self.hgtarget, libraries=[], output_dir=self.build_temp
843 )
843 )
844
844
845 self.addlongpathsmanifest()
845 self.addlongpathsmanifest()
846
846
847 def addlongpathsmanifest(self):
847 def addlongpathsmanifest(self):
848 """Add manifest pieces so that hg.exe understands long paths
848 """Add manifest pieces so that hg.exe understands long paths
849
849
850 Why resource #1 should be used for .exe manifests? I don't know and
850 Why resource #1 should be used for .exe manifests? I don't know and
851 wasn't able to find an explanation for mortals. But it seems to work.
851 wasn't able to find an explanation for mortals. But it seems to work.
852 """
852 """
853 exefname = self.compiler.executable_filename(self.hgtarget)
853 exefname = self.compiler.executable_filename(self.hgtarget)
854 fdauto, manfname = tempfile.mkstemp(suffix='.hg.exe.manifest')
854 fdauto, manfname = tempfile.mkstemp(suffix='.hg.exe.manifest')
855 os.close(fdauto)
855 os.close(fdauto)
856 with open(manfname, 'w', encoding="UTF-8") as f:
856 with open(manfname, 'w', encoding="UTF-8") as f:
857 f.write(self.LONG_PATHS_MANIFEST)
857 f.write(self.LONG_PATHS_MANIFEST)
858 log.info("long paths manifest is written to '%s'" % manfname)
858 log.info("long paths manifest is written to '%s'" % manfname)
859 outputresource = '-outputresource:%s;#1' % exefname
859 outputresource = '-outputresource:%s;#1' % exefname
860 log.info("running mt.exe to update hg.exe's manifest in-place")
860 log.info("running mt.exe to update hg.exe's manifest in-place")
861
861
862 self.spawn(
862 self.spawn(
863 [
863 [
864 self.compiler.mt,
864 self.compiler.mt,
865 '-nologo',
865 '-nologo',
866 '-manifest',
866 '-manifest',
867 manfname,
867 manfname,
868 outputresource,
868 outputresource,
869 ]
869 ]
870 )
870 )
871 log.info("done updating hg.exe's manifest")
871 log.info("done updating hg.exe's manifest")
872 os.remove(manfname)
872 os.remove(manfname)
873
873
874 @property
874 @property
875 def hgexepath(self):
875 def hgexepath(self):
876 dir = os.path.dirname(self.get_ext_fullpath('dummy'))
876 dir = os.path.dirname(self.get_ext_fullpath('dummy'))
877 return os.path.join(self.build_temp, dir, 'hg.exe')
877 return os.path.join(self.build_temp, dir, 'hg.exe')
878
878
879
879
880 class hgbuilddoc(Command):
880 class hgbuilddoc(Command):
881 description = 'build documentation'
881 description = 'build documentation'
882 user_options = [
882 user_options = [
883 ('man', None, 'generate man pages'),
883 ('man', None, 'generate man pages'),
884 ('html', None, 'generate html pages'),
884 ('html', None, 'generate html pages'),
885 ]
885 ]
886
886
887 def initialize_options(self):
887 def initialize_options(self):
888 self.man = None
888 self.man = None
889 self.html = None
889 self.html = None
890
890
891 def finalize_options(self):
891 def finalize_options(self):
892 # If --man or --html are set, only generate what we're told to.
892 # If --man or --html are set, only generate what we're told to.
893 # Otherwise generate everything.
893 # Otherwise generate everything.
894 have_subset = self.man is not None or self.html is not None
894 have_subset = self.man is not None or self.html is not None
895
895
896 if have_subset:
896 if have_subset:
897 self.man = True if self.man else False
897 self.man = True if self.man else False
898 self.html = True if self.html else False
898 self.html = True if self.html else False
899 else:
899 else:
900 self.man = True
900 self.man = True
901 self.html = True
901 self.html = True
902
902
903 def run(self):
903 def run(self):
904 def normalizecrlf(p):
904 def normalizecrlf(p):
905 with open(p, 'rb') as fh:
905 with open(p, 'rb') as fh:
906 orig = fh.read()
906 orig = fh.read()
907
907
908 if b'\r\n' not in orig:
908 if b'\r\n' not in orig:
909 return
909 return
910
910
911 log.info('normalizing %s to LF line endings' % p)
911 log.info('normalizing %s to LF line endings' % p)
912 with open(p, 'wb') as fh:
912 with open(p, 'wb') as fh:
913 fh.write(orig.replace(b'\r\n', b'\n'))
913 fh.write(orig.replace(b'\r\n', b'\n'))
914
914
915 def gentxt(root):
915 def gentxt(root):
916 txt = 'doc/%s.txt' % root
916 txt = 'doc/%s.txt' % root
917 log.info('generating %s' % txt)
917 log.info('generating %s' % txt)
918 res, out, err = runcmd(
918 res, out, err = runcmd(
919 [sys.executable, 'gendoc.py', root], os.environ, cwd='doc'
919 [sys.executable, 'gendoc.py', root], os.environ, cwd='doc'
920 )
920 )
921 if res:
921 if res:
922 raise SystemExit(
922 raise SystemExit(
923 'error running gendoc.py: %s'
923 'error running gendoc.py: %s'
924 % '\n'.join([sysstr(out), sysstr(err)])
924 % '\n'.join([sysstr(out), sysstr(err)])
925 )
925 )
926
926
927 with open(txt, 'wb') as fh:
927 with open(txt, 'wb') as fh:
928 fh.write(out)
928 fh.write(out)
929
929
930 def gengendoc(root):
930 def gengendoc(root):
931 gendoc = 'doc/%s.gendoc.txt' % root
931 gendoc = 'doc/%s.gendoc.txt' % root
932
932
933 log.info('generating %s' % gendoc)
933 log.info('generating %s' % gendoc)
934 res, out, err = runcmd(
934 res, out, err = runcmd(
935 [sys.executable, 'gendoc.py', '%s.gendoc' % root],
935 [sys.executable, 'gendoc.py', '%s.gendoc' % root],
936 os.environ,
936 os.environ,
937 cwd='doc',
937 cwd='doc',
938 )
938 )
939 if res:
939 if res:
940 raise SystemExit(
940 raise SystemExit(
941 'error running gendoc: %s'
941 'error running gendoc: %s'
942 % '\n'.join([sysstr(out), sysstr(err)])
942 % '\n'.join([sysstr(out), sysstr(err)])
943 )
943 )
944
944
945 with open(gendoc, 'wb') as fh:
945 with open(gendoc, 'wb') as fh:
946 fh.write(out)
946 fh.write(out)
947
947
948 def genman(root):
948 def genman(root):
949 log.info('generating doc/%s' % root)
949 log.info('generating doc/%s' % root)
950 res, out, err = runcmd(
950 res, out, err = runcmd(
951 [
951 [
952 sys.executable,
952 sys.executable,
953 'runrst',
953 'runrst',
954 'hgmanpage',
954 'hgmanpage',
955 '--halt',
955 '--halt',
956 'warning',
956 'warning',
957 '--strip-elements-with-class',
957 '--strip-elements-with-class',
958 'htmlonly',
958 'htmlonly',
959 '%s.txt' % root,
959 '%s.txt' % root,
960 root,
960 root,
961 ],
961 ],
962 os.environ,
962 os.environ,
963 cwd='doc',
963 cwd='doc',
964 )
964 )
965 if res:
965 if res:
966 raise SystemExit(
966 raise SystemExit(
967 'error running runrst: %s'
967 'error running runrst: %s'
968 % '\n'.join([sysstr(out), sysstr(err)])
968 % '\n'.join([sysstr(out), sysstr(err)])
969 )
969 )
970
970
971 normalizecrlf('doc/%s' % root)
971 normalizecrlf('doc/%s' % root)
972
972
973 def genhtml(root):
973 def genhtml(root):
974 log.info('generating doc/%s.html' % root)
974 log.info('generating doc/%s.html' % root)
975 res, out, err = runcmd(
975 res, out, err = runcmd(
976 [
976 [
977 sys.executable,
977 sys.executable,
978 'runrst',
978 'runrst',
979 'html',
979 'html',
980 '--halt',
980 '--halt',
981 'warning',
981 'warning',
982 '--link-stylesheet',
982 '--link-stylesheet',
983 '--stylesheet-path',
983 '--stylesheet-path',
984 'style.css',
984 'style.css',
985 '%s.txt' % root,
985 '%s.txt' % root,
986 '%s.html' % root,
986 '%s.html' % root,
987 ],
987 ],
988 os.environ,
988 os.environ,
989 cwd='doc',
989 cwd='doc',
990 )
990 )
991 if res:
991 if res:
992 raise SystemExit(
992 raise SystemExit(
993 'error running runrst: %s'
993 'error running runrst: %s'
994 % '\n'.join([sysstr(out), sysstr(err)])
994 % '\n'.join([sysstr(out), sysstr(err)])
995 )
995 )
996
996
997 normalizecrlf('doc/%s.html' % root)
997 normalizecrlf('doc/%s.html' % root)
998
998
999 # This logic is duplicated in doc/Makefile.
999 # This logic is duplicated in doc/Makefile.
1000 sources = {
1000 sources = {
1001 f
1001 f
1002 for f in os.listdir('mercurial/helptext')
1002 for f in os.listdir('mercurial/helptext')
1003 if re.search(r'[0-9]\.txt$', f)
1003 if re.search(r'[0-9]\.txt$', f)
1004 }
1004 }
1005
1005
1006 # common.txt is a one-off.
1006 # common.txt is a one-off.
1007 gentxt('common')
1007 gentxt('common')
1008
1008
1009 for source in sorted(sources):
1009 for source in sorted(sources):
1010 assert source[-4:] == '.txt'
1010 assert source[-4:] == '.txt'
1011 root = source[:-4]
1011 root = source[:-4]
1012
1012
1013 gentxt(root)
1013 gentxt(root)
1014 gengendoc(root)
1014 gengendoc(root)
1015
1015
1016 if self.man:
1016 if self.man:
1017 genman(root)
1017 genman(root)
1018 if self.html:
1018 if self.html:
1019 genhtml(root)
1019 genhtml(root)
1020
1020
1021
1021
1022 class hginstall(install):
1022 class hginstall(install):
1023
1023
1024 user_options = install.user_options + [
1024 user_options = install.user_options + [
1025 (
1025 (
1026 'old-and-unmanageable',
1026 'old-and-unmanageable',
1027 None,
1027 None,
1028 'noop, present for eggless setuptools compat',
1028 'noop, present for eggless setuptools compat',
1029 ),
1029 ),
1030 (
1030 (
1031 'single-version-externally-managed',
1031 'single-version-externally-managed',
1032 None,
1032 None,
1033 'noop, present for eggless setuptools compat',
1033 'noop, present for eggless setuptools compat',
1034 ),
1034 ),
1035 ]
1035 ]
1036
1036
1037 sub_commands = install.sub_commands + [
1037 sub_commands = install.sub_commands + [
1038 ('install_completion', lambda self: True)
1038 ('install_completion', lambda self: True)
1039 ]
1039 ]
1040
1040
1041 # Also helps setuptools not be sad while we refuse to create eggs.
1041 # Also helps setuptools not be sad while we refuse to create eggs.
1042 single_version_externally_managed = True
1042 single_version_externally_managed = True
1043
1043
1044 def get_sub_commands(self):
1044 def get_sub_commands(self):
1045 # Screen out egg related commands to prevent egg generation. But allow
1045 # Screen out egg related commands to prevent egg generation. But allow
1046 # mercurial.egg-info generation, since that is part of modern
1046 # mercurial.egg-info generation, since that is part of modern
1047 # packaging.
1047 # packaging.
1048 excl = {'bdist_egg'}
1048 excl = {'bdist_egg'}
1049 return filter(lambda x: x not in excl, install.get_sub_commands(self))
1049 return filter(lambda x: x not in excl, install.get_sub_commands(self))
1050
1050
1051
1051
1052 class hginstalllib(install_lib):
1052 class hginstalllib(install_lib):
1053 """
1053 """
1054 This is a specialization of install_lib that replaces the copy_file used
1054 This is a specialization of install_lib that replaces the copy_file used
1055 there so that it supports setting the mode of files after copying them,
1055 there so that it supports setting the mode of files after copying them,
1056 instead of just preserving the mode that the files originally had. If your
1056 instead of just preserving the mode that the files originally had. If your
1057 system has a umask of something like 027, preserving the permissions when
1057 system has a umask of something like 027, preserving the permissions when
1058 copying will lead to a broken install.
1058 copying will lead to a broken install.
1059
1059
1060 Note that just passing keep_permissions=False to copy_file would be
1060 Note that just passing keep_permissions=False to copy_file would be
1061 insufficient, as it might still be applying a umask.
1061 insufficient, as it might still be applying a umask.
1062 """
1062 """
1063
1063
1064 def run(self):
1064 def run(self):
1065 realcopyfile = file_util.copy_file
1065 realcopyfile = file_util.copy_file
1066
1066
1067 def copyfileandsetmode(*args, **kwargs):
1067 def copyfileandsetmode(*args, **kwargs):
1068 src, dst = args[0], args[1]
1068 src, dst = args[0], args[1]
1069 dst, copied = realcopyfile(*args, **kwargs)
1069 dst, copied = realcopyfile(*args, **kwargs)
1070 if copied:
1070 if copied:
1071 st = os.stat(src)
1071 st = os.stat(src)
1072 # Persist executable bit (apply it to group and other if user
1072 # Persist executable bit (apply it to group and other if user
1073 # has it)
1073 # has it)
1074 if st[stat.ST_MODE] & stat.S_IXUSR:
1074 if st[stat.ST_MODE] & stat.S_IXUSR:
1075 setmode = int('0755', 8)
1075 setmode = int('0755', 8)
1076 else:
1076 else:
1077 setmode = int('0644', 8)
1077 setmode = int('0644', 8)
1078 m = stat.S_IMODE(st[stat.ST_MODE])
1078 m = stat.S_IMODE(st[stat.ST_MODE])
1079 m = (m & ~int('0777', 8)) | setmode
1079 m = (m & ~int('0777', 8)) | setmode
1080 os.chmod(dst, m)
1080 os.chmod(dst, m)
1081
1081
1082 file_util.copy_file = copyfileandsetmode
1082 file_util.copy_file = copyfileandsetmode
1083 try:
1083 try:
1084 install_lib.run(self)
1084 install_lib.run(self)
1085 finally:
1085 finally:
1086 file_util.copy_file = realcopyfile
1086 file_util.copy_file = realcopyfile
1087
1087
1088
1088
1089 class hginstallscripts(install_scripts):
1089 class hginstallscripts(install_scripts):
1090 """
1090 """
1091 This is a specialization of install_scripts that replaces the @LIBDIR@ with
1091 This is a specialization of install_scripts that replaces the @LIBDIR@ with
1092 the configured directory for modules. If possible, the path is made relative
1092 the configured directory for modules. If possible, the path is made relative
1093 to the directory for scripts.
1093 to the directory for scripts.
1094 """
1094 """
1095
1095
1096 def initialize_options(self):
1096 def initialize_options(self):
1097 install_scripts.initialize_options(self)
1097 install_scripts.initialize_options(self)
1098
1098
1099 self.install_lib = None
1099 self.install_lib = None
1100
1100
1101 def finalize_options(self):
1101 def finalize_options(self):
1102 install_scripts.finalize_options(self)
1102 install_scripts.finalize_options(self)
1103 self.set_undefined_options('install', ('install_lib', 'install_lib'))
1103 self.set_undefined_options('install', ('install_lib', 'install_lib'))
1104
1104
1105 def run(self):
1105 def run(self):
1106 install_scripts.run(self)
1106 install_scripts.run(self)
1107
1107
1108 # It only makes sense to replace @LIBDIR@ with the install path if
1108 # It only makes sense to replace @LIBDIR@ with the install path if
1109 # the install path is known. For wheels, the logic below calculates
1109 # the install path is known. For wheels, the logic below calculates
1110 # the libdir to be "../..". This is because the internal layout of a
1110 # the libdir to be "../..". This is because the internal layout of a
1111 # wheel archive looks like:
1111 # wheel archive looks like:
1112 #
1112 #
1113 # mercurial-3.6.1.data/scripts/hg
1113 # mercurial-3.6.1.data/scripts/hg
1114 # mercurial/__init__.py
1114 # mercurial/__init__.py
1115 #
1115 #
1116 # When installing wheels, the subdirectories of the "<pkg>.data"
1116 # When installing wheels, the subdirectories of the "<pkg>.data"
1117 # directory are translated to system local paths and files therein
1117 # directory are translated to system local paths and files therein
1118 # are copied in place. The mercurial/* files are installed into the
1118 # are copied in place. The mercurial/* files are installed into the
1119 # site-packages directory. However, the site-packages directory
1119 # site-packages directory. However, the site-packages directory
1120 # isn't known until wheel install time. This means we have no clue
1120 # isn't known until wheel install time. This means we have no clue
1121 # at wheel generation time what the installed site-packages directory
1121 # at wheel generation time what the installed site-packages directory
1122 # will be. And, wheels don't appear to provide the ability to register
1122 # will be. And, wheels don't appear to provide the ability to register
1123 # custom code to run during wheel installation. This all means that
1123 # custom code to run during wheel installation. This all means that
1124 # we can't reliably set the libdir in wheels: the default behavior
1124 # we can't reliably set the libdir in wheels: the default behavior
1125 # of looking in sys.path must do.
1125 # of looking in sys.path must do.
1126
1126
1127 if (
1127 if (
1128 os.path.splitdrive(self.install_dir)[0]
1128 os.path.splitdrive(self.install_dir)[0]
1129 != os.path.splitdrive(self.install_lib)[0]
1129 != os.path.splitdrive(self.install_lib)[0]
1130 ):
1130 ):
1131 # can't make relative paths from one drive to another, so use an
1131 # can't make relative paths from one drive to another, so use an
1132 # absolute path instead
1132 # absolute path instead
1133 libdir = self.install_lib
1133 libdir = self.install_lib
1134 else:
1134 else:
1135 libdir = os.path.relpath(self.install_lib, self.install_dir)
1135 libdir = os.path.relpath(self.install_lib, self.install_dir)
1136
1136
1137 for outfile in self.outfiles:
1137 for outfile in self.outfiles:
1138 with open(outfile, 'rb') as fp:
1138 with open(outfile, 'rb') as fp:
1139 data = fp.read()
1139 data = fp.read()
1140
1140
1141 # skip binary files
1141 # skip binary files
1142 if b'\0' in data:
1142 if b'\0' in data:
1143 continue
1143 continue
1144
1144
1145 # During local installs, the shebang will be rewritten to the final
1145 # During local installs, the shebang will be rewritten to the final
1146 # install path. During wheel packaging, the shebang has a special
1146 # install path. During wheel packaging, the shebang has a special
1147 # value.
1147 # value.
1148 if data.startswith(b'#!python'):
1148 if data.startswith(b'#!python'):
1149 log.info(
1149 log.info(
1150 'not rewriting @LIBDIR@ in %s because install path '
1150 'not rewriting @LIBDIR@ in %s because install path '
1151 'not known' % outfile
1151 'not known' % outfile
1152 )
1152 )
1153 continue
1153 continue
1154
1154
1155 data = data.replace(b'@LIBDIR@', libdir.encode('unicode_escape'))
1155 data = data.replace(b'@LIBDIR@', libdir.encode('unicode_escape'))
1156 with open(outfile, 'wb') as fp:
1156 with open(outfile, 'wb') as fp:
1157 fp.write(data)
1157 fp.write(data)
1158
1158
1159
1159
1160 class hginstallcompletion(Command):
1160 class hginstallcompletion(Command):
1161 description = 'Install shell completion'
1161 description = 'Install shell completion'
1162
1162
1163 def initialize_options(self):
1163 def initialize_options(self):
1164 self.install_dir = None
1164 self.install_dir = None
1165 self.outputs = []
1165 self.outputs = []
1166
1166
1167 def finalize_options(self):
1167 def finalize_options(self):
1168 self.set_undefined_options(
1168 self.set_undefined_options(
1169 'install_data', ('install_dir', 'install_dir')
1169 'install_data', ('install_dir', 'install_dir')
1170 )
1170 )
1171
1171
1172 def get_outputs(self):
1172 def get_outputs(self):
1173 return self.outputs
1173 return self.outputs
1174
1174
1175 def run(self):
1175 def run(self):
1176 for src, dir_path, dest in (
1176 for src, dir_path, dest in (
1177 (
1177 (
1178 'bash_completion',
1178 'bash_completion',
1179 ('share', 'bash-completion', 'completions'),
1179 ('share', 'bash-completion', 'completions'),
1180 'hg',
1180 'hg',
1181 ),
1181 ),
1182 ('zsh_completion', ('share', 'zsh', 'site-functions'), '_hg'),
1182 ('zsh_completion', ('share', 'zsh', 'site-functions'), '_hg'),
1183 ):
1183 ):
1184 dir = os.path.join(self.install_dir, *dir_path)
1184 dir = os.path.join(self.install_dir, *dir_path)
1185 self.mkpath(dir)
1185 self.mkpath(dir)
1186
1186
1187 dest = os.path.join(dir, dest)
1187 dest = os.path.join(dir, dest)
1188 self.outputs.append(dest)
1188 self.outputs.append(dest)
1189 self.copy_file(os.path.join('contrib', src), dest)
1189 self.copy_file(os.path.join('contrib', src), dest)
1190
1190
1191
1191
1192 # virtualenv installs custom distutils/__init__.py and
1192 # virtualenv installs custom distutils/__init__.py and
1193 # distutils/distutils.cfg files which essentially proxy back to the
1193 # distutils/distutils.cfg files which essentially proxy back to the
1194 # "real" distutils in the main Python install. The presence of this
1194 # "real" distutils in the main Python install. The presence of this
1195 # directory causes py2exe to pick up the "hacked" distutils package
1195 # directory causes py2exe to pick up the "hacked" distutils package
1196 # from the virtualenv and "import distutils" will fail from the py2exe
1196 # from the virtualenv and "import distutils" will fail from the py2exe
1197 # build because the "real" distutils files can't be located.
1197 # build because the "real" distutils files can't be located.
1198 #
1198 #
1199 # We work around this by monkeypatching the py2exe code finding Python
1199 # We work around this by monkeypatching the py2exe code finding Python
1200 # modules to replace the found virtualenv distutils modules with the
1200 # modules to replace the found virtualenv distutils modules with the
1201 # original versions via filesystem scanning. This is a bit hacky. But
1201 # original versions via filesystem scanning. This is a bit hacky. But
1202 # it allows us to use virtualenvs for py2exe packaging, which is more
1202 # it allows us to use virtualenvs for py2exe packaging, which is more
1203 # deterministic and reproducible.
1203 # deterministic and reproducible.
1204 #
1204 #
1205 # It's worth noting that the common StackOverflow suggestions for this
1205 # It's worth noting that the common StackOverflow suggestions for this
1206 # problem involve copying the original distutils files into the
1206 # problem involve copying the original distutils files into the
1207 # virtualenv or into the staging directory after setup() is invoked.
1207 # virtualenv or into the staging directory after setup() is invoked.
1208 # The former is very brittle and can easily break setup(). Our hacking
1208 # The former is very brittle and can easily break setup(). Our hacking
1209 # of the found modules routine has a similar result as copying the files
1209 # of the found modules routine has a similar result as copying the files
1210 # manually. But it makes fewer assumptions about how py2exe works and
1210 # manually. But it makes fewer assumptions about how py2exe works and
1211 # is less brittle.
1211 # is less brittle.
1212
1212
1213 # This only catches virtualenvs made with virtualenv (as opposed to
1213 # This only catches virtualenvs made with virtualenv (as opposed to
1214 # venv, which is likely what Python 3 uses).
1214 # venv, which is likely what Python 3 uses).
1215 py2exehacked = py2exeloaded and getattr(sys, 'real_prefix', None) is not None
1215 py2exehacked = py2exeloaded and getattr(sys, 'real_prefix', None) is not None
1216
1216
1217 if py2exehacked:
1217 if py2exehacked:
1218 from distutils.command.py2exe import py2exe as buildpy2exe
1218 from distutils.command.py2exe import py2exe as buildpy2exe
1219 from py2exe.mf import Module as py2exemodule
1219 from py2exe.mf import Module as py2exemodule
1220
1220
1221 class hgbuildpy2exe(buildpy2exe):
1221 class hgbuildpy2exe(buildpy2exe):
1222 def find_needed_modules(self, mf, files, modules):
1222 def find_needed_modules(self, mf, files, modules):
1223 res = buildpy2exe.find_needed_modules(self, mf, files, modules)
1223 res = buildpy2exe.find_needed_modules(self, mf, files, modules)
1224
1224
1225 # Replace virtualenv's distutils modules with the real ones.
1225 # Replace virtualenv's distutils modules with the real ones.
1226 modules = {}
1226 modules = {}
1227 for k, v in res.modules.items():
1227 for k, v in res.modules.items():
1228 if k != 'distutils' and not k.startswith('distutils.'):
1228 if k != 'distutils' and not k.startswith('distutils.'):
1229 modules[k] = v
1229 modules[k] = v
1230
1230
1231 res.modules = modules
1231 res.modules = modules
1232
1232
1233 import opcode
1233 import opcode
1234
1234
1235 distutilsreal = os.path.join(
1235 distutilsreal = os.path.join(
1236 os.path.dirname(opcode.__file__), 'distutils'
1236 os.path.dirname(opcode.__file__), 'distutils'
1237 )
1237 )
1238
1238
1239 for root, dirs, files in os.walk(distutilsreal):
1239 for root, dirs, files in os.walk(distutilsreal):
1240 for f in sorted(files):
1240 for f in sorted(files):
1241 if not f.endswith('.py'):
1241 if not f.endswith('.py'):
1242 continue
1242 continue
1243
1243
1244 full = os.path.join(root, f)
1244 full = os.path.join(root, f)
1245
1245
1246 parents = ['distutils']
1246 parents = ['distutils']
1247
1247
1248 if root != distutilsreal:
1248 if root != distutilsreal:
1249 rel = os.path.relpath(root, distutilsreal)
1249 rel = os.path.relpath(root, distutilsreal)
1250 parents.extend(p for p in rel.split(os.sep))
1250 parents.extend(p for p in rel.split(os.sep))
1251
1251
1252 modname = '%s.%s' % ('.'.join(parents), f[:-3])
1252 modname = '%s.%s' % ('.'.join(parents), f[:-3])
1253
1253
1254 if modname.startswith('distutils.tests.'):
1254 if modname.startswith('distutils.tests.'):
1255 continue
1255 continue
1256
1256
1257 if modname.endswith('.__init__'):
1257 if modname.endswith('.__init__'):
1258 modname = modname[: -len('.__init__')]
1258 modname = modname[: -len('.__init__')]
1259 path = os.path.dirname(full)
1259 path = os.path.dirname(full)
1260 else:
1260 else:
1261 path = None
1261 path = None
1262
1262
1263 res.modules[modname] = py2exemodule(
1263 res.modules[modname] = py2exemodule(
1264 modname, full, path=path
1264 modname, full, path=path
1265 )
1265 )
1266
1266
1267 if 'distutils' not in res.modules:
1267 if 'distutils' not in res.modules:
1268 raise SystemExit('could not find distutils modules')
1268 raise SystemExit('could not find distutils modules')
1269
1269
1270 return res
1270 return res
1271
1271
1272
1272
1273 cmdclass = {
1273 cmdclass = {
1274 'build': hgbuild,
1274 'build': hgbuild,
1275 'build_doc': hgbuilddoc,
1275 'build_doc': hgbuilddoc,
1276 'build_mo': hgbuildmo,
1276 'build_mo': hgbuildmo,
1277 'build_ext': hgbuildext,
1277 'build_ext': hgbuildext,
1278 'build_py': hgbuildpy,
1278 'build_py': hgbuildpy,
1279 'build_scripts': hgbuildscripts,
1279 'build_scripts': hgbuildscripts,
1280 'build_hgextindex': buildhgextindex,
1280 'build_hgextindex': buildhgextindex,
1281 'install': hginstall,
1281 'install': hginstall,
1282 'install_completion': hginstallcompletion,
1282 'install_completion': hginstallcompletion,
1283 'install_lib': hginstalllib,
1283 'install_lib': hginstalllib,
1284 'install_scripts': hginstallscripts,
1284 'install_scripts': hginstallscripts,
1285 'build_hgexe': buildhgexe,
1285 'build_hgexe': buildhgexe,
1286 }
1286 }
1287
1287
1288 if py2exehacked:
1288 if py2exehacked:
1289 cmdclass['py2exe'] = hgbuildpy2exe
1289 cmdclass['py2exe'] = hgbuildpy2exe
1290
1290
1291 packages = [
1291 packages = [
1292 'mercurial',
1292 'mercurial',
1293 'mercurial.cext',
1293 'mercurial.cext',
1294 'mercurial.cffi',
1294 'mercurial.cffi',
1295 'mercurial.defaultrc',
1295 'mercurial.defaultrc',
1296 'mercurial.dirstateutils',
1296 'mercurial.dirstateutils',
1297 'mercurial.helptext',
1297 'mercurial.helptext',
1298 'mercurial.helptext.internals',
1298 'mercurial.helptext.internals',
1299 'mercurial.hgweb',
1299 'mercurial.hgweb',
1300 'mercurial.interfaces',
1300 'mercurial.interfaces',
1301 'mercurial.pure',
1301 'mercurial.pure',
1302 'mercurial.stabletailgraph',
1302 'mercurial.templates',
1303 'mercurial.templates',
1303 'mercurial.thirdparty',
1304 'mercurial.thirdparty',
1304 'mercurial.thirdparty.attr',
1305 'mercurial.thirdparty.attr',
1305 'mercurial.thirdparty.jaraco',
1306 'mercurial.thirdparty.jaraco',
1306 'mercurial.thirdparty.zope',
1307 'mercurial.thirdparty.zope',
1307 'mercurial.thirdparty.zope.interface',
1308 'mercurial.thirdparty.zope.interface',
1308 'mercurial.upgrade_utils',
1309 'mercurial.upgrade_utils',
1309 'mercurial.utils',
1310 'mercurial.utils',
1310 'mercurial.revlogutils',
1311 'mercurial.revlogutils',
1311 'mercurial.testing',
1312 'mercurial.testing',
1312 'hgext',
1313 'hgext',
1313 'hgext.convert',
1314 'hgext.convert',
1314 'hgext.fsmonitor',
1315 'hgext.fsmonitor',
1315 'hgext.fastannotate',
1316 'hgext.fastannotate',
1316 'hgext.fsmonitor.pywatchman',
1317 'hgext.fsmonitor.pywatchman',
1317 'hgext.git',
1318 'hgext.git',
1318 'hgext.highlight',
1319 'hgext.highlight',
1319 'hgext.hooklib',
1320 'hgext.hooklib',
1320 'hgext.infinitepush',
1321 'hgext.infinitepush',
1321 'hgext.largefiles',
1322 'hgext.largefiles',
1322 'hgext.lfs',
1323 'hgext.lfs',
1323 'hgext.narrow',
1324 'hgext.narrow',
1324 'hgext.remotefilelog',
1325 'hgext.remotefilelog',
1325 'hgext.zeroconf',
1326 'hgext.zeroconf',
1326 'hgext3rd',
1327 'hgext3rd',
1327 'hgdemandimport',
1328 'hgdemandimport',
1328 ]
1329 ]
1329
1330
1330 for name in os.listdir(os.path.join('mercurial', 'templates')):
1331 for name in os.listdir(os.path.join('mercurial', 'templates')):
1331 if name != '__pycache__' and os.path.isdir(
1332 if name != '__pycache__' and os.path.isdir(
1332 os.path.join('mercurial', 'templates', name)
1333 os.path.join('mercurial', 'templates', name)
1333 ):
1334 ):
1334 packages.append('mercurial.templates.%s' % name)
1335 packages.append('mercurial.templates.%s' % name)
1335
1336
1336 if 'HG_PY2EXE_EXTRA_INSTALL_PACKAGES' in os.environ:
1337 if 'HG_PY2EXE_EXTRA_INSTALL_PACKAGES' in os.environ:
1337 # py2exe can't cope with namespace packages very well, so we have to
1338 # py2exe can't cope with namespace packages very well, so we have to
1338 # install any hgext3rd.* extensions that we want in the final py2exe
1339 # install any hgext3rd.* extensions that we want in the final py2exe
1339 # image here. This is gross, but you gotta do what you gotta do.
1340 # image here. This is gross, but you gotta do what you gotta do.
1340 packages.extend(os.environ['HG_PY2EXE_EXTRA_INSTALL_PACKAGES'].split(' '))
1341 packages.extend(os.environ['HG_PY2EXE_EXTRA_INSTALL_PACKAGES'].split(' '))
1341
1342
1342 common_depends = [
1343 common_depends = [
1343 'mercurial/bitmanipulation.h',
1344 'mercurial/bitmanipulation.h',
1344 'mercurial/compat.h',
1345 'mercurial/compat.h',
1345 'mercurial/cext/util.h',
1346 'mercurial/cext/util.h',
1346 ]
1347 ]
1347 common_include_dirs = ['mercurial']
1348 common_include_dirs = ['mercurial']
1348
1349
1349 common_cflags = []
1350 common_cflags = []
1350
1351
1351 # MSVC 2008 still needs declarations at the top of the scope, but Python 3.9
1352 # MSVC 2008 still needs declarations at the top of the scope, but Python 3.9
1352 # makes declarations not at the top of a scope in the headers.
1353 # makes declarations not at the top of a scope in the headers.
1353 if os.name != 'nt' and sys.version_info[1] < 9:
1354 if os.name != 'nt' and sys.version_info[1] < 9:
1354 common_cflags = ['-Werror=declaration-after-statement']
1355 common_cflags = ['-Werror=declaration-after-statement']
1355
1356
1356 osutil_cflags = []
1357 osutil_cflags = []
1357 osutil_ldflags = []
1358 osutil_ldflags = []
1358
1359
1359 # platform specific macros
1360 # platform specific macros
1360 for plat, func in [('bsd', 'setproctitle')]:
1361 for plat, func in [('bsd', 'setproctitle')]:
1361 if re.search(plat, sys.platform) and hasfunction(new_compiler(), func):
1362 if re.search(plat, sys.platform) and hasfunction(new_compiler(), func):
1362 osutil_cflags.append('-DHAVE_%s' % func.upper())
1363 osutil_cflags.append('-DHAVE_%s' % func.upper())
1363
1364
1364 for plat, macro, code in [
1365 for plat, macro, code in [
1365 (
1366 (
1366 'bsd|darwin',
1367 'bsd|darwin',
1367 'BSD_STATFS',
1368 'BSD_STATFS',
1368 '''
1369 '''
1369 #include <sys/param.h>
1370 #include <sys/param.h>
1370 #include <sys/mount.h>
1371 #include <sys/mount.h>
1371 int main() { struct statfs s; return sizeof(s.f_fstypename); }
1372 int main() { struct statfs s; return sizeof(s.f_fstypename); }
1372 ''',
1373 ''',
1373 ),
1374 ),
1374 (
1375 (
1375 'linux',
1376 'linux',
1376 'LINUX_STATFS',
1377 'LINUX_STATFS',
1377 '''
1378 '''
1378 #include <linux/magic.h>
1379 #include <linux/magic.h>
1379 #include <sys/vfs.h>
1380 #include <sys/vfs.h>
1380 int main() { struct statfs s; return sizeof(s.f_type); }
1381 int main() { struct statfs s; return sizeof(s.f_type); }
1381 ''',
1382 ''',
1382 ),
1383 ),
1383 ]:
1384 ]:
1384 if re.search(plat, sys.platform) and cancompile(new_compiler(), code):
1385 if re.search(plat, sys.platform) and cancompile(new_compiler(), code):
1385 osutil_cflags.append('-DHAVE_%s' % macro)
1386 osutil_cflags.append('-DHAVE_%s' % macro)
1386
1387
1387 if sys.platform == 'darwin':
1388 if sys.platform == 'darwin':
1388 osutil_ldflags += ['-framework', 'ApplicationServices']
1389 osutil_ldflags += ['-framework', 'ApplicationServices']
1389
1390
1390 if sys.platform == 'sunos5':
1391 if sys.platform == 'sunos5':
1391 osutil_ldflags += ['-lsocket']
1392 osutil_ldflags += ['-lsocket']
1392
1393
1393 xdiff_srcs = [
1394 xdiff_srcs = [
1394 'mercurial/thirdparty/xdiff/xdiffi.c',
1395 'mercurial/thirdparty/xdiff/xdiffi.c',
1395 'mercurial/thirdparty/xdiff/xprepare.c',
1396 'mercurial/thirdparty/xdiff/xprepare.c',
1396 'mercurial/thirdparty/xdiff/xutils.c',
1397 'mercurial/thirdparty/xdiff/xutils.c',
1397 ]
1398 ]
1398
1399
1399 xdiff_headers = [
1400 xdiff_headers = [
1400 'mercurial/thirdparty/xdiff/xdiff.h',
1401 'mercurial/thirdparty/xdiff/xdiff.h',
1401 'mercurial/thirdparty/xdiff/xdiffi.h',
1402 'mercurial/thirdparty/xdiff/xdiffi.h',
1402 'mercurial/thirdparty/xdiff/xinclude.h',
1403 'mercurial/thirdparty/xdiff/xinclude.h',
1403 'mercurial/thirdparty/xdiff/xmacros.h',
1404 'mercurial/thirdparty/xdiff/xmacros.h',
1404 'mercurial/thirdparty/xdiff/xprepare.h',
1405 'mercurial/thirdparty/xdiff/xprepare.h',
1405 'mercurial/thirdparty/xdiff/xtypes.h',
1406 'mercurial/thirdparty/xdiff/xtypes.h',
1406 'mercurial/thirdparty/xdiff/xutils.h',
1407 'mercurial/thirdparty/xdiff/xutils.h',
1407 ]
1408 ]
1408
1409
1409
1410
1410 class RustCompilationError(CCompilerError):
1411 class RustCompilationError(CCompilerError):
1411 """Exception class for Rust compilation errors."""
1412 """Exception class for Rust compilation errors."""
1412
1413
1413
1414
1414 class RustExtension(Extension):
1415 class RustExtension(Extension):
1415 """Base classes for concrete Rust Extension classes."""
1416 """Base classes for concrete Rust Extension classes."""
1416
1417
1417 rusttargetdir = os.path.join('rust', 'target', 'release')
1418 rusttargetdir = os.path.join('rust', 'target', 'release')
1418
1419
1419 def __init__(self, mpath, sources, rustlibname, subcrate, **kw):
1420 def __init__(self, mpath, sources, rustlibname, subcrate, **kw):
1420 Extension.__init__(self, mpath, sources, **kw)
1421 Extension.__init__(self, mpath, sources, **kw)
1421 srcdir = self.rustsrcdir = os.path.join('rust', subcrate)
1422 srcdir = self.rustsrcdir = os.path.join('rust', subcrate)
1422
1423
1423 # adding Rust source and control files to depends so that the extension
1424 # adding Rust source and control files to depends so that the extension
1424 # gets rebuilt if they've changed
1425 # gets rebuilt if they've changed
1425 self.depends.append(os.path.join(srcdir, 'Cargo.toml'))
1426 self.depends.append(os.path.join(srcdir, 'Cargo.toml'))
1426 cargo_lock = os.path.join(srcdir, 'Cargo.lock')
1427 cargo_lock = os.path.join(srcdir, 'Cargo.lock')
1427 if os.path.exists(cargo_lock):
1428 if os.path.exists(cargo_lock):
1428 self.depends.append(cargo_lock)
1429 self.depends.append(cargo_lock)
1429 for dirpath, subdir, fnames in os.walk(os.path.join(srcdir, 'src')):
1430 for dirpath, subdir, fnames in os.walk(os.path.join(srcdir, 'src')):
1430 self.depends.extend(
1431 self.depends.extend(
1431 os.path.join(dirpath, fname)
1432 os.path.join(dirpath, fname)
1432 for fname in fnames
1433 for fname in fnames
1433 if os.path.splitext(fname)[1] == '.rs'
1434 if os.path.splitext(fname)[1] == '.rs'
1434 )
1435 )
1435
1436
1436 @staticmethod
1437 @staticmethod
1437 def rustdylibsuffix():
1438 def rustdylibsuffix():
1438 """Return the suffix for shared libraries produced by rustc.
1439 """Return the suffix for shared libraries produced by rustc.
1439
1440
1440 See also: https://doc.rust-lang.org/reference/linkage.html
1441 See also: https://doc.rust-lang.org/reference/linkage.html
1441 """
1442 """
1442 if sys.platform == 'darwin':
1443 if sys.platform == 'darwin':
1443 return '.dylib'
1444 return '.dylib'
1444 elif os.name == 'nt':
1445 elif os.name == 'nt':
1445 return '.dll'
1446 return '.dll'
1446 else:
1447 else:
1447 return '.so'
1448 return '.so'
1448
1449
1449 def rustbuild(self):
1450 def rustbuild(self):
1450 env = os.environ.copy()
1451 env = os.environ.copy()
1451 if 'HGTEST_RESTOREENV' in env:
1452 if 'HGTEST_RESTOREENV' in env:
1452 # Mercurial tests change HOME to a temporary directory,
1453 # Mercurial tests change HOME to a temporary directory,
1453 # but, if installed with rustup, the Rust toolchain needs
1454 # but, if installed with rustup, the Rust toolchain needs
1454 # HOME to be correct (otherwise the 'no default toolchain'
1455 # HOME to be correct (otherwise the 'no default toolchain'
1455 # error message is issued and the build fails).
1456 # error message is issued and the build fails).
1456 # This happens currently with test-hghave.t, which does
1457 # This happens currently with test-hghave.t, which does
1457 # invoke this build.
1458 # invoke this build.
1458
1459
1459 # Unix only fix (os.path.expanduser not really reliable if
1460 # Unix only fix (os.path.expanduser not really reliable if
1460 # HOME is shadowed like this)
1461 # HOME is shadowed like this)
1461 import pwd
1462 import pwd
1462
1463
1463 env['HOME'] = pwd.getpwuid(os.getuid()).pw_dir
1464 env['HOME'] = pwd.getpwuid(os.getuid()).pw_dir
1464
1465
1465 cargocmd = ['cargo', 'rustc', '--release']
1466 cargocmd = ['cargo', 'rustc', '--release']
1466
1467
1467 rust_features = env.get("HG_RUST_FEATURES")
1468 rust_features = env.get("HG_RUST_FEATURES")
1468 if rust_features:
1469 if rust_features:
1469 cargocmd.extend(('--features', rust_features))
1470 cargocmd.extend(('--features', rust_features))
1470
1471
1471 cargocmd.append('--')
1472 cargocmd.append('--')
1472 if sys.platform == 'darwin':
1473 if sys.platform == 'darwin':
1473 cargocmd.extend(
1474 cargocmd.extend(
1474 ("-C", "link-arg=-undefined", "-C", "link-arg=dynamic_lookup")
1475 ("-C", "link-arg=-undefined", "-C", "link-arg=dynamic_lookup")
1475 )
1476 )
1476 try:
1477 try:
1477 subprocess.check_call(cargocmd, env=env, cwd=self.rustsrcdir)
1478 subprocess.check_call(cargocmd, env=env, cwd=self.rustsrcdir)
1478 except FileNotFoundError:
1479 except FileNotFoundError:
1479 raise RustCompilationError("Cargo not found")
1480 raise RustCompilationError("Cargo not found")
1480 except PermissionError:
1481 except PermissionError:
1481 raise RustCompilationError(
1482 raise RustCompilationError(
1482 "Cargo found, but permission to execute it is denied"
1483 "Cargo found, but permission to execute it is denied"
1483 )
1484 )
1484 except subprocess.CalledProcessError:
1485 except subprocess.CalledProcessError:
1485 raise RustCompilationError(
1486 raise RustCompilationError(
1486 "Cargo failed. Working directory: %r, "
1487 "Cargo failed. Working directory: %r, "
1487 "command: %r, environment: %r"
1488 "command: %r, environment: %r"
1488 % (self.rustsrcdir, cargocmd, env)
1489 % (self.rustsrcdir, cargocmd, env)
1489 )
1490 )
1490
1491
1491
1492
1492 class RustStandaloneExtension(RustExtension):
1493 class RustStandaloneExtension(RustExtension):
1493 def __init__(self, pydottedname, rustcrate, dylibname, **kw):
1494 def __init__(self, pydottedname, rustcrate, dylibname, **kw):
1494 RustExtension.__init__(
1495 RustExtension.__init__(
1495 self, pydottedname, [], dylibname, rustcrate, **kw
1496 self, pydottedname, [], dylibname, rustcrate, **kw
1496 )
1497 )
1497 self.dylibname = dylibname
1498 self.dylibname = dylibname
1498
1499
1499 def build(self, target_dir):
1500 def build(self, target_dir):
1500 self.rustbuild()
1501 self.rustbuild()
1501 target = [target_dir]
1502 target = [target_dir]
1502 target.extend(self.name.split('.'))
1503 target.extend(self.name.split('.'))
1503 target[-1] += DYLIB_SUFFIX
1504 target[-1] += DYLIB_SUFFIX
1504 target = os.path.join(*target)
1505 target = os.path.join(*target)
1505 os.makedirs(os.path.dirname(target), exist_ok=True)
1506 os.makedirs(os.path.dirname(target), exist_ok=True)
1506 shutil.copy2(
1507 shutil.copy2(
1507 os.path.join(
1508 os.path.join(
1508 self.rusttargetdir, self.dylibname + self.rustdylibsuffix()
1509 self.rusttargetdir, self.dylibname + self.rustdylibsuffix()
1509 ),
1510 ),
1510 target,
1511 target,
1511 )
1512 )
1512
1513
1513
1514
1514 extmodules = [
1515 extmodules = [
1515 Extension(
1516 Extension(
1516 'mercurial.cext.base85',
1517 'mercurial.cext.base85',
1517 ['mercurial/cext/base85.c'],
1518 ['mercurial/cext/base85.c'],
1518 include_dirs=common_include_dirs,
1519 include_dirs=common_include_dirs,
1519 extra_compile_args=common_cflags,
1520 extra_compile_args=common_cflags,
1520 depends=common_depends,
1521 depends=common_depends,
1521 ),
1522 ),
1522 Extension(
1523 Extension(
1523 'mercurial.cext.bdiff',
1524 'mercurial.cext.bdiff',
1524 ['mercurial/bdiff.c', 'mercurial/cext/bdiff.c'] + xdiff_srcs,
1525 ['mercurial/bdiff.c', 'mercurial/cext/bdiff.c'] + xdiff_srcs,
1525 include_dirs=common_include_dirs,
1526 include_dirs=common_include_dirs,
1526 extra_compile_args=common_cflags,
1527 extra_compile_args=common_cflags,
1527 depends=common_depends + ['mercurial/bdiff.h'] + xdiff_headers,
1528 depends=common_depends + ['mercurial/bdiff.h'] + xdiff_headers,
1528 ),
1529 ),
1529 Extension(
1530 Extension(
1530 'mercurial.cext.mpatch',
1531 'mercurial.cext.mpatch',
1531 ['mercurial/mpatch.c', 'mercurial/cext/mpatch.c'],
1532 ['mercurial/mpatch.c', 'mercurial/cext/mpatch.c'],
1532 include_dirs=common_include_dirs,
1533 include_dirs=common_include_dirs,
1533 extra_compile_args=common_cflags,
1534 extra_compile_args=common_cflags,
1534 depends=common_depends,
1535 depends=common_depends,
1535 ),
1536 ),
1536 Extension(
1537 Extension(
1537 'mercurial.cext.parsers',
1538 'mercurial.cext.parsers',
1538 [
1539 [
1539 'mercurial/cext/charencode.c',
1540 'mercurial/cext/charencode.c',
1540 'mercurial/cext/dirs.c',
1541 'mercurial/cext/dirs.c',
1541 'mercurial/cext/manifest.c',
1542 'mercurial/cext/manifest.c',
1542 'mercurial/cext/parsers.c',
1543 'mercurial/cext/parsers.c',
1543 'mercurial/cext/pathencode.c',
1544 'mercurial/cext/pathencode.c',
1544 'mercurial/cext/revlog.c',
1545 'mercurial/cext/revlog.c',
1545 ],
1546 ],
1546 include_dirs=common_include_dirs,
1547 include_dirs=common_include_dirs,
1547 extra_compile_args=common_cflags,
1548 extra_compile_args=common_cflags,
1548 depends=common_depends
1549 depends=common_depends
1549 + [
1550 + [
1550 'mercurial/cext/charencode.h',
1551 'mercurial/cext/charencode.h',
1551 'mercurial/cext/revlog.h',
1552 'mercurial/cext/revlog.h',
1552 ],
1553 ],
1553 ),
1554 ),
1554 Extension(
1555 Extension(
1555 'mercurial.cext.osutil',
1556 'mercurial.cext.osutil',
1556 ['mercurial/cext/osutil.c'],
1557 ['mercurial/cext/osutil.c'],
1557 include_dirs=common_include_dirs,
1558 include_dirs=common_include_dirs,
1558 extra_compile_args=common_cflags + osutil_cflags,
1559 extra_compile_args=common_cflags + osutil_cflags,
1559 extra_link_args=osutil_ldflags,
1560 extra_link_args=osutil_ldflags,
1560 depends=common_depends,
1561 depends=common_depends,
1561 ),
1562 ),
1562 Extension(
1563 Extension(
1563 'mercurial.thirdparty.zope.interface._zope_interface_coptimizations',
1564 'mercurial.thirdparty.zope.interface._zope_interface_coptimizations',
1564 [
1565 [
1565 'mercurial/thirdparty/zope/interface/_zope_interface_coptimizations.c',
1566 'mercurial/thirdparty/zope/interface/_zope_interface_coptimizations.c',
1566 ],
1567 ],
1567 extra_compile_args=common_cflags,
1568 extra_compile_args=common_cflags,
1568 ),
1569 ),
1569 Extension(
1570 Extension(
1570 'mercurial.thirdparty.sha1dc',
1571 'mercurial.thirdparty.sha1dc',
1571 [
1572 [
1572 'mercurial/thirdparty/sha1dc/cext.c',
1573 'mercurial/thirdparty/sha1dc/cext.c',
1573 'mercurial/thirdparty/sha1dc/lib/sha1.c',
1574 'mercurial/thirdparty/sha1dc/lib/sha1.c',
1574 'mercurial/thirdparty/sha1dc/lib/ubc_check.c',
1575 'mercurial/thirdparty/sha1dc/lib/ubc_check.c',
1575 ],
1576 ],
1576 extra_compile_args=common_cflags,
1577 extra_compile_args=common_cflags,
1577 ),
1578 ),
1578 Extension(
1579 Extension(
1579 'hgext.fsmonitor.pywatchman.bser',
1580 'hgext.fsmonitor.pywatchman.bser',
1580 ['hgext/fsmonitor/pywatchman/bser.c'],
1581 ['hgext/fsmonitor/pywatchman/bser.c'],
1581 extra_compile_args=common_cflags,
1582 extra_compile_args=common_cflags,
1582 ),
1583 ),
1583 RustStandaloneExtension(
1584 RustStandaloneExtension(
1584 'mercurial.rustext',
1585 'mercurial.rustext',
1585 'hg-cpython',
1586 'hg-cpython',
1586 'librusthg',
1587 'librusthg',
1587 ),
1588 ),
1588 ]
1589 ]
1589
1590
1590
1591
1591 sys.path.insert(0, 'contrib/python-zstandard')
1592 sys.path.insert(0, 'contrib/python-zstandard')
1592 import setup_zstd
1593 import setup_zstd
1593
1594
1594 zstd = setup_zstd.get_c_extension(
1595 zstd = setup_zstd.get_c_extension(
1595 name='mercurial.zstd', root=os.path.abspath(os.path.dirname(__file__))
1596 name='mercurial.zstd', root=os.path.abspath(os.path.dirname(__file__))
1596 )
1597 )
1597 zstd.extra_compile_args += common_cflags
1598 zstd.extra_compile_args += common_cflags
1598 extmodules.append(zstd)
1599 extmodules.append(zstd)
1599
1600
1600 try:
1601 try:
1601 from distutils import cygwinccompiler
1602 from distutils import cygwinccompiler
1602
1603
1603 # the -mno-cygwin option has been deprecated for years
1604 # the -mno-cygwin option has been deprecated for years
1604 mingw32compilerclass = cygwinccompiler.Mingw32CCompiler
1605 mingw32compilerclass = cygwinccompiler.Mingw32CCompiler
1605
1606
1606 class HackedMingw32CCompiler(cygwinccompiler.Mingw32CCompiler):
1607 class HackedMingw32CCompiler(cygwinccompiler.Mingw32CCompiler):
1607 def __init__(self, *args, **kwargs):
1608 def __init__(self, *args, **kwargs):
1608 mingw32compilerclass.__init__(self, *args, **kwargs)
1609 mingw32compilerclass.__init__(self, *args, **kwargs)
1609 for i in 'compiler compiler_so linker_exe linker_so'.split():
1610 for i in 'compiler compiler_so linker_exe linker_so'.split():
1610 try:
1611 try:
1611 getattr(self, i).remove('-mno-cygwin')
1612 getattr(self, i).remove('-mno-cygwin')
1612 except ValueError:
1613 except ValueError:
1613 pass
1614 pass
1614
1615
1615 cygwinccompiler.Mingw32CCompiler = HackedMingw32CCompiler
1616 cygwinccompiler.Mingw32CCompiler = HackedMingw32CCompiler
1616 except ImportError:
1617 except ImportError:
1617 # the cygwinccompiler package is not available on some Python
1618 # the cygwinccompiler package is not available on some Python
1618 # distributions like the ones from the optware project for Synology
1619 # distributions like the ones from the optware project for Synology
1619 # DiskStation boxes
1620 # DiskStation boxes
1620 class HackedMingw32CCompiler:
1621 class HackedMingw32CCompiler:
1621 pass
1622 pass
1622
1623
1623
1624
1624 if os.name == 'nt':
1625 if os.name == 'nt':
1625 # Allow compiler/linker flags to be added to Visual Studio builds. Passing
1626 # Allow compiler/linker flags to be added to Visual Studio builds. Passing
1626 # extra_link_args to distutils.extensions.Extension() doesn't have any
1627 # extra_link_args to distutils.extensions.Extension() doesn't have any
1627 # effect.
1628 # effect.
1628 from distutils import msvccompiler
1629 from distutils import msvccompiler
1629
1630
1630 msvccompilerclass = msvccompiler.MSVCCompiler
1631 msvccompilerclass = msvccompiler.MSVCCompiler
1631
1632
1632 class HackedMSVCCompiler(msvccompiler.MSVCCompiler):
1633 class HackedMSVCCompiler(msvccompiler.MSVCCompiler):
1633 def initialize(self):
1634 def initialize(self):
1634 msvccompilerclass.initialize(self)
1635 msvccompilerclass.initialize(self)
1635 # "warning LNK4197: export 'func' specified multiple times"
1636 # "warning LNK4197: export 'func' specified multiple times"
1636 self.ldflags_shared.append('/ignore:4197')
1637 self.ldflags_shared.append('/ignore:4197')
1637 self.ldflags_shared_debug.append('/ignore:4197')
1638 self.ldflags_shared_debug.append('/ignore:4197')
1638
1639
1639 msvccompiler.MSVCCompiler = HackedMSVCCompiler
1640 msvccompiler.MSVCCompiler = HackedMSVCCompiler
1640
1641
1641 packagedata = {
1642 packagedata = {
1642 'mercurial': [
1643 'mercurial': [
1643 'locale/*/LC_MESSAGES/hg.mo',
1644 'locale/*/LC_MESSAGES/hg.mo',
1644 'dummycert.pem',
1645 'dummycert.pem',
1645 ],
1646 ],
1646 'mercurial.defaultrc': [
1647 'mercurial.defaultrc': [
1647 '*.rc',
1648 '*.rc',
1648 ],
1649 ],
1649 'mercurial.helptext': [
1650 'mercurial.helptext': [
1650 '*.txt',
1651 '*.txt',
1651 ],
1652 ],
1652 'mercurial.helptext.internals': [
1653 'mercurial.helptext.internals': [
1653 '*.txt',
1654 '*.txt',
1654 ],
1655 ],
1655 'mercurial.thirdparty.attr': [
1656 'mercurial.thirdparty.attr': [
1656 '*.pyi',
1657 '*.pyi',
1657 'py.typed',
1658 'py.typed',
1658 ],
1659 ],
1659 }
1660 }
1660
1661
1661
1662
1662 def ordinarypath(p):
1663 def ordinarypath(p):
1663 return p and p[0] != '.' and p[-1] != '~'
1664 return p and p[0] != '.' and p[-1] != '~'
1664
1665
1665
1666
1666 for root in ('templates',):
1667 for root in ('templates',):
1667 for curdir, dirs, files in os.walk(os.path.join('mercurial', root)):
1668 for curdir, dirs, files in os.walk(os.path.join('mercurial', root)):
1668 packagename = curdir.replace(os.sep, '.')
1669 packagename = curdir.replace(os.sep, '.')
1669 packagedata[packagename] = list(filter(ordinarypath, files))
1670 packagedata[packagename] = list(filter(ordinarypath, files))
1670
1671
1671 datafiles = []
1672 datafiles = []
1672
1673
1673 # distutils expects version to be str/unicode. Converting it to
1674 # distutils expects version to be str/unicode. Converting it to
1674 # unicode on Python 2 still works because it won't contain any
1675 # unicode on Python 2 still works because it won't contain any
1675 # non-ascii bytes and will be implicitly converted back to bytes
1676 # non-ascii bytes and will be implicitly converted back to bytes
1676 # when operated on.
1677 # when operated on.
1677 assert isinstance(version, str)
1678 assert isinstance(version, str)
1678 setupversion = version
1679 setupversion = version
1679
1680
1680 extra = {}
1681 extra = {}
1681
1682
1682 py2exepackages = [
1683 py2exepackages = [
1683 'hgdemandimport',
1684 'hgdemandimport',
1684 'hgext3rd',
1685 'hgext3rd',
1685 'hgext',
1686 'hgext',
1686 'email',
1687 'email',
1687 # implicitly imported per module policy
1688 # implicitly imported per module policy
1688 # (cffi wouldn't be used as a frozen exe)
1689 # (cffi wouldn't be used as a frozen exe)
1689 'mercurial.cext',
1690 'mercurial.cext',
1690 #'mercurial.cffi',
1691 #'mercurial.cffi',
1691 'mercurial.pure',
1692 'mercurial.pure',
1692 ]
1693 ]
1693
1694
1694 py2exe_includes = []
1695 py2exe_includes = []
1695
1696
1696 py2exeexcludes = []
1697 py2exeexcludes = []
1697 py2exedllexcludes = ['crypt32.dll']
1698 py2exedllexcludes = ['crypt32.dll']
1698
1699
1699 if issetuptools:
1700 if issetuptools:
1700 extra['python_requires'] = supportedpy
1701 extra['python_requires'] = supportedpy
1701
1702
1702 if py2exeloaded:
1703 if py2exeloaded:
1703 extra['console'] = [
1704 extra['console'] = [
1704 {
1705 {
1705 'script': 'hg',
1706 'script': 'hg',
1706 'copyright': 'Copyright (C) 2005-2023 Olivia Mackall and others',
1707 'copyright': 'Copyright (C) 2005-2023 Olivia Mackall and others',
1707 'product_version': version,
1708 'product_version': version,
1708 }
1709 }
1709 ]
1710 ]
1710 # Sub command of 'build' because 'py2exe' does not handle sub_commands.
1711 # Sub command of 'build' because 'py2exe' does not handle sub_commands.
1711 # Need to override hgbuild because it has a private copy of
1712 # Need to override hgbuild because it has a private copy of
1712 # build.sub_commands.
1713 # build.sub_commands.
1713 hgbuild.sub_commands.insert(0, ('build_hgextindex', None))
1714 hgbuild.sub_commands.insert(0, ('build_hgextindex', None))
1714 # put dlls in sub directory so that they won't pollute PATH
1715 # put dlls in sub directory so that they won't pollute PATH
1715 extra['zipfile'] = 'lib/library.zip'
1716 extra['zipfile'] = 'lib/library.zip'
1716
1717
1717 # We allow some configuration to be supplemented via environment
1718 # We allow some configuration to be supplemented via environment
1718 # variables. This is better than setup.cfg files because it allows
1719 # variables. This is better than setup.cfg files because it allows
1719 # supplementing configs instead of replacing them.
1720 # supplementing configs instead of replacing them.
1720 extrapackages = os.environ.get('HG_PY2EXE_EXTRA_PACKAGES')
1721 extrapackages = os.environ.get('HG_PY2EXE_EXTRA_PACKAGES')
1721 if extrapackages:
1722 if extrapackages:
1722 py2exepackages.extend(extrapackages.split(' '))
1723 py2exepackages.extend(extrapackages.split(' '))
1723
1724
1724 extra_includes = os.environ.get('HG_PY2EXE_EXTRA_INCLUDES')
1725 extra_includes = os.environ.get('HG_PY2EXE_EXTRA_INCLUDES')
1725 if extra_includes:
1726 if extra_includes:
1726 py2exe_includes.extend(extra_includes.split(' '))
1727 py2exe_includes.extend(extra_includes.split(' '))
1727
1728
1728 excludes = os.environ.get('HG_PY2EXE_EXTRA_EXCLUDES')
1729 excludes = os.environ.get('HG_PY2EXE_EXTRA_EXCLUDES')
1729 if excludes:
1730 if excludes:
1730 py2exeexcludes.extend(excludes.split(' '))
1731 py2exeexcludes.extend(excludes.split(' '))
1731
1732
1732 dllexcludes = os.environ.get('HG_PY2EXE_EXTRA_DLL_EXCLUDES')
1733 dllexcludes = os.environ.get('HG_PY2EXE_EXTRA_DLL_EXCLUDES')
1733 if dllexcludes:
1734 if dllexcludes:
1734 py2exedllexcludes.extend(dllexcludes.split(' '))
1735 py2exedllexcludes.extend(dllexcludes.split(' '))
1735
1736
1736 if os.environ.get('PYOXIDIZER'):
1737 if os.environ.get('PYOXIDIZER'):
1737 hgbuild.sub_commands.insert(0, ('build_hgextindex', None))
1738 hgbuild.sub_commands.insert(0, ('build_hgextindex', None))
1738
1739
1739 if os.name == 'nt':
1740 if os.name == 'nt':
1740 # Windows binary file versions for exe/dll files must have the
1741 # Windows binary file versions for exe/dll files must have the
1741 # form W.X.Y.Z, where W,X,Y,Z are numbers in the range 0..65535
1742 # form W.X.Y.Z, where W,X,Y,Z are numbers in the range 0..65535
1742 setupversion = setupversion.split(r'+', 1)[0]
1743 setupversion = setupversion.split(r'+', 1)[0]
1743
1744
1744 setup(
1745 setup(
1745 name='mercurial',
1746 name='mercurial',
1746 version=setupversion,
1747 version=setupversion,
1747 author='Olivia Mackall and many others',
1748 author='Olivia Mackall and many others',
1748 author_email='mercurial@mercurial-scm.org',
1749 author_email='mercurial@mercurial-scm.org',
1749 url='https://mercurial-scm.org/',
1750 url='https://mercurial-scm.org/',
1750 download_url='https://mercurial-scm.org/release/',
1751 download_url='https://mercurial-scm.org/release/',
1751 description=(
1752 description=(
1752 'Fast scalable distributed SCM (revision control, version '
1753 'Fast scalable distributed SCM (revision control, version '
1753 'control) system'
1754 'control) system'
1754 ),
1755 ),
1755 long_description=(
1756 long_description=(
1756 'Mercurial is a distributed SCM tool written in Python.'
1757 'Mercurial is a distributed SCM tool written in Python.'
1757 ' It is used by a number of large projects that require'
1758 ' It is used by a number of large projects that require'
1758 ' fast, reliable distributed revision control, such as '
1759 ' fast, reliable distributed revision control, such as '
1759 'Mozilla.'
1760 'Mozilla.'
1760 ),
1761 ),
1761 license='GNU GPLv2 or any later version',
1762 license='GNU GPLv2 or any later version',
1762 classifiers=[
1763 classifiers=[
1763 'Development Status :: 6 - Mature',
1764 'Development Status :: 6 - Mature',
1764 'Environment :: Console',
1765 'Environment :: Console',
1765 'Intended Audience :: Developers',
1766 'Intended Audience :: Developers',
1766 'Intended Audience :: System Administrators',
1767 'Intended Audience :: System Administrators',
1767 'License :: OSI Approved :: GNU General Public License (GPL)',
1768 'License :: OSI Approved :: GNU General Public License (GPL)',
1768 'Natural Language :: Danish',
1769 'Natural Language :: Danish',
1769 'Natural Language :: English',
1770 'Natural Language :: English',
1770 'Natural Language :: German',
1771 'Natural Language :: German',
1771 'Natural Language :: Italian',
1772 'Natural Language :: Italian',
1772 'Natural Language :: Japanese',
1773 'Natural Language :: Japanese',
1773 'Natural Language :: Portuguese (Brazilian)',
1774 'Natural Language :: Portuguese (Brazilian)',
1774 'Operating System :: Microsoft :: Windows',
1775 'Operating System :: Microsoft :: Windows',
1775 'Operating System :: OS Independent',
1776 'Operating System :: OS Independent',
1776 'Operating System :: POSIX',
1777 'Operating System :: POSIX',
1777 'Programming Language :: C',
1778 'Programming Language :: C',
1778 'Programming Language :: Python',
1779 'Programming Language :: Python',
1779 'Topic :: Software Development :: Version Control',
1780 'Topic :: Software Development :: Version Control',
1780 ],
1781 ],
1781 scripts=scripts,
1782 scripts=scripts,
1782 packages=packages,
1783 packages=packages,
1783 ext_modules=extmodules,
1784 ext_modules=extmodules,
1784 data_files=datafiles,
1785 data_files=datafiles,
1785 package_data=packagedata,
1786 package_data=packagedata,
1786 cmdclass=cmdclass,
1787 cmdclass=cmdclass,
1787 distclass=hgdist,
1788 distclass=hgdist,
1788 options={
1789 options={
1789 'py2exe': {
1790 'py2exe': {
1790 'bundle_files': 3,
1791 'bundle_files': 3,
1791 'dll_excludes': py2exedllexcludes,
1792 'dll_excludes': py2exedllexcludes,
1792 'includes': py2exe_includes,
1793 'includes': py2exe_includes,
1793 'excludes': py2exeexcludes,
1794 'excludes': py2exeexcludes,
1794 'packages': py2exepackages,
1795 'packages': py2exepackages,
1795 },
1796 },
1796 'bdist_mpkg': {
1797 'bdist_mpkg': {
1797 'zipdist': False,
1798 'zipdist': False,
1798 'license': 'COPYING',
1799 'license': 'COPYING',
1799 'readme': 'contrib/packaging/macosx/Readme.html',
1800 'readme': 'contrib/packaging/macosx/Readme.html',
1800 'welcome': 'contrib/packaging/macosx/Welcome.html',
1801 'welcome': 'contrib/packaging/macosx/Welcome.html',
1801 },
1802 },
1802 },
1803 },
1803 **extra
1804 **extra
1804 )
1805 )
@@ -1,451 +1,453 b''
1 Show all commands except debug commands
1 Show all commands except debug commands
2 $ hg debugcomplete
2 $ hg debugcomplete
3 abort
3 abort
4 add
4 add
5 addremove
5 addremove
6 annotate
6 annotate
7 archive
7 archive
8 backout
8 backout
9 bisect
9 bisect
10 bookmarks
10 bookmarks
11 branch
11 branch
12 branches
12 branches
13 bundle
13 bundle
14 cat
14 cat
15 clone
15 clone
16 commit
16 commit
17 config
17 config
18 continue
18 continue
19 copy
19 copy
20 diff
20 diff
21 export
21 export
22 files
22 files
23 forget
23 forget
24 graft
24 graft
25 grep
25 grep
26 heads
26 heads
27 help
27 help
28 identify
28 identify
29 import
29 import
30 incoming
30 incoming
31 init
31 init
32 locate
32 locate
33 log
33 log
34 manifest
34 manifest
35 merge
35 merge
36 outgoing
36 outgoing
37 parents
37 parents
38 paths
38 paths
39 phase
39 phase
40 pull
40 pull
41 purge
41 purge
42 push
42 push
43 recover
43 recover
44 remove
44 remove
45 rename
45 rename
46 resolve
46 resolve
47 revert
47 revert
48 rollback
48 rollback
49 root
49 root
50 serve
50 serve
51 shelve
51 shelve
52 status
52 status
53 summary
53 summary
54 tag
54 tag
55 tags
55 tags
56 tip
56 tip
57 unbundle
57 unbundle
58 unshelve
58 unshelve
59 update
59 update
60 verify
60 verify
61 version
61 version
62
62
63 Show all commands that start with "a"
63 Show all commands that start with "a"
64 $ hg debugcomplete a
64 $ hg debugcomplete a
65 abort
65 abort
66 add
66 add
67 addremove
67 addremove
68 annotate
68 annotate
69 archive
69 archive
70
70
71 Do not show debug commands if there are other candidates
71 Do not show debug commands if there are other candidates
72 $ hg debugcomplete d
72 $ hg debugcomplete d
73 diff
73 diff
74
74
75 Show debug commands if there are no other candidates
75 Show debug commands if there are no other candidates
76 $ hg debugcomplete debug
76 $ hg debugcomplete debug
77 debug-delta-find
77 debug-delta-find
78 debug-repair-issue6528
78 debug-repair-issue6528
79 debug-revlog-index
79 debug-revlog-index
80 debug-revlog-stats
80 debug-revlog-stats
81 debug::stable-tail-sort
81 debugancestor
82 debugancestor
82 debugantivirusrunning
83 debugantivirusrunning
83 debugapplystreamclonebundle
84 debugapplystreamclonebundle
84 debugbackupbundle
85 debugbackupbundle
85 debugbuilddag
86 debugbuilddag
86 debugbundle
87 debugbundle
87 debugcapabilities
88 debugcapabilities
88 debugchangedfiles
89 debugchangedfiles
89 debugcheckstate
90 debugcheckstate
90 debugcolor
91 debugcolor
91 debugcommands
92 debugcommands
92 debugcomplete
93 debugcomplete
93 debugconfig
94 debugconfig
94 debugcreatestreamclonebundle
95 debugcreatestreamclonebundle
95 debugdag
96 debugdag
96 debugdata
97 debugdata
97 debugdate
98 debugdate
98 debugdeltachain
99 debugdeltachain
99 debugdirstate
100 debugdirstate
100 debugdirstateignorepatternshash
101 debugdirstateignorepatternshash
101 debugdiscovery
102 debugdiscovery
102 debugdownload
103 debugdownload
103 debugextensions
104 debugextensions
104 debugfileset
105 debugfileset
105 debugformat
106 debugformat
106 debugfsinfo
107 debugfsinfo
107 debuggetbundle
108 debuggetbundle
108 debugignore
109 debugignore
109 debugindexdot
110 debugindexdot
110 debugindexstats
111 debugindexstats
111 debuginstall
112 debuginstall
112 debugknown
113 debugknown
113 debuglabelcomplete
114 debuglabelcomplete
114 debuglocks
115 debuglocks
115 debugmanifestfulltextcache
116 debugmanifestfulltextcache
116 debugmergestate
117 debugmergestate
117 debugnamecomplete
118 debugnamecomplete
118 debugnodemap
119 debugnodemap
119 debugobsolete
120 debugobsolete
120 debugp1copies
121 debugp1copies
121 debugp2copies
122 debugp2copies
122 debugpathcomplete
123 debugpathcomplete
123 debugpathcopies
124 debugpathcopies
124 debugpeer
125 debugpeer
125 debugpickmergetool
126 debugpickmergetool
126 debugpushkey
127 debugpushkey
127 debugpvec
128 debugpvec
128 debugrebuilddirstate
129 debugrebuilddirstate
129 debugrebuildfncache
130 debugrebuildfncache
130 debugrename
131 debugrename
131 debugrequires
132 debugrequires
132 debugrevlog
133 debugrevlog
133 debugrevlogindex
134 debugrevlogindex
134 debugrevspec
135 debugrevspec
135 debugserve
136 debugserve
136 debugsetparents
137 debugsetparents
137 debugshell
138 debugshell
138 debugsidedata
139 debugsidedata
139 debugssl
140 debugssl
140 debugstrip
141 debugstrip
141 debugsub
142 debugsub
142 debugsuccessorssets
143 debugsuccessorssets
143 debugtagscache
144 debugtagscache
144 debugtemplate
145 debugtemplate
145 debuguigetpass
146 debuguigetpass
146 debuguiprompt
147 debuguiprompt
147 debugupdatecaches
148 debugupdatecaches
148 debugupgraderepo
149 debugupgraderepo
149 debugwalk
150 debugwalk
150 debugwhyunstable
151 debugwhyunstable
151 debugwireargs
152 debugwireargs
152 debugwireproto
153 debugwireproto
153
154
154 Do not show the alias of a debug command if there are other candidates
155 Do not show the alias of a debug command if there are other candidates
155 (this should hide rawcommit)
156 (this should hide rawcommit)
156 $ hg debugcomplete r
157 $ hg debugcomplete r
157 recover
158 recover
158 remove
159 remove
159 rename
160 rename
160 resolve
161 resolve
161 revert
162 revert
162 rollback
163 rollback
163 root
164 root
164 Show the alias of a debug command if there are no other candidates
165 Show the alias of a debug command if there are no other candidates
165 $ hg debugcomplete rawc
166 $ hg debugcomplete rawc
166
167
167
168
168 Show the global options
169 Show the global options
169 $ hg debugcomplete --options | sort
170 $ hg debugcomplete --options | sort
170 --color
171 --color
171 --config
172 --config
172 --cwd
173 --cwd
173 --debug
174 --debug
174 --debugger
175 --debugger
175 --encoding
176 --encoding
176 --encodingmode
177 --encodingmode
177 --help
178 --help
178 --hidden
179 --hidden
179 --noninteractive
180 --noninteractive
180 --pager
181 --pager
181 --profile
182 --profile
182 --quiet
183 --quiet
183 --repository
184 --repository
184 --time
185 --time
185 --traceback
186 --traceback
186 --verbose
187 --verbose
187 --version
188 --version
188 -R
189 -R
189 -h
190 -h
190 -q
191 -q
191 -v
192 -v
192 -y
193 -y
193
194
194 Show the options for the "serve" command
195 Show the options for the "serve" command
195 $ hg debugcomplete --options serve | sort
196 $ hg debugcomplete --options serve | sort
196 --accesslog
197 --accesslog
197 --address
198 --address
198 --certificate
199 --certificate
199 --cmdserver
200 --cmdserver
200 --color
201 --color
201 --config
202 --config
202 --cwd
203 --cwd
203 --daemon
204 --daemon
204 --daemon-postexec
205 --daemon-postexec
205 --debug
206 --debug
206 --debugger
207 --debugger
207 --encoding
208 --encoding
208 --encodingmode
209 --encodingmode
209 --errorlog
210 --errorlog
210 --help
211 --help
211 --hidden
212 --hidden
212 --ipv6
213 --ipv6
213 --name
214 --name
214 --noninteractive
215 --noninteractive
215 --pager
216 --pager
216 --pid-file
217 --pid-file
217 --port
218 --port
218 --prefix
219 --prefix
219 --print-url
220 --print-url
220 --profile
221 --profile
221 --quiet
222 --quiet
222 --repository
223 --repository
223 --stdio
224 --stdio
224 --style
225 --style
225 --subrepos
226 --subrepos
226 --templates
227 --templates
227 --time
228 --time
228 --traceback
229 --traceback
229 --verbose
230 --verbose
230 --version
231 --version
231 --web-conf
232 --web-conf
232 -6
233 -6
233 -A
234 -A
234 -E
235 -E
235 -R
236 -R
236 -S
237 -S
237 -a
238 -a
238 -d
239 -d
239 -h
240 -h
240 -n
241 -n
241 -p
242 -p
242 -q
243 -q
243 -t
244 -t
244 -v
245 -v
245 -y
246 -y
246
247
247 Show an error if we use --options with an ambiguous abbreviation
248 Show an error if we use --options with an ambiguous abbreviation
248 $ hg debugcomplete --options s
249 $ hg debugcomplete --options s
249 hg: command 's' is ambiguous:
250 hg: command 's' is ambiguous:
250 serve shelve showconfig status summary
251 serve shelve showconfig status summary
251 [10]
252 [10]
252
253
253 Show all commands + options
254 Show all commands + options
254 $ hg debugcommands
255 $ hg debugcommands
255 abort: dry-run
256 abort: dry-run
256 add: include, exclude, subrepos, dry-run
257 add: include, exclude, subrepos, dry-run
257 addremove: similarity, subrepos, include, exclude, dry-run
258 addremove: similarity, subrepos, include, exclude, dry-run
258 annotate: rev, follow, no-follow, text, user, file, date, number, changeset, line-number, skip, ignore-all-space, ignore-space-change, ignore-blank-lines, ignore-space-at-eol, include, exclude, template
259 annotate: rev, follow, no-follow, text, user, file, date, number, changeset, line-number, skip, ignore-all-space, ignore-space-change, ignore-blank-lines, ignore-space-at-eol, include, exclude, template
259 archive: no-decode, prefix, rev, type, subrepos, include, exclude
260 archive: no-decode, prefix, rev, type, subrepos, include, exclude
260 backout: merge, commit, no-commit, parent, rev, edit, tool, include, exclude, message, logfile, date, user
261 backout: merge, commit, no-commit, parent, rev, edit, tool, include, exclude, message, logfile, date, user
261 bisect: reset, good, bad, skip, extend, command, noupdate
262 bisect: reset, good, bad, skip, extend, command, noupdate
262 bookmarks: force, rev, delete, rename, inactive, list, template
263 bookmarks: force, rev, delete, rename, inactive, list, template
263 branch: force, clean, rev
264 branch: force, clean, rev
264 branches: active, closed, rev, template
265 branches: active, closed, rev, template
265 bundle: exact, force, rev, branch, base, all, type, ssh, remotecmd, insecure
266 bundle: exact, force, rev, branch, base, all, type, ssh, remotecmd, insecure
266 cat: output, rev, decode, include, exclude, template
267 cat: output, rev, decode, include, exclude, template
267 clone: noupdate, updaterev, rev, branch, pull, uncompressed, stream, ssh, remotecmd, insecure
268 clone: noupdate, updaterev, rev, branch, pull, uncompressed, stream, ssh, remotecmd, insecure
268 commit: addremove, close-branch, amend, secret, draft, edit, force-close-branch, interactive, include, exclude, message, logfile, date, user, subrepos
269 commit: addremove, close-branch, amend, secret, draft, edit, force-close-branch, interactive, include, exclude, message, logfile, date, user, subrepos
269 config: untrusted, exp-all-known, edit, local, source, shared, non-shared, global, template
270 config: untrusted, exp-all-known, edit, local, source, shared, non-shared, global, template
270 continue: dry-run
271 continue: dry-run
271 copy: forget, after, at-rev, force, include, exclude, dry-run
272 copy: forget, after, at-rev, force, include, exclude, dry-run
272 debug-delta-find: changelog, manifest, dir, template, source
273 debug-delta-find: changelog, manifest, dir, template, source
273 debug-repair-issue6528: to-report, from-report, paranoid, dry-run
274 debug-repair-issue6528: to-report, from-report, paranoid, dry-run
274 debug-revlog-index: changelog, manifest, dir, template
275 debug-revlog-index: changelog, manifest, dir, template
275 debug-revlog-stats: changelog, manifest, filelogs, template
276 debug-revlog-stats: changelog, manifest, filelogs, template
277 debug::stable-tail-sort: template
276 debugancestor:
278 debugancestor:
277 debugantivirusrunning:
279 debugantivirusrunning:
278 debugapplystreamclonebundle:
280 debugapplystreamclonebundle:
279 debugbackupbundle: recover, patch, git, limit, no-merges, stat, graph, style, template
281 debugbackupbundle: recover, patch, git, limit, no-merges, stat, graph, style, template
280 debugbuilddag: mergeable-file, overwritten-file, new-file, from-existing
282 debugbuilddag: mergeable-file, overwritten-file, new-file, from-existing
281 debugbundle: all, part-type, spec
283 debugbundle: all, part-type, spec
282 debugcapabilities:
284 debugcapabilities:
283 debugchangedfiles: compute
285 debugchangedfiles: compute
284 debugcheckstate:
286 debugcheckstate:
285 debugcolor: style
287 debugcolor: style
286 debugcommands:
288 debugcommands:
287 debugcomplete: options
289 debugcomplete: options
288 debugcreatestreamclonebundle:
290 debugcreatestreamclonebundle:
289 debugdag: tags, branches, dots, spaces
291 debugdag: tags, branches, dots, spaces
290 debugdata: changelog, manifest, dir
292 debugdata: changelog, manifest, dir
291 debugdate: extended
293 debugdate: extended
292 debugdeltachain: changelog, manifest, dir, template
294 debugdeltachain: changelog, manifest, dir, template
293 debugdirstateignorepatternshash:
295 debugdirstateignorepatternshash:
294 debugdirstate: nodates, dates, datesort, docket, all
296 debugdirstate: nodates, dates, datesort, docket, all
295 debugdiscovery: old, nonheads, rev, seed, local-as-revs, remote-as-revs, ssh, remotecmd, insecure, template
297 debugdiscovery: old, nonheads, rev, seed, local-as-revs, remote-as-revs, ssh, remotecmd, insecure, template
296 debugdownload: output
298 debugdownload: output
297 debugextensions: template
299 debugextensions: template
298 debugfileset: rev, all-files, show-matcher, show-stage
300 debugfileset: rev, all-files, show-matcher, show-stage
299 debugformat: template
301 debugformat: template
300 debugfsinfo:
302 debugfsinfo:
301 debuggetbundle: head, common, type
303 debuggetbundle: head, common, type
302 debugignore:
304 debugignore:
303 debugindexdot: changelog, manifest, dir
305 debugindexdot: changelog, manifest, dir
304 debugindexstats:
306 debugindexstats:
305 debuginstall: template
307 debuginstall: template
306 debugknown:
308 debugknown:
307 debuglabelcomplete:
309 debuglabelcomplete:
308 debuglocks: force-free-lock, force-free-wlock, set-lock, set-wlock
310 debuglocks: force-free-lock, force-free-wlock, set-lock, set-wlock
309 debugmanifestfulltextcache: clear, add
311 debugmanifestfulltextcache: clear, add
310 debugmergestate: style, template
312 debugmergestate: style, template
311 debugnamecomplete:
313 debugnamecomplete:
312 debugnodemap: dump-new, dump-disk, check, metadata
314 debugnodemap: dump-new, dump-disk, check, metadata
313 debugobsolete: flags, record-parents, rev, exclusive, index, delete, date, user, template
315 debugobsolete: flags, record-parents, rev, exclusive, index, delete, date, user, template
314 debugp1copies: rev
316 debugp1copies: rev
315 debugp2copies: rev
317 debugp2copies: rev
316 debugpathcomplete: full, normal, added, removed
318 debugpathcomplete: full, normal, added, removed
317 debugpathcopies: include, exclude
319 debugpathcopies: include, exclude
318 debugpeer:
320 debugpeer:
319 debugpickmergetool: rev, changedelete, include, exclude, tool
321 debugpickmergetool: rev, changedelete, include, exclude, tool
320 debugpushkey:
322 debugpushkey:
321 debugpvec:
323 debugpvec:
322 debugrebuilddirstate: rev, minimal
324 debugrebuilddirstate: rev, minimal
323 debugrebuildfncache: only-data
325 debugrebuildfncache: only-data
324 debugrename: rev
326 debugrename: rev
325 debugrequires:
327 debugrequires:
326 debugrevlog: changelog, manifest, dir, dump
328 debugrevlog: changelog, manifest, dir, dump
327 debugrevlogindex: changelog, manifest, dir, format
329 debugrevlogindex: changelog, manifest, dir, format
328 debugrevspec: optimize, show-revs, show-set, show-stage, no-optimized, verify-optimized
330 debugrevspec: optimize, show-revs, show-set, show-stage, no-optimized, verify-optimized
329 debugserve: sshstdio, logiofd, logiofile
331 debugserve: sshstdio, logiofd, logiofile
330 debugsetparents:
332 debugsetparents:
331 debugshell: command
333 debugshell: command
332 debugsidedata: changelog, manifest, dir
334 debugsidedata: changelog, manifest, dir
333 debugssl:
335 debugssl:
334 debugstrip: rev, force, no-backup, nobackup, , keep, bookmark, soft
336 debugstrip: rev, force, no-backup, nobackup, , keep, bookmark, soft
335 debugsub: rev
337 debugsub: rev
336 debugsuccessorssets: closest
338 debugsuccessorssets: closest
337 debugtagscache:
339 debugtagscache:
338 debugtemplate: rev, define
340 debugtemplate: rev, define
339 debuguigetpass: prompt
341 debuguigetpass: prompt
340 debuguiprompt: prompt
342 debuguiprompt: prompt
341 debugupdatecaches:
343 debugupdatecaches:
342 debugupgraderepo: optimize, run, backup, changelog, manifest, filelogs
344 debugupgraderepo: optimize, run, backup, changelog, manifest, filelogs
343 debugwalk: include, exclude
345 debugwalk: include, exclude
344 debugwhyunstable:
346 debugwhyunstable:
345 debugwireargs: three, four, five, ssh, remotecmd, insecure
347 debugwireargs: three, four, five, ssh, remotecmd, insecure
346 debugwireproto: localssh, peer, noreadstderr, nologhandshake, ssh, remotecmd, insecure
348 debugwireproto: localssh, peer, noreadstderr, nologhandshake, ssh, remotecmd, insecure
347 diff: rev, from, to, change, text, git, binary, nodates, noprefix, show-function, reverse, ignore-all-space, ignore-space-change, ignore-blank-lines, ignore-space-at-eol, unified, stat, root, include, exclude, subrepos
349 diff: rev, from, to, change, text, git, binary, nodates, noprefix, show-function, reverse, ignore-all-space, ignore-space-change, ignore-blank-lines, ignore-space-at-eol, unified, stat, root, include, exclude, subrepos
348 export: bookmark, output, switch-parent, rev, text, git, binary, nodates, template
350 export: bookmark, output, switch-parent, rev, text, git, binary, nodates, template
349 files: rev, print0, include, exclude, template, subrepos
351 files: rev, print0, include, exclude, template, subrepos
350 forget: interactive, include, exclude, dry-run
352 forget: interactive, include, exclude, dry-run
351 graft: rev, base, continue, stop, abort, edit, log, no-commit, force, currentdate, currentuser, date, user, tool, dry-run
353 graft: rev, base, continue, stop, abort, edit, log, no-commit, force, currentdate, currentuser, date, user, tool, dry-run
352 grep: print0, all, diff, text, follow, ignore-case, files-with-matches, line-number, rev, all-files, user, date, template, include, exclude
354 grep: print0, all, diff, text, follow, ignore-case, files-with-matches, line-number, rev, all-files, user, date, template, include, exclude
353 heads: rev, topo, active, closed, style, template
355 heads: rev, topo, active, closed, style, template
354 help: extension, command, keyword, system
356 help: extension, command, keyword, system
355 identify: rev, num, id, branch, tags, bookmarks, ssh, remotecmd, insecure, template
357 identify: rev, num, id, branch, tags, bookmarks, ssh, remotecmd, insecure, template
356 import: strip, base, secret, edit, force, no-commit, bypass, partial, exact, prefix, import-branch, message, logfile, date, user, similarity
358 import: strip, base, secret, edit, force, no-commit, bypass, partial, exact, prefix, import-branch, message, logfile, date, user, similarity
357 incoming: force, newest-first, bundle, rev, bookmarks, branch, patch, git, limit, no-merges, stat, graph, style, template, ssh, remotecmd, insecure, subrepos
359 incoming: force, newest-first, bundle, rev, bookmarks, branch, patch, git, limit, no-merges, stat, graph, style, template, ssh, remotecmd, insecure, subrepos
358 init: ssh, remotecmd, insecure
360 init: ssh, remotecmd, insecure
359 locate: rev, print0, fullpath, include, exclude
361 locate: rev, print0, fullpath, include, exclude
360 log: follow, follow-first, date, copies, keyword, rev, line-range, removed, only-merges, user, only-branch, branch, bookmark, prune, patch, git, limit, no-merges, stat, graph, style, template, include, exclude
362 log: follow, follow-first, date, copies, keyword, rev, line-range, removed, only-merges, user, only-branch, branch, bookmark, prune, patch, git, limit, no-merges, stat, graph, style, template, include, exclude
361 manifest: rev, all, template
363 manifest: rev, all, template
362 merge: force, rev, preview, abort, tool
364 merge: force, rev, preview, abort, tool
363 outgoing: force, rev, newest-first, bookmarks, branch, patch, git, limit, no-merges, stat, graph, style, template, ssh, remotecmd, insecure, subrepos
365 outgoing: force, rev, newest-first, bookmarks, branch, patch, git, limit, no-merges, stat, graph, style, template, ssh, remotecmd, insecure, subrepos
364 parents: rev, style, template
366 parents: rev, style, template
365 paths: template
367 paths: template
366 phase: public, draft, secret, force, rev
368 phase: public, draft, secret, force, rev
367 pull: update, force, confirm, rev, bookmark, branch, ssh, remotecmd, insecure
369 pull: update, force, confirm, rev, bookmark, branch, ssh, remotecmd, insecure
368 purge: abort-on-err, all, ignored, dirs, files, print, print0, confirm, include, exclude
370 purge: abort-on-err, all, ignored, dirs, files, print, print0, confirm, include, exclude
369 push: force, rev, bookmark, all-bookmarks, branch, new-branch, pushvars, publish, ssh, remotecmd, insecure
371 push: force, rev, bookmark, all-bookmarks, branch, new-branch, pushvars, publish, ssh, remotecmd, insecure
370 recover: verify
372 recover: verify
371 remove: after, force, subrepos, include, exclude, dry-run
373 remove: after, force, subrepos, include, exclude, dry-run
372 rename: forget, after, at-rev, force, include, exclude, dry-run
374 rename: forget, after, at-rev, force, include, exclude, dry-run
373 resolve: all, list, mark, unmark, no-status, re-merge, tool, include, exclude, template
375 resolve: all, list, mark, unmark, no-status, re-merge, tool, include, exclude, template
374 revert: all, date, rev, no-backup, interactive, include, exclude, dry-run
376 revert: all, date, rev, no-backup, interactive, include, exclude, dry-run
375 rollback: dry-run, force
377 rollback: dry-run, force
376 root: template
378 root: template
377 serve: accesslog, daemon, daemon-postexec, errorlog, port, address, prefix, name, web-conf, webdir-conf, pid-file, stdio, cmdserver, templates, style, ipv6, certificate, print-url, subrepos
379 serve: accesslog, daemon, daemon-postexec, errorlog, port, address, prefix, name, web-conf, webdir-conf, pid-file, stdio, cmdserver, templates, style, ipv6, certificate, print-url, subrepos
378 shelve: addremove, unknown, cleanup, date, delete, edit, keep, list, message, name, patch, interactive, stat, include, exclude
380 shelve: addremove, unknown, cleanup, date, delete, edit, keep, list, message, name, patch, interactive, stat, include, exclude
379 status: all, modified, added, removed, deleted, clean, unknown, ignored, no-status, terse, copies, print0, rev, change, include, exclude, subrepos, template
381 status: all, modified, added, removed, deleted, clean, unknown, ignored, no-status, terse, copies, print0, rev, change, include, exclude, subrepos, template
380 summary: remote
382 summary: remote
381 tag: force, local, rev, remove, edit, message, date, user
383 tag: force, local, rev, remove, edit, message, date, user
382 tags: template
384 tags: template
383 tip: patch, git, style, template
385 tip: patch, git, style, template
384 unbundle: update
386 unbundle: update
385 unshelve: abort, continue, interactive, keep, name, tool, date
387 unshelve: abort, continue, interactive, keep, name, tool, date
386 update: clean, check, merge, date, rev, tool
388 update: clean, check, merge, date, rev, tool
387 verify: full
389 verify: full
388 version: template
390 version: template
389
391
390 $ hg init a
392 $ hg init a
391 $ cd a
393 $ cd a
392 $ echo fee > fee
394 $ echo fee > fee
393 $ hg ci -q -Amfee
395 $ hg ci -q -Amfee
394 $ hg tag fee
396 $ hg tag fee
395 $ mkdir fie
397 $ mkdir fie
396 $ echo dead > fie/dead
398 $ echo dead > fie/dead
397 $ echo live > fie/live
399 $ echo live > fie/live
398 $ hg bookmark fo
400 $ hg bookmark fo
399 $ hg branch -q fie
401 $ hg branch -q fie
400 $ hg ci -q -Amfie
402 $ hg ci -q -Amfie
401 $ echo fo > fo
403 $ echo fo > fo
402 $ hg branch -qf default
404 $ hg branch -qf default
403 $ hg ci -q -Amfo
405 $ hg ci -q -Amfo
404 $ echo Fum > Fum
406 $ echo Fum > Fum
405 $ hg ci -q -AmFum
407 $ hg ci -q -AmFum
406 $ hg bookmark Fum
408 $ hg bookmark Fum
407
409
408 Test debugpathcomplete
410 Test debugpathcomplete
409
411
410 $ hg debugpathcomplete f
412 $ hg debugpathcomplete f
411 fee
413 fee
412 fie
414 fie
413 fo
415 fo
414 $ hg debugpathcomplete -f f
416 $ hg debugpathcomplete -f f
415 fee
417 fee
416 fie/dead
418 fie/dead
417 fie/live
419 fie/live
418 fo
420 fo
419
421
420 $ hg rm Fum
422 $ hg rm Fum
421 $ hg debugpathcomplete -r F
423 $ hg debugpathcomplete -r F
422 Fum
424 Fum
423
425
424 Test debugnamecomplete
426 Test debugnamecomplete
425
427
426 $ hg debugnamecomplete
428 $ hg debugnamecomplete
427 Fum
429 Fum
428 default
430 default
429 fee
431 fee
430 fie
432 fie
431 fo
433 fo
432 tip
434 tip
433 $ hg debugnamecomplete f
435 $ hg debugnamecomplete f
434 fee
436 fee
435 fie
437 fie
436 fo
438 fo
437
439
438 Test debuglabelcomplete, a deprecated name for debugnamecomplete that is still
440 Test debuglabelcomplete, a deprecated name for debugnamecomplete that is still
439 used for completions in some shells.
441 used for completions in some shells.
440
442
441 $ hg debuglabelcomplete
443 $ hg debuglabelcomplete
442 Fum
444 Fum
443 default
445 default
444 fee
446 fee
445 fie
447 fie
446 fo
448 fo
447 tip
449 tip
448 $ hg debuglabelcomplete f
450 $ hg debuglabelcomplete f
449 fee
451 fee
450 fie
452 fie
451 fo
453 fo
@@ -1,4077 +1,4079 b''
1 Short help:
1 Short help:
2
2
3 $ hg
3 $ hg
4 Mercurial Distributed SCM
4 Mercurial Distributed SCM
5
5
6 basic commands:
6 basic commands:
7
7
8 add add the specified files on the next commit
8 add add the specified files on the next commit
9 annotate show changeset information by line for each file
9 annotate show changeset information by line for each file
10 clone make a copy of an existing repository
10 clone make a copy of an existing repository
11 commit commit the specified files or all outstanding changes
11 commit commit the specified files or all outstanding changes
12 diff diff repository (or selected files)
12 diff diff repository (or selected files)
13 export dump the header and diffs for one or more changesets
13 export dump the header and diffs for one or more changesets
14 forget forget the specified files on the next commit
14 forget forget the specified files on the next commit
15 init create a new repository in the given directory
15 init create a new repository in the given directory
16 log show revision history of entire repository or files
16 log show revision history of entire repository or files
17 merge merge another revision into working directory
17 merge merge another revision into working directory
18 pull pull changes from the specified source
18 pull pull changes from the specified source
19 push push changes to the specified destination
19 push push changes to the specified destination
20 remove remove the specified files on the next commit
20 remove remove the specified files on the next commit
21 serve start stand-alone webserver
21 serve start stand-alone webserver
22 status show changed files in the working directory
22 status show changed files in the working directory
23 summary summarize working directory state
23 summary summarize working directory state
24 update update working directory (or switch revisions)
24 update update working directory (or switch revisions)
25
25
26 (use 'hg help' for the full list of commands or 'hg -v' for details)
26 (use 'hg help' for the full list of commands or 'hg -v' for details)
27
27
28 $ hg -q
28 $ hg -q
29 add add the specified files on the next commit
29 add add the specified files on the next commit
30 annotate show changeset information by line for each file
30 annotate show changeset information by line for each file
31 clone make a copy of an existing repository
31 clone make a copy of an existing repository
32 commit commit the specified files or all outstanding changes
32 commit commit the specified files or all outstanding changes
33 diff diff repository (or selected files)
33 diff diff repository (or selected files)
34 export dump the header and diffs for one or more changesets
34 export dump the header and diffs for one or more changesets
35 forget forget the specified files on the next commit
35 forget forget the specified files on the next commit
36 init create a new repository in the given directory
36 init create a new repository in the given directory
37 log show revision history of entire repository or files
37 log show revision history of entire repository or files
38 merge merge another revision into working directory
38 merge merge another revision into working directory
39 pull pull changes from the specified source
39 pull pull changes from the specified source
40 push push changes to the specified destination
40 push push changes to the specified destination
41 remove remove the specified files on the next commit
41 remove remove the specified files on the next commit
42 serve start stand-alone webserver
42 serve start stand-alone webserver
43 status show changed files in the working directory
43 status show changed files in the working directory
44 summary summarize working directory state
44 summary summarize working directory state
45 update update working directory (or switch revisions)
45 update update working directory (or switch revisions)
46
46
47 Extra extensions will be printed in help output in a non-reliable order since
47 Extra extensions will be printed in help output in a non-reliable order since
48 the extension is unknown.
48 the extension is unknown.
49 #if no-extraextensions
49 #if no-extraextensions
50
50
51 $ hg help
51 $ hg help
52 Mercurial Distributed SCM
52 Mercurial Distributed SCM
53
53
54 list of commands:
54 list of commands:
55
55
56 Repository creation:
56 Repository creation:
57
57
58 clone make a copy of an existing repository
58 clone make a copy of an existing repository
59 init create a new repository in the given directory
59 init create a new repository in the given directory
60
60
61 Remote repository management:
61 Remote repository management:
62
62
63 incoming show new changesets found in source
63 incoming show new changesets found in source
64 outgoing show changesets not found in the destination
64 outgoing show changesets not found in the destination
65 paths show aliases for remote repositories
65 paths show aliases for remote repositories
66 pull pull changes from the specified source
66 pull pull changes from the specified source
67 push push changes to the specified destination
67 push push changes to the specified destination
68 serve start stand-alone webserver
68 serve start stand-alone webserver
69
69
70 Change creation:
70 Change creation:
71
71
72 commit commit the specified files or all outstanding changes
72 commit commit the specified files or all outstanding changes
73
73
74 Change manipulation:
74 Change manipulation:
75
75
76 backout reverse effect of earlier changeset
76 backout reverse effect of earlier changeset
77 graft copy changes from other branches onto the current branch
77 graft copy changes from other branches onto the current branch
78 merge merge another revision into working directory
78 merge merge another revision into working directory
79
79
80 Change organization:
80 Change organization:
81
81
82 bookmarks create a new bookmark or list existing bookmarks
82 bookmarks create a new bookmark or list existing bookmarks
83 branch set or show the current branch name
83 branch set or show the current branch name
84 branches list repository named branches
84 branches list repository named branches
85 phase set or show the current phase name
85 phase set or show the current phase name
86 tag add one or more tags for the current or given revision
86 tag add one or more tags for the current or given revision
87 tags list repository tags
87 tags list repository tags
88
88
89 File content management:
89 File content management:
90
90
91 annotate show changeset information by line for each file
91 annotate show changeset information by line for each file
92 cat output the current or given revision of files
92 cat output the current or given revision of files
93 copy mark files as copied for the next commit
93 copy mark files as copied for the next commit
94 diff diff repository (or selected files)
94 diff diff repository (or selected files)
95 grep search for a pattern in specified files
95 grep search for a pattern in specified files
96
96
97 Change navigation:
97 Change navigation:
98
98
99 bisect subdivision search of changesets
99 bisect subdivision search of changesets
100 heads show branch heads
100 heads show branch heads
101 identify identify the working directory or specified revision
101 identify identify the working directory or specified revision
102 log show revision history of entire repository or files
102 log show revision history of entire repository or files
103
103
104 Working directory management:
104 Working directory management:
105
105
106 add add the specified files on the next commit
106 add add the specified files on the next commit
107 addremove add all new files, delete all missing files
107 addremove add all new files, delete all missing files
108 files list tracked files
108 files list tracked files
109 forget forget the specified files on the next commit
109 forget forget the specified files on the next commit
110 purge removes files not tracked by Mercurial
110 purge removes files not tracked by Mercurial
111 remove remove the specified files on the next commit
111 remove remove the specified files on the next commit
112 rename rename files; equivalent of copy + remove
112 rename rename files; equivalent of copy + remove
113 resolve redo merges or set/view the merge status of files
113 resolve redo merges or set/view the merge status of files
114 revert restore files to their checkout state
114 revert restore files to their checkout state
115 root print the root (top) of the current working directory
115 root print the root (top) of the current working directory
116 shelve save and set aside changes from the working directory
116 shelve save and set aside changes from the working directory
117 status show changed files in the working directory
117 status show changed files in the working directory
118 summary summarize working directory state
118 summary summarize working directory state
119 unshelve restore a shelved change to the working directory
119 unshelve restore a shelved change to the working directory
120 update update working directory (or switch revisions)
120 update update working directory (or switch revisions)
121
121
122 Change import/export:
122 Change import/export:
123
123
124 archive create an unversioned archive of a repository revision
124 archive create an unversioned archive of a repository revision
125 bundle create a bundle file
125 bundle create a bundle file
126 export dump the header and diffs for one or more changesets
126 export dump the header and diffs for one or more changesets
127 import import an ordered set of patches
127 import import an ordered set of patches
128 unbundle apply one or more bundle files
128 unbundle apply one or more bundle files
129
129
130 Repository maintenance:
130 Repository maintenance:
131
131
132 manifest output the current or given revision of the project manifest
132 manifest output the current or given revision of the project manifest
133 recover roll back an interrupted transaction
133 recover roll back an interrupted transaction
134 verify verify the integrity of the repository
134 verify verify the integrity of the repository
135
135
136 Help:
136 Help:
137
137
138 config show combined config settings from all hgrc files
138 config show combined config settings from all hgrc files
139 help show help for a given topic or a help overview
139 help show help for a given topic or a help overview
140 version output version and copyright information
140 version output version and copyright information
141
141
142 additional help topics:
142 additional help topics:
143
143
144 Mercurial identifiers:
144 Mercurial identifiers:
145
145
146 filesets Specifying File Sets
146 filesets Specifying File Sets
147 hgignore Syntax for Mercurial Ignore Files
147 hgignore Syntax for Mercurial Ignore Files
148 patterns File Name Patterns
148 patterns File Name Patterns
149 revisions Specifying Revisions
149 revisions Specifying Revisions
150 urls URL Paths
150 urls URL Paths
151
151
152 Mercurial output:
152 Mercurial output:
153
153
154 color Colorizing Outputs
154 color Colorizing Outputs
155 dates Date Formats
155 dates Date Formats
156 diffs Diff Formats
156 diffs Diff Formats
157 templating Template Usage
157 templating Template Usage
158
158
159 Mercurial configuration:
159 Mercurial configuration:
160
160
161 config Configuration Files
161 config Configuration Files
162 environment Environment Variables
162 environment Environment Variables
163 extensions Using Additional Features
163 extensions Using Additional Features
164 flags Command-line flags
164 flags Command-line flags
165 hgweb Configuring hgweb
165 hgweb Configuring hgweb
166 merge-tools Merge Tools
166 merge-tools Merge Tools
167 pager Pager Support
167 pager Pager Support
168 rust Rust in Mercurial
168 rust Rust in Mercurial
169
169
170 Concepts:
170 Concepts:
171
171
172 bundlespec Bundle File Formats
172 bundlespec Bundle File Formats
173 evolution Safely rewriting history (EXPERIMENTAL)
173 evolution Safely rewriting history (EXPERIMENTAL)
174 glossary Glossary
174 glossary Glossary
175 phases Working with Phases
175 phases Working with Phases
176 subrepos Subrepositories
176 subrepos Subrepositories
177
177
178 Miscellaneous:
178 Miscellaneous:
179
179
180 deprecated Deprecated Features
180 deprecated Deprecated Features
181 internals Technical implementation topics
181 internals Technical implementation topics
182 scripting Using Mercurial from scripts and automation
182 scripting Using Mercurial from scripts and automation
183
183
184 (use 'hg help -v' to show built-in aliases and global options)
184 (use 'hg help -v' to show built-in aliases and global options)
185
185
186 $ hg -q help
186 $ hg -q help
187 Repository creation:
187 Repository creation:
188
188
189 clone make a copy of an existing repository
189 clone make a copy of an existing repository
190 init create a new repository in the given directory
190 init create a new repository in the given directory
191
191
192 Remote repository management:
192 Remote repository management:
193
193
194 incoming show new changesets found in source
194 incoming show new changesets found in source
195 outgoing show changesets not found in the destination
195 outgoing show changesets not found in the destination
196 paths show aliases for remote repositories
196 paths show aliases for remote repositories
197 pull pull changes from the specified source
197 pull pull changes from the specified source
198 push push changes to the specified destination
198 push push changes to the specified destination
199 serve start stand-alone webserver
199 serve start stand-alone webserver
200
200
201 Change creation:
201 Change creation:
202
202
203 commit commit the specified files or all outstanding changes
203 commit commit the specified files or all outstanding changes
204
204
205 Change manipulation:
205 Change manipulation:
206
206
207 backout reverse effect of earlier changeset
207 backout reverse effect of earlier changeset
208 graft copy changes from other branches onto the current branch
208 graft copy changes from other branches onto the current branch
209 merge merge another revision into working directory
209 merge merge another revision into working directory
210
210
211 Change organization:
211 Change organization:
212
212
213 bookmarks create a new bookmark or list existing bookmarks
213 bookmarks create a new bookmark or list existing bookmarks
214 branch set or show the current branch name
214 branch set or show the current branch name
215 branches list repository named branches
215 branches list repository named branches
216 phase set or show the current phase name
216 phase set or show the current phase name
217 tag add one or more tags for the current or given revision
217 tag add one or more tags for the current or given revision
218 tags list repository tags
218 tags list repository tags
219
219
220 File content management:
220 File content management:
221
221
222 annotate show changeset information by line for each file
222 annotate show changeset information by line for each file
223 cat output the current or given revision of files
223 cat output the current or given revision of files
224 copy mark files as copied for the next commit
224 copy mark files as copied for the next commit
225 diff diff repository (or selected files)
225 diff diff repository (or selected files)
226 grep search for a pattern in specified files
226 grep search for a pattern in specified files
227
227
228 Change navigation:
228 Change navigation:
229
229
230 bisect subdivision search of changesets
230 bisect subdivision search of changesets
231 heads show branch heads
231 heads show branch heads
232 identify identify the working directory or specified revision
232 identify identify the working directory or specified revision
233 log show revision history of entire repository or files
233 log show revision history of entire repository or files
234
234
235 Working directory management:
235 Working directory management:
236
236
237 add add the specified files on the next commit
237 add add the specified files on the next commit
238 addremove add all new files, delete all missing files
238 addremove add all new files, delete all missing files
239 files list tracked files
239 files list tracked files
240 forget forget the specified files on the next commit
240 forget forget the specified files on the next commit
241 purge removes files not tracked by Mercurial
241 purge removes files not tracked by Mercurial
242 remove remove the specified files on the next commit
242 remove remove the specified files on the next commit
243 rename rename files; equivalent of copy + remove
243 rename rename files; equivalent of copy + remove
244 resolve redo merges or set/view the merge status of files
244 resolve redo merges or set/view the merge status of files
245 revert restore files to their checkout state
245 revert restore files to their checkout state
246 root print the root (top) of the current working directory
246 root print the root (top) of the current working directory
247 shelve save and set aside changes from the working directory
247 shelve save and set aside changes from the working directory
248 status show changed files in the working directory
248 status show changed files in the working directory
249 summary summarize working directory state
249 summary summarize working directory state
250 unshelve restore a shelved change to the working directory
250 unshelve restore a shelved change to the working directory
251 update update working directory (or switch revisions)
251 update update working directory (or switch revisions)
252
252
253 Change import/export:
253 Change import/export:
254
254
255 archive create an unversioned archive of a repository revision
255 archive create an unversioned archive of a repository revision
256 bundle create a bundle file
256 bundle create a bundle file
257 export dump the header and diffs for one or more changesets
257 export dump the header and diffs for one or more changesets
258 import import an ordered set of patches
258 import import an ordered set of patches
259 unbundle apply one or more bundle files
259 unbundle apply one or more bundle files
260
260
261 Repository maintenance:
261 Repository maintenance:
262
262
263 manifest output the current or given revision of the project manifest
263 manifest output the current or given revision of the project manifest
264 recover roll back an interrupted transaction
264 recover roll back an interrupted transaction
265 verify verify the integrity of the repository
265 verify verify the integrity of the repository
266
266
267 Help:
267 Help:
268
268
269 config show combined config settings from all hgrc files
269 config show combined config settings from all hgrc files
270 help show help for a given topic or a help overview
270 help show help for a given topic or a help overview
271 version output version and copyright information
271 version output version and copyright information
272
272
273 additional help topics:
273 additional help topics:
274
274
275 Mercurial identifiers:
275 Mercurial identifiers:
276
276
277 filesets Specifying File Sets
277 filesets Specifying File Sets
278 hgignore Syntax for Mercurial Ignore Files
278 hgignore Syntax for Mercurial Ignore Files
279 patterns File Name Patterns
279 patterns File Name Patterns
280 revisions Specifying Revisions
280 revisions Specifying Revisions
281 urls URL Paths
281 urls URL Paths
282
282
283 Mercurial output:
283 Mercurial output:
284
284
285 color Colorizing Outputs
285 color Colorizing Outputs
286 dates Date Formats
286 dates Date Formats
287 diffs Diff Formats
287 diffs Diff Formats
288 templating Template Usage
288 templating Template Usage
289
289
290 Mercurial configuration:
290 Mercurial configuration:
291
291
292 config Configuration Files
292 config Configuration Files
293 environment Environment Variables
293 environment Environment Variables
294 extensions Using Additional Features
294 extensions Using Additional Features
295 flags Command-line flags
295 flags Command-line flags
296 hgweb Configuring hgweb
296 hgweb Configuring hgweb
297 merge-tools Merge Tools
297 merge-tools Merge Tools
298 pager Pager Support
298 pager Pager Support
299 rust Rust in Mercurial
299 rust Rust in Mercurial
300
300
301 Concepts:
301 Concepts:
302
302
303 bundlespec Bundle File Formats
303 bundlespec Bundle File Formats
304 evolution Safely rewriting history (EXPERIMENTAL)
304 evolution Safely rewriting history (EXPERIMENTAL)
305 glossary Glossary
305 glossary Glossary
306 phases Working with Phases
306 phases Working with Phases
307 subrepos Subrepositories
307 subrepos Subrepositories
308
308
309 Miscellaneous:
309 Miscellaneous:
310
310
311 deprecated Deprecated Features
311 deprecated Deprecated Features
312 internals Technical implementation topics
312 internals Technical implementation topics
313 scripting Using Mercurial from scripts and automation
313 scripting Using Mercurial from scripts and automation
314
314
315 Test extension help:
315 Test extension help:
316 $ hg help extensions --config extensions.rebase= --config extensions.children=
316 $ hg help extensions --config extensions.rebase= --config extensions.children=
317 Using Additional Features
317 Using Additional Features
318 """""""""""""""""""""""""
318 """""""""""""""""""""""""
319
319
320 Mercurial has the ability to add new features through the use of
320 Mercurial has the ability to add new features through the use of
321 extensions. Extensions may add new commands, add options to existing
321 extensions. Extensions may add new commands, add options to existing
322 commands, change the default behavior of commands, or implement hooks.
322 commands, change the default behavior of commands, or implement hooks.
323
323
324 To enable the "foo" extension, either shipped with Mercurial or in the
324 To enable the "foo" extension, either shipped with Mercurial or in the
325 Python search path, create an entry for it in your configuration file,
325 Python search path, create an entry for it in your configuration file,
326 like this:
326 like this:
327
327
328 [extensions]
328 [extensions]
329 foo =
329 foo =
330
330
331 You may also specify the full path to an extension:
331 You may also specify the full path to an extension:
332
332
333 [extensions]
333 [extensions]
334 myfeature = ~/.hgext/myfeature.py
334 myfeature = ~/.hgext/myfeature.py
335
335
336 See 'hg help config' for more information on configuration files.
336 See 'hg help config' for more information on configuration files.
337
337
338 Extensions are not loaded by default for a variety of reasons: they can
338 Extensions are not loaded by default for a variety of reasons: they can
339 increase startup overhead; they may be meant for advanced usage only; they
339 increase startup overhead; they may be meant for advanced usage only; they
340 may provide potentially dangerous abilities (such as letting you destroy
340 may provide potentially dangerous abilities (such as letting you destroy
341 or modify history); they might not be ready for prime time; or they may
341 or modify history); they might not be ready for prime time; or they may
342 alter some usual behaviors of stock Mercurial. It is thus up to the user
342 alter some usual behaviors of stock Mercurial. It is thus up to the user
343 to activate extensions as needed.
343 to activate extensions as needed.
344
344
345 To explicitly disable an extension enabled in a configuration file of
345 To explicitly disable an extension enabled in a configuration file of
346 broader scope, prepend its path with !:
346 broader scope, prepend its path with !:
347
347
348 [extensions]
348 [extensions]
349 # disabling extension bar residing in /path/to/extension/bar.py
349 # disabling extension bar residing in /path/to/extension/bar.py
350 bar = !/path/to/extension/bar.py
350 bar = !/path/to/extension/bar.py
351 # ditto, but no path was supplied for extension baz
351 # ditto, but no path was supplied for extension baz
352 baz = !
352 baz = !
353
353
354 enabled extensions:
354 enabled extensions:
355
355
356 children command to display child changesets (DEPRECATED)
356 children command to display child changesets (DEPRECATED)
357 rebase command to move sets of revisions to a different ancestor
357 rebase command to move sets of revisions to a different ancestor
358
358
359 disabled extensions:
359 disabled extensions:
360
360
361 acl hooks for controlling repository access
361 acl hooks for controlling repository access
362 blackbox log repository events to a blackbox for debugging
362 blackbox log repository events to a blackbox for debugging
363 bugzilla hooks for integrating with the Bugzilla bug tracker
363 bugzilla hooks for integrating with the Bugzilla bug tracker
364 censor erase file content at a given revision
364 censor erase file content at a given revision
365 churn command to display statistics about repository history
365 churn command to display statistics about repository history
366 clonebundles advertise pre-generated bundles to seed clones
366 clonebundles advertise pre-generated bundles to seed clones
367 closehead close arbitrary heads without checking them out first
367 closehead close arbitrary heads without checking them out first
368 convert import revisions from foreign VCS repositories into
368 convert import revisions from foreign VCS repositories into
369 Mercurial
369 Mercurial
370 eol automatically manage newlines in repository files
370 eol automatically manage newlines in repository files
371 extdiff command to allow external programs to compare revisions
371 extdiff command to allow external programs to compare revisions
372 factotum http authentication with factotum
372 factotum http authentication with factotum
373 fastexport export repositories as git fast-import stream
373 fastexport export repositories as git fast-import stream
374 githelp try mapping git commands to Mercurial commands
374 githelp try mapping git commands to Mercurial commands
375 gpg commands to sign and verify changesets
375 gpg commands to sign and verify changesets
376 hgk browse the repository in a graphical way
376 hgk browse the repository in a graphical way
377 highlight syntax highlighting for hgweb (requires Pygments)
377 highlight syntax highlighting for hgweb (requires Pygments)
378 histedit interactive history editing
378 histedit interactive history editing
379 keyword expand keywords in tracked files
379 keyword expand keywords in tracked files
380 largefiles track large binary files
380 largefiles track large binary files
381 mq manage a stack of patches
381 mq manage a stack of patches
382 notify hooks for sending email push notifications
382 notify hooks for sending email push notifications
383 patchbomb command to send changesets as (a series of) patch emails
383 patchbomb command to send changesets as (a series of) patch emails
384 relink recreates hardlinks between repository clones
384 relink recreates hardlinks between repository clones
385 schemes extend schemes with shortcuts to repository swarms
385 schemes extend schemes with shortcuts to repository swarms
386 share share a common history between several working directories
386 share share a common history between several working directories
387 transplant command to transplant changesets from another branch
387 transplant command to transplant changesets from another branch
388 win32mbcs allow the use of MBCS paths with problematic encodings
388 win32mbcs allow the use of MBCS paths with problematic encodings
389 zeroconf discover and advertise repositories on the local network
389 zeroconf discover and advertise repositories on the local network
390
390
391 #endif
391 #endif
392
392
393 Verify that deprecated extensions are included if --verbose:
393 Verify that deprecated extensions are included if --verbose:
394
394
395 $ hg -v help extensions | grep children
395 $ hg -v help extensions | grep children
396 children command to display child changesets (DEPRECATED)
396 children command to display child changesets (DEPRECATED)
397
397
398 Verify that extension keywords appear in help templates
398 Verify that extension keywords appear in help templates
399
399
400 $ hg help --config extensions.transplant= templating|grep transplant > /dev/null
400 $ hg help --config extensions.transplant= templating|grep transplant > /dev/null
401
401
402 Test short command list with verbose option
402 Test short command list with verbose option
403
403
404 $ hg -v help shortlist
404 $ hg -v help shortlist
405 Mercurial Distributed SCM
405 Mercurial Distributed SCM
406
406
407 basic commands:
407 basic commands:
408
408
409 abort abort an unfinished operation (EXPERIMENTAL)
409 abort abort an unfinished operation (EXPERIMENTAL)
410 add add the specified files on the next commit
410 add add the specified files on the next commit
411 annotate, blame
411 annotate, blame
412 show changeset information by line for each file
412 show changeset information by line for each file
413 clone make a copy of an existing repository
413 clone make a copy of an existing repository
414 commit, ci commit the specified files or all outstanding changes
414 commit, ci commit the specified files or all outstanding changes
415 continue resumes an interrupted operation (EXPERIMENTAL)
415 continue resumes an interrupted operation (EXPERIMENTAL)
416 diff diff repository (or selected files)
416 diff diff repository (or selected files)
417 export dump the header and diffs for one or more changesets
417 export dump the header and diffs for one or more changesets
418 forget forget the specified files on the next commit
418 forget forget the specified files on the next commit
419 init create a new repository in the given directory
419 init create a new repository in the given directory
420 log, history show revision history of entire repository or files
420 log, history show revision history of entire repository or files
421 merge merge another revision into working directory
421 merge merge another revision into working directory
422 pull pull changes from the specified source
422 pull pull changes from the specified source
423 push push changes to the specified destination
423 push push changes to the specified destination
424 remove, rm remove the specified files on the next commit
424 remove, rm remove the specified files on the next commit
425 serve start stand-alone webserver
425 serve start stand-alone webserver
426 status, st show changed files in the working directory
426 status, st show changed files in the working directory
427 summary, sum summarize working directory state
427 summary, sum summarize working directory state
428 update, up, checkout, co
428 update, up, checkout, co
429 update working directory (or switch revisions)
429 update working directory (or switch revisions)
430
430
431 global options ([+] can be repeated):
431 global options ([+] can be repeated):
432
432
433 -R --repository REPO repository root directory or name of overlay bundle
433 -R --repository REPO repository root directory or name of overlay bundle
434 file
434 file
435 --cwd DIR change working directory
435 --cwd DIR change working directory
436 -y --noninteractive do not prompt, automatically pick the first choice for
436 -y --noninteractive do not prompt, automatically pick the first choice for
437 all prompts
437 all prompts
438 -q --quiet suppress output
438 -q --quiet suppress output
439 -v --verbose enable additional output
439 -v --verbose enable additional output
440 --color TYPE when to colorize (boolean, always, auto, never, or
440 --color TYPE when to colorize (boolean, always, auto, never, or
441 debug)
441 debug)
442 --config CONFIG [+] set/override config option (use 'section.name=value')
442 --config CONFIG [+] set/override config option (use 'section.name=value')
443 --debug enable debugging output
443 --debug enable debugging output
444 --debugger start debugger
444 --debugger start debugger
445 --encoding ENCODE set the charset encoding (default: ascii)
445 --encoding ENCODE set the charset encoding (default: ascii)
446 --encodingmode MODE set the charset encoding mode (default: strict)
446 --encodingmode MODE set the charset encoding mode (default: strict)
447 --traceback always print a traceback on exception
447 --traceback always print a traceback on exception
448 --time time how long the command takes
448 --time time how long the command takes
449 --profile print command execution profile
449 --profile print command execution profile
450 --version output version information and exit
450 --version output version information and exit
451 -h --help display help and exit
451 -h --help display help and exit
452 --hidden consider hidden changesets
452 --hidden consider hidden changesets
453 --pager TYPE when to paginate (boolean, always, auto, or never)
453 --pager TYPE when to paginate (boolean, always, auto, or never)
454 (default: auto)
454 (default: auto)
455
455
456 (use 'hg help' for the full list of commands)
456 (use 'hg help' for the full list of commands)
457
457
458 $ hg add -h
458 $ hg add -h
459 hg add [OPTION]... [FILE]...
459 hg add [OPTION]... [FILE]...
460
460
461 add the specified files on the next commit
461 add the specified files on the next commit
462
462
463 Schedule files to be version controlled and added to the repository.
463 Schedule files to be version controlled and added to the repository.
464
464
465 The files will be added to the repository at the next commit. To undo an
465 The files will be added to the repository at the next commit. To undo an
466 add before that, see 'hg forget'.
466 add before that, see 'hg forget'.
467
467
468 If no names are given, add all files to the repository (except files
468 If no names are given, add all files to the repository (except files
469 matching ".hgignore").
469 matching ".hgignore").
470
470
471 Returns 0 if all files are successfully added.
471 Returns 0 if all files are successfully added.
472
472
473 options ([+] can be repeated):
473 options ([+] can be repeated):
474
474
475 -I --include PATTERN [+] include names matching the given patterns
475 -I --include PATTERN [+] include names matching the given patterns
476 -X --exclude PATTERN [+] exclude names matching the given patterns
476 -X --exclude PATTERN [+] exclude names matching the given patterns
477 -S --subrepos recurse into subrepositories
477 -S --subrepos recurse into subrepositories
478 -n --dry-run do not perform actions, just print output
478 -n --dry-run do not perform actions, just print output
479
479
480 (some details hidden, use --verbose to show complete help)
480 (some details hidden, use --verbose to show complete help)
481
481
482 Verbose help for add
482 Verbose help for add
483
483
484 $ hg add -hv
484 $ hg add -hv
485 hg add [OPTION]... [FILE]...
485 hg add [OPTION]... [FILE]...
486
486
487 add the specified files on the next commit
487 add the specified files on the next commit
488
488
489 Schedule files to be version controlled and added to the repository.
489 Schedule files to be version controlled and added to the repository.
490
490
491 The files will be added to the repository at the next commit. To undo an
491 The files will be added to the repository at the next commit. To undo an
492 add before that, see 'hg forget'.
492 add before that, see 'hg forget'.
493
493
494 If no names are given, add all files to the repository (except files
494 If no names are given, add all files to the repository (except files
495 matching ".hgignore").
495 matching ".hgignore").
496
496
497 Examples:
497 Examples:
498
498
499 - New (unknown) files are added automatically by 'hg add':
499 - New (unknown) files are added automatically by 'hg add':
500
500
501 $ ls
501 $ ls
502 foo.c
502 foo.c
503 $ hg status
503 $ hg status
504 ? foo.c
504 ? foo.c
505 $ hg add
505 $ hg add
506 adding foo.c
506 adding foo.c
507 $ hg status
507 $ hg status
508 A foo.c
508 A foo.c
509
509
510 - Specific files to be added can be specified:
510 - Specific files to be added can be specified:
511
511
512 $ ls
512 $ ls
513 bar.c foo.c
513 bar.c foo.c
514 $ hg status
514 $ hg status
515 ? bar.c
515 ? bar.c
516 ? foo.c
516 ? foo.c
517 $ hg add bar.c
517 $ hg add bar.c
518 $ hg status
518 $ hg status
519 A bar.c
519 A bar.c
520 ? foo.c
520 ? foo.c
521
521
522 Returns 0 if all files are successfully added.
522 Returns 0 if all files are successfully added.
523
523
524 options ([+] can be repeated):
524 options ([+] can be repeated):
525
525
526 -I --include PATTERN [+] include names matching the given patterns
526 -I --include PATTERN [+] include names matching the given patterns
527 -X --exclude PATTERN [+] exclude names matching the given patterns
527 -X --exclude PATTERN [+] exclude names matching the given patterns
528 -S --subrepos recurse into subrepositories
528 -S --subrepos recurse into subrepositories
529 -n --dry-run do not perform actions, just print output
529 -n --dry-run do not perform actions, just print output
530
530
531 global options ([+] can be repeated):
531 global options ([+] can be repeated):
532
532
533 -R --repository REPO repository root directory or name of overlay bundle
533 -R --repository REPO repository root directory or name of overlay bundle
534 file
534 file
535 --cwd DIR change working directory
535 --cwd DIR change working directory
536 -y --noninteractive do not prompt, automatically pick the first choice for
536 -y --noninteractive do not prompt, automatically pick the first choice for
537 all prompts
537 all prompts
538 -q --quiet suppress output
538 -q --quiet suppress output
539 -v --verbose enable additional output
539 -v --verbose enable additional output
540 --color TYPE when to colorize (boolean, always, auto, never, or
540 --color TYPE when to colorize (boolean, always, auto, never, or
541 debug)
541 debug)
542 --config CONFIG [+] set/override config option (use 'section.name=value')
542 --config CONFIG [+] set/override config option (use 'section.name=value')
543 --debug enable debugging output
543 --debug enable debugging output
544 --debugger start debugger
544 --debugger start debugger
545 --encoding ENCODE set the charset encoding (default: ascii)
545 --encoding ENCODE set the charset encoding (default: ascii)
546 --encodingmode MODE set the charset encoding mode (default: strict)
546 --encodingmode MODE set the charset encoding mode (default: strict)
547 --traceback always print a traceback on exception
547 --traceback always print a traceback on exception
548 --time time how long the command takes
548 --time time how long the command takes
549 --profile print command execution profile
549 --profile print command execution profile
550 --version output version information and exit
550 --version output version information and exit
551 -h --help display help and exit
551 -h --help display help and exit
552 --hidden consider hidden changesets
552 --hidden consider hidden changesets
553 --pager TYPE when to paginate (boolean, always, auto, or never)
553 --pager TYPE when to paginate (boolean, always, auto, or never)
554 (default: auto)
554 (default: auto)
555
555
556 Test the textwidth config option
556 Test the textwidth config option
557
557
558 $ hg root -h --config ui.textwidth=50
558 $ hg root -h --config ui.textwidth=50
559 hg root
559 hg root
560
560
561 print the root (top) of the current working
561 print the root (top) of the current working
562 directory
562 directory
563
563
564 Print the root directory of the current
564 Print the root directory of the current
565 repository.
565 repository.
566
566
567 Returns 0 on success.
567 Returns 0 on success.
568
568
569 options:
569 options:
570
570
571 -T --template TEMPLATE display with template
571 -T --template TEMPLATE display with template
572
572
573 (some details hidden, use --verbose to show
573 (some details hidden, use --verbose to show
574 complete help)
574 complete help)
575
575
576 Test help option with version option
576 Test help option with version option
577
577
578 $ hg add -h --version
578 $ hg add -h --version
579 Mercurial Distributed SCM (version *) (glob)
579 Mercurial Distributed SCM (version *) (glob)
580 (see https://mercurial-scm.org for more information)
580 (see https://mercurial-scm.org for more information)
581
581
582 Copyright (C) 2005-* Olivia Mackall and others (glob)
582 Copyright (C) 2005-* Olivia Mackall and others (glob)
583 This is free software; see the source for copying conditions. There is NO
583 This is free software; see the source for copying conditions. There is NO
584 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
584 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
585
585
586 $ hg add --skjdfks
586 $ hg add --skjdfks
587 hg add: option --skjdfks not recognized
587 hg add: option --skjdfks not recognized
588 hg add [OPTION]... [FILE]...
588 hg add [OPTION]... [FILE]...
589
589
590 add the specified files on the next commit
590 add the specified files on the next commit
591
591
592 options ([+] can be repeated):
592 options ([+] can be repeated):
593
593
594 -I --include PATTERN [+] include names matching the given patterns
594 -I --include PATTERN [+] include names matching the given patterns
595 -X --exclude PATTERN [+] exclude names matching the given patterns
595 -X --exclude PATTERN [+] exclude names matching the given patterns
596 -S --subrepos recurse into subrepositories
596 -S --subrepos recurse into subrepositories
597 -n --dry-run do not perform actions, just print output
597 -n --dry-run do not perform actions, just print output
598
598
599 (use 'hg add -h' to show more help)
599 (use 'hg add -h' to show more help)
600 [10]
600 [10]
601
601
602 Test ambiguous command help
602 Test ambiguous command help
603
603
604 $ hg help ad
604 $ hg help ad
605 list of commands:
605 list of commands:
606
606
607 add add the specified files on the next commit
607 add add the specified files on the next commit
608 addremove add all new files, delete all missing files
608 addremove add all new files, delete all missing files
609
609
610 (use 'hg help -v ad' to show built-in aliases and global options)
610 (use 'hg help -v ad' to show built-in aliases and global options)
611
611
612 Test command without options
612 Test command without options
613
613
614 $ hg help verify
614 $ hg help verify
615 hg verify
615 hg verify
616
616
617 verify the integrity of the repository
617 verify the integrity of the repository
618
618
619 Verify the integrity of the current repository.
619 Verify the integrity of the current repository.
620
620
621 This will perform an extensive check of the repository's integrity,
621 This will perform an extensive check of the repository's integrity,
622 validating the hashes and checksums of each entry in the changelog,
622 validating the hashes and checksums of each entry in the changelog,
623 manifest, and tracked files, as well as the integrity of their crosslinks
623 manifest, and tracked files, as well as the integrity of their crosslinks
624 and indices.
624 and indices.
625
625
626 Please see https://mercurial-scm.org/wiki/RepositoryCorruption for more
626 Please see https://mercurial-scm.org/wiki/RepositoryCorruption for more
627 information about recovery from corruption of the repository.
627 information about recovery from corruption of the repository.
628
628
629 Returns 0 on success, 1 if errors are encountered.
629 Returns 0 on success, 1 if errors are encountered.
630
630
631 options:
631 options:
632
632
633 (some details hidden, use --verbose to show complete help)
633 (some details hidden, use --verbose to show complete help)
634
634
635 $ hg help diff
635 $ hg help diff
636 hg diff [OPTION]... ([-c REV] | [--from REV1] [--to REV2]) [FILE]...
636 hg diff [OPTION]... ([-c REV] | [--from REV1] [--to REV2]) [FILE]...
637
637
638 diff repository (or selected files)
638 diff repository (or selected files)
639
639
640 Show differences between revisions for the specified files.
640 Show differences between revisions for the specified files.
641
641
642 Differences between files are shown using the unified diff format.
642 Differences between files are shown using the unified diff format.
643
643
644 Note:
644 Note:
645 'hg diff' may generate unexpected results for merges, as it will
645 'hg diff' may generate unexpected results for merges, as it will
646 default to comparing against the working directory's first parent
646 default to comparing against the working directory's first parent
647 changeset if no revisions are specified. To diff against the conflict
647 changeset if no revisions are specified. To diff against the conflict
648 regions, you can use '--config diff.merge=yes'.
648 regions, you can use '--config diff.merge=yes'.
649
649
650 By default, the working directory files are compared to its first parent.
650 By default, the working directory files are compared to its first parent.
651 To see the differences from another revision, use --from. To see the
651 To see the differences from another revision, use --from. To see the
652 difference to another revision, use --to. For example, 'hg diff --from .^'
652 difference to another revision, use --to. For example, 'hg diff --from .^'
653 will show the differences from the working copy's grandparent to the
653 will show the differences from the working copy's grandparent to the
654 working copy, 'hg diff --to .' will show the diff from the working copy to
654 working copy, 'hg diff --to .' will show the diff from the working copy to
655 its parent (i.e. the reverse of the default), and 'hg diff --from 1.0 --to
655 its parent (i.e. the reverse of the default), and 'hg diff --from 1.0 --to
656 1.2' will show the diff between those two revisions.
656 1.2' will show the diff between those two revisions.
657
657
658 Alternatively you can specify -c/--change with a revision to see the
658 Alternatively you can specify -c/--change with a revision to see the
659 changes in that changeset relative to its first parent (i.e. 'hg diff -c
659 changes in that changeset relative to its first parent (i.e. 'hg diff -c
660 42' is equivalent to 'hg diff --from 42^ --to 42')
660 42' is equivalent to 'hg diff --from 42^ --to 42')
661
661
662 Without the -a/--text option, diff will avoid generating diffs of files it
662 Without the -a/--text option, diff will avoid generating diffs of files it
663 detects as binary. With -a, diff will generate a diff anyway, probably
663 detects as binary. With -a, diff will generate a diff anyway, probably
664 with undesirable results.
664 with undesirable results.
665
665
666 Use the -g/--git option to generate diffs in the git extended diff format.
666 Use the -g/--git option to generate diffs in the git extended diff format.
667 For more information, read 'hg help diffs'.
667 For more information, read 'hg help diffs'.
668
668
669 Returns 0 on success.
669 Returns 0 on success.
670
670
671 options ([+] can be repeated):
671 options ([+] can be repeated):
672
672
673 --from REV1 revision to diff from
673 --from REV1 revision to diff from
674 --to REV2 revision to diff to
674 --to REV2 revision to diff to
675 -c --change REV change made by revision
675 -c --change REV change made by revision
676 -a --text treat all files as text
676 -a --text treat all files as text
677 -g --git use git extended diff format
677 -g --git use git extended diff format
678 --binary generate binary diffs in git mode (default)
678 --binary generate binary diffs in git mode (default)
679 --nodates omit dates from diff headers
679 --nodates omit dates from diff headers
680 --noprefix omit a/ and b/ prefixes from filenames
680 --noprefix omit a/ and b/ prefixes from filenames
681 -p --show-function show which function each change is in
681 -p --show-function show which function each change is in
682 --reverse produce a diff that undoes the changes
682 --reverse produce a diff that undoes the changes
683 -w --ignore-all-space ignore white space when comparing lines
683 -w --ignore-all-space ignore white space when comparing lines
684 -b --ignore-space-change ignore changes in the amount of white space
684 -b --ignore-space-change ignore changes in the amount of white space
685 -B --ignore-blank-lines ignore changes whose lines are all blank
685 -B --ignore-blank-lines ignore changes whose lines are all blank
686 -Z --ignore-space-at-eol ignore changes in whitespace at EOL
686 -Z --ignore-space-at-eol ignore changes in whitespace at EOL
687 -U --unified NUM number of lines of context to show
687 -U --unified NUM number of lines of context to show
688 --stat output diffstat-style summary of changes
688 --stat output diffstat-style summary of changes
689 --root DIR produce diffs relative to subdirectory
689 --root DIR produce diffs relative to subdirectory
690 -I --include PATTERN [+] include names matching the given patterns
690 -I --include PATTERN [+] include names matching the given patterns
691 -X --exclude PATTERN [+] exclude names matching the given patterns
691 -X --exclude PATTERN [+] exclude names matching the given patterns
692 -S --subrepos recurse into subrepositories
692 -S --subrepos recurse into subrepositories
693
693
694 (some details hidden, use --verbose to show complete help)
694 (some details hidden, use --verbose to show complete help)
695
695
696 $ hg help status
696 $ hg help status
697 hg status [OPTION]... [FILE]...
697 hg status [OPTION]... [FILE]...
698
698
699 aliases: st
699 aliases: st
700
700
701 show changed files in the working directory
701 show changed files in the working directory
702
702
703 Show status of files in the repository. If names are given, only files
703 Show status of files in the repository. If names are given, only files
704 that match are shown. Files that are clean or ignored or the source of a
704 that match are shown. Files that are clean or ignored or the source of a
705 copy/move operation, are not listed unless -c/--clean, -i/--ignored,
705 copy/move operation, are not listed unless -c/--clean, -i/--ignored,
706 -C/--copies or -A/--all are given. Unless options described with "show
706 -C/--copies or -A/--all are given. Unless options described with "show
707 only ..." are given, the options -mardu are used.
707 only ..." are given, the options -mardu are used.
708
708
709 Option -q/--quiet hides untracked (unknown and ignored) files unless
709 Option -q/--quiet hides untracked (unknown and ignored) files unless
710 explicitly requested with -u/--unknown or -i/--ignored.
710 explicitly requested with -u/--unknown or -i/--ignored.
711
711
712 Note:
712 Note:
713 'hg status' may appear to disagree with diff if permissions have
713 'hg status' may appear to disagree with diff if permissions have
714 changed or a merge has occurred. The standard diff format does not
714 changed or a merge has occurred. The standard diff format does not
715 report permission changes and diff only reports changes relative to one
715 report permission changes and diff only reports changes relative to one
716 merge parent.
716 merge parent.
717
717
718 If one revision is given, it is used as the base revision. If two
718 If one revision is given, it is used as the base revision. If two
719 revisions are given, the differences between them are shown. The --change
719 revisions are given, the differences between them are shown. The --change
720 option can also be used as a shortcut to list the changed files of a
720 option can also be used as a shortcut to list the changed files of a
721 revision from its first parent.
721 revision from its first parent.
722
722
723 The codes used to show the status of files are:
723 The codes used to show the status of files are:
724
724
725 M = modified
725 M = modified
726 A = added
726 A = added
727 R = removed
727 R = removed
728 C = clean
728 C = clean
729 ! = missing (deleted by non-hg command, but still tracked)
729 ! = missing (deleted by non-hg command, but still tracked)
730 ? = not tracked
730 ? = not tracked
731 I = ignored
731 I = ignored
732 = origin of the previous file (with --copies)
732 = origin of the previous file (with --copies)
733
733
734 Returns 0 on success.
734 Returns 0 on success.
735
735
736 options ([+] can be repeated):
736 options ([+] can be repeated):
737
737
738 -A --all show status of all files
738 -A --all show status of all files
739 -m --modified show only modified files
739 -m --modified show only modified files
740 -a --added show only added files
740 -a --added show only added files
741 -r --removed show only removed files
741 -r --removed show only removed files
742 -d --deleted show only missing files
742 -d --deleted show only missing files
743 -c --clean show only files without changes
743 -c --clean show only files without changes
744 -u --unknown show only unknown (not tracked) files
744 -u --unknown show only unknown (not tracked) files
745 -i --ignored show only ignored files
745 -i --ignored show only ignored files
746 -n --no-status hide status prefix
746 -n --no-status hide status prefix
747 -C --copies show source of copied files
747 -C --copies show source of copied files
748 -0 --print0 end filenames with NUL, for use with xargs
748 -0 --print0 end filenames with NUL, for use with xargs
749 --rev REV [+] show difference from revision
749 --rev REV [+] show difference from revision
750 --change REV list the changed files of a revision
750 --change REV list the changed files of a revision
751 -I --include PATTERN [+] include names matching the given patterns
751 -I --include PATTERN [+] include names matching the given patterns
752 -X --exclude PATTERN [+] exclude names matching the given patterns
752 -X --exclude PATTERN [+] exclude names matching the given patterns
753 -S --subrepos recurse into subrepositories
753 -S --subrepos recurse into subrepositories
754 -T --template TEMPLATE display with template
754 -T --template TEMPLATE display with template
755
755
756 (some details hidden, use --verbose to show complete help)
756 (some details hidden, use --verbose to show complete help)
757
757
758 $ hg -q help status
758 $ hg -q help status
759 hg status [OPTION]... [FILE]...
759 hg status [OPTION]... [FILE]...
760
760
761 show changed files in the working directory
761 show changed files in the working directory
762
762
763 $ hg help foo
763 $ hg help foo
764 abort: no such help topic: foo
764 abort: no such help topic: foo
765 (try 'hg help --keyword foo')
765 (try 'hg help --keyword foo')
766 [10]
766 [10]
767
767
768 $ hg skjdfks
768 $ hg skjdfks
769 hg: unknown command 'skjdfks'
769 hg: unknown command 'skjdfks'
770 (use 'hg help' for a list of commands)
770 (use 'hg help' for a list of commands)
771 [10]
771 [10]
772
772
773 Typoed command gives suggestion
773 Typoed command gives suggestion
774 $ hg puls
774 $ hg puls
775 hg: unknown command 'puls'
775 hg: unknown command 'puls'
776 (did you mean one of pull, push?)
776 (did you mean one of pull, push?)
777 [10]
777 [10]
778
778
779 Not enabled extension gets suggested
779 Not enabled extension gets suggested
780
780
781 $ hg rebase
781 $ hg rebase
782 hg: unknown command 'rebase'
782 hg: unknown command 'rebase'
783 'rebase' is provided by the following extension:
783 'rebase' is provided by the following extension:
784
784
785 rebase command to move sets of revisions to a different ancestor
785 rebase command to move sets of revisions to a different ancestor
786
786
787 (use 'hg help extensions' for information on enabling extensions)
787 (use 'hg help extensions' for information on enabling extensions)
788 [10]
788 [10]
789
789
790 Disabled extension gets suggested
790 Disabled extension gets suggested
791 $ hg --config extensions.rebase=! rebase
791 $ hg --config extensions.rebase=! rebase
792 hg: unknown command 'rebase'
792 hg: unknown command 'rebase'
793 'rebase' is provided by the following extension:
793 'rebase' is provided by the following extension:
794
794
795 rebase command to move sets of revisions to a different ancestor
795 rebase command to move sets of revisions to a different ancestor
796
796
797 (use 'hg help extensions' for information on enabling extensions)
797 (use 'hg help extensions' for information on enabling extensions)
798 [10]
798 [10]
799
799
800 Checking that help adapts based on the config:
800 Checking that help adapts based on the config:
801
801
802 $ hg help diff --config ui.tweakdefaults=true | egrep -e '^ *(-g|config)'
802 $ hg help diff --config ui.tweakdefaults=true | egrep -e '^ *(-g|config)'
803 -g --[no-]git use git extended diff format (default: on from
803 -g --[no-]git use git extended diff format (default: on from
804 config)
804 config)
805
805
806 Make sure that we don't run afoul of the help system thinking that
806 Make sure that we don't run afoul of the help system thinking that
807 this is a section and erroring out weirdly.
807 this is a section and erroring out weirdly.
808
808
809 $ hg .log
809 $ hg .log
810 hg: unknown command '.log'
810 hg: unknown command '.log'
811 (did you mean log?)
811 (did you mean log?)
812 [10]
812 [10]
813
813
814 $ hg log.
814 $ hg log.
815 hg: unknown command 'log.'
815 hg: unknown command 'log.'
816 (did you mean log?)
816 (did you mean log?)
817 [10]
817 [10]
818 $ hg pu.lh
818 $ hg pu.lh
819 hg: unknown command 'pu.lh'
819 hg: unknown command 'pu.lh'
820 (did you mean one of pull, push?)
820 (did you mean one of pull, push?)
821 [10]
821 [10]
822
822
823 $ cat > helpext.py <<EOF
823 $ cat > helpext.py <<EOF
824 > import os
824 > import os
825 > from mercurial import commands, fancyopts, registrar
825 > from mercurial import commands, fancyopts, registrar
826 >
826 >
827 > def func(arg):
827 > def func(arg):
828 > return '%sfoo' % arg
828 > return '%sfoo' % arg
829 > class customopt(fancyopts.customopt):
829 > class customopt(fancyopts.customopt):
830 > def newstate(self, oldstate, newparam, abort):
830 > def newstate(self, oldstate, newparam, abort):
831 > return '%sbar' % oldstate
831 > return '%sbar' % oldstate
832 > cmdtable = {}
832 > cmdtable = {}
833 > command = registrar.command(cmdtable)
833 > command = registrar.command(cmdtable)
834 >
834 >
835 > @command(b'nohelp',
835 > @command(b'nohelp',
836 > [(b'', b'longdesc', 3, b'x'*67),
836 > [(b'', b'longdesc', 3, b'x'*67),
837 > (b'n', b'', None, b'normal desc'),
837 > (b'n', b'', None, b'normal desc'),
838 > (b'', b'newline', b'', b'line1\nline2'),
838 > (b'', b'newline', b'', b'line1\nline2'),
839 > (b'', b'default-off', False, b'enable X'),
839 > (b'', b'default-off', False, b'enable X'),
840 > (b'', b'default-on', True, b'enable Y'),
840 > (b'', b'default-on', True, b'enable Y'),
841 > (b'', b'callableopt', func, b'adds foo'),
841 > (b'', b'callableopt', func, b'adds foo'),
842 > (b'', b'customopt', customopt(''), b'adds bar'),
842 > (b'', b'customopt', customopt(''), b'adds bar'),
843 > (b'', b'customopt-withdefault', customopt('foo'), b'adds bar')],
843 > (b'', b'customopt-withdefault', customopt('foo'), b'adds bar')],
844 > b'hg nohelp',
844 > b'hg nohelp',
845 > norepo=True)
845 > norepo=True)
846 > @command(b'debugoptADV', [(b'', b'aopt', None, b'option is (ADVANCED)')])
846 > @command(b'debugoptADV', [(b'', b'aopt', None, b'option is (ADVANCED)')])
847 > @command(b'debugoptDEP', [(b'', b'dopt', None, b'option is (DEPRECATED)')])
847 > @command(b'debugoptDEP', [(b'', b'dopt', None, b'option is (DEPRECATED)')])
848 > @command(b'debugoptEXP', [(b'', b'eopt', None, b'option is (EXPERIMENTAL)')])
848 > @command(b'debugoptEXP', [(b'', b'eopt', None, b'option is (EXPERIMENTAL)')])
849 > def nohelp(ui, *args, **kwargs):
849 > def nohelp(ui, *args, **kwargs):
850 > pass
850 > pass
851 >
851 >
852 > @command(b'hashelp', [], b'hg hashelp', norepo=True)
852 > @command(b'hashelp', [], b'hg hashelp', norepo=True)
853 > def hashelp(ui, *args, **kwargs):
853 > def hashelp(ui, *args, **kwargs):
854 > """Extension command's help"""
854 > """Extension command's help"""
855 >
855 >
856 > def uisetup(ui):
856 > def uisetup(ui):
857 > ui.setconfig(b'alias', b'shellalias', b'!echo hi', b'helpext')
857 > ui.setconfig(b'alias', b'shellalias', b'!echo hi', b'helpext')
858 > ui.setconfig(b'alias', b'hgalias', b'summary', b'helpext')
858 > ui.setconfig(b'alias', b'hgalias', b'summary', b'helpext')
859 > ui.setconfig(b'alias', b'hgalias:doc', b'My doc', b'helpext')
859 > ui.setconfig(b'alias', b'hgalias:doc', b'My doc', b'helpext')
860 > ui.setconfig(b'alias', b'hgalias:category', b'navigation', b'helpext')
860 > ui.setconfig(b'alias', b'hgalias:category', b'navigation', b'helpext')
861 > ui.setconfig(b'alias', b'hgaliasnodoc', b'summary', b'helpext')
861 > ui.setconfig(b'alias', b'hgaliasnodoc', b'summary', b'helpext')
862 >
862 >
863 > EOF
863 > EOF
864 $ echo '[extensions]' >> $HGRCPATH
864 $ echo '[extensions]' >> $HGRCPATH
865 $ echo "helpext = `pwd`/helpext.py" >> $HGRCPATH
865 $ echo "helpext = `pwd`/helpext.py" >> $HGRCPATH
866
866
867 Test for aliases
867 Test for aliases
868
868
869 $ hg help | grep hgalias
869 $ hg help | grep hgalias
870 hgalias My doc
870 hgalias My doc
871
871
872 $ hg help hgalias
872 $ hg help hgalias
873 hg hgalias [--remote]
873 hg hgalias [--remote]
874
874
875 alias for: hg summary
875 alias for: hg summary
876
876
877 My doc
877 My doc
878
878
879 defined by: helpext
879 defined by: helpext
880
880
881 options:
881 options:
882
882
883 --remote check for push and pull
883 --remote check for push and pull
884
884
885 (some details hidden, use --verbose to show complete help)
885 (some details hidden, use --verbose to show complete help)
886 $ hg help hgaliasnodoc
886 $ hg help hgaliasnodoc
887 hg hgaliasnodoc [--remote]
887 hg hgaliasnodoc [--remote]
888
888
889 alias for: hg summary
889 alias for: hg summary
890
890
891 summarize working directory state
891 summarize working directory state
892
892
893 This generates a brief summary of the working directory state, including
893 This generates a brief summary of the working directory state, including
894 parents, branch, commit status, phase and available updates.
894 parents, branch, commit status, phase and available updates.
895
895
896 With the --remote option, this will check the default paths for incoming
896 With the --remote option, this will check the default paths for incoming
897 and outgoing changes. This can be time-consuming.
897 and outgoing changes. This can be time-consuming.
898
898
899 Returns 0 on success.
899 Returns 0 on success.
900
900
901 defined by: helpext
901 defined by: helpext
902
902
903 options:
903 options:
904
904
905 --remote check for push and pull
905 --remote check for push and pull
906
906
907 (some details hidden, use --verbose to show complete help)
907 (some details hidden, use --verbose to show complete help)
908
908
909 $ hg help shellalias
909 $ hg help shellalias
910 hg shellalias
910 hg shellalias
911
911
912 shell alias for: echo hi
912 shell alias for: echo hi
913
913
914 (no help text available)
914 (no help text available)
915
915
916 defined by: helpext
916 defined by: helpext
917
917
918 (some details hidden, use --verbose to show complete help)
918 (some details hidden, use --verbose to show complete help)
919
919
920 Test command with no help text
920 Test command with no help text
921
921
922 $ hg help nohelp
922 $ hg help nohelp
923 hg nohelp
923 hg nohelp
924
924
925 (no help text available)
925 (no help text available)
926
926
927 options:
927 options:
928
928
929 --longdesc VALUE
929 --longdesc VALUE
930 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
930 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
931 xxxxxxxxxxxxxxxxxxxxxxx (default: 3)
931 xxxxxxxxxxxxxxxxxxxxxxx (default: 3)
932 -n -- normal desc
932 -n -- normal desc
933 --newline VALUE line1 line2
933 --newline VALUE line1 line2
934 --default-off enable X
934 --default-off enable X
935 --[no-]default-on enable Y (default: on)
935 --[no-]default-on enable Y (default: on)
936 --callableopt VALUE adds foo
936 --callableopt VALUE adds foo
937 --customopt VALUE adds bar
937 --customopt VALUE adds bar
938 --customopt-withdefault VALUE adds bar (default: foo)
938 --customopt-withdefault VALUE adds bar (default: foo)
939
939
940 (some details hidden, use --verbose to show complete help)
940 (some details hidden, use --verbose to show complete help)
941
941
942 Test that default list of commands includes extension commands that have help,
942 Test that default list of commands includes extension commands that have help,
943 but not those that don't, except in verbose mode, when a keyword is passed, or
943 but not those that don't, except in verbose mode, when a keyword is passed, or
944 when help about the extension is requested.
944 when help about the extension is requested.
945
945
946 #if no-extraextensions
946 #if no-extraextensions
947
947
948 $ hg help | grep hashelp
948 $ hg help | grep hashelp
949 hashelp Extension command's help
949 hashelp Extension command's help
950 $ hg help | grep nohelp
950 $ hg help | grep nohelp
951 [1]
951 [1]
952 $ hg help -v | grep nohelp
952 $ hg help -v | grep nohelp
953 nohelp (no help text available)
953 nohelp (no help text available)
954
954
955 $ hg help -k nohelp
955 $ hg help -k nohelp
956 Commands:
956 Commands:
957
957
958 nohelp hg nohelp
958 nohelp hg nohelp
959
959
960 Extension Commands:
960 Extension Commands:
961
961
962 nohelp (no help text available)
962 nohelp (no help text available)
963
963
964 $ hg help helpext
964 $ hg help helpext
965 helpext extension - no help text available
965 helpext extension - no help text available
966
966
967 list of commands:
967 list of commands:
968
968
969 hashelp Extension command's help
969 hashelp Extension command's help
970 nohelp (no help text available)
970 nohelp (no help text available)
971
971
972 (use 'hg help -v helpext' to show built-in aliases and global options)
972 (use 'hg help -v helpext' to show built-in aliases and global options)
973
973
974 #endif
974 #endif
975
975
976 Test list of internal help commands
976 Test list of internal help commands
977
977
978 $ hg help debug
978 $ hg help debug
979 debug commands (internal and unsupported):
979 debug commands (internal and unsupported):
980
980
981 debug-delta-find
981 debug-delta-find
982 display the computation to get to a valid delta for storing REV
982 display the computation to get to a valid delta for storing REV
983 debug-repair-issue6528
983 debug-repair-issue6528
984 find affected revisions and repair them. See issue6528 for more
984 find affected revisions and repair them. See issue6528 for more
985 details.
985 details.
986 debug-revlog-index
986 debug-revlog-index
987 dump index data for a revlog
987 dump index data for a revlog
988 debug-revlog-stats
988 debug-revlog-stats
989 display statistics about revlogs in the store
989 display statistics about revlogs in the store
990 debug::stable-tail-sort
991 display the stable-tail sort of the ancestors of a given node
990 debugancestor
992 debugancestor
991 find the ancestor revision of two revisions in a given index
993 find the ancestor revision of two revisions in a given index
992 debugantivirusrunning
994 debugantivirusrunning
993 attempt to trigger an antivirus scanner to see if one is active
995 attempt to trigger an antivirus scanner to see if one is active
994 debugapplystreamclonebundle
996 debugapplystreamclonebundle
995 apply a stream clone bundle file
997 apply a stream clone bundle file
996 debugbackupbundle
998 debugbackupbundle
997 lists the changesets available in backup bundles
999 lists the changesets available in backup bundles
998 debugbuilddag
1000 debugbuilddag
999 builds a repo with a given DAG from scratch in the current
1001 builds a repo with a given DAG from scratch in the current
1000 empty repo
1002 empty repo
1001 debugbundle lists the contents of a bundle
1003 debugbundle lists the contents of a bundle
1002 debugcapabilities
1004 debugcapabilities
1003 lists the capabilities of a remote peer
1005 lists the capabilities of a remote peer
1004 debugchangedfiles
1006 debugchangedfiles
1005 list the stored files changes for a revision
1007 list the stored files changes for a revision
1006 debugcheckstate
1008 debugcheckstate
1007 validate the correctness of the current dirstate
1009 validate the correctness of the current dirstate
1008 debugcolor show available color, effects or style
1010 debugcolor show available color, effects or style
1009 debugcommands
1011 debugcommands
1010 list all available commands and options
1012 list all available commands and options
1011 debugcomplete
1013 debugcomplete
1012 returns the completion list associated with the given command
1014 returns the completion list associated with the given command
1013 debugcreatestreamclonebundle
1015 debugcreatestreamclonebundle
1014 create a stream clone bundle file
1016 create a stream clone bundle file
1015 debugdag format the changelog or an index DAG as a concise textual
1017 debugdag format the changelog or an index DAG as a concise textual
1016 description
1018 description
1017 debugdata dump the contents of a data file revision
1019 debugdata dump the contents of a data file revision
1018 debugdate parse and display a date
1020 debugdate parse and display a date
1019 debugdeltachain
1021 debugdeltachain
1020 dump information about delta chains in a revlog
1022 dump information about delta chains in a revlog
1021 debugdirstate
1023 debugdirstate
1022 show the contents of the current dirstate
1024 show the contents of the current dirstate
1023 debugdirstateignorepatternshash
1025 debugdirstateignorepatternshash
1024 show the hash of ignore patterns stored in dirstate if v2,
1026 show the hash of ignore patterns stored in dirstate if v2,
1025 debugdiscovery
1027 debugdiscovery
1026 runs the changeset discovery protocol in isolation
1028 runs the changeset discovery protocol in isolation
1027 debugdownload
1029 debugdownload
1028 download a resource using Mercurial logic and config
1030 download a resource using Mercurial logic and config
1029 debugextensions
1031 debugextensions
1030 show information about active extensions
1032 show information about active extensions
1031 debugfileset parse and apply a fileset specification
1033 debugfileset parse and apply a fileset specification
1032 debugformat display format information about the current repository
1034 debugformat display format information about the current repository
1033 debugfsinfo show information detected about current filesystem
1035 debugfsinfo show information detected about current filesystem
1034 debuggetbundle
1036 debuggetbundle
1035 retrieves a bundle from a repo
1037 retrieves a bundle from a repo
1036 debugignore display the combined ignore pattern and information about
1038 debugignore display the combined ignore pattern and information about
1037 ignored files
1039 ignored files
1038 debugindexdot
1040 debugindexdot
1039 dump an index DAG as a graphviz dot file
1041 dump an index DAG as a graphviz dot file
1040 debugindexstats
1042 debugindexstats
1041 show stats related to the changelog index
1043 show stats related to the changelog index
1042 debuginstall test Mercurial installation
1044 debuginstall test Mercurial installation
1043 debugknown test whether node ids are known to a repo
1045 debugknown test whether node ids are known to a repo
1044 debuglocks show or modify state of locks
1046 debuglocks show or modify state of locks
1045 debugmanifestfulltextcache
1047 debugmanifestfulltextcache
1046 show, clear or amend the contents of the manifest fulltext
1048 show, clear or amend the contents of the manifest fulltext
1047 cache
1049 cache
1048 debugmergestate
1050 debugmergestate
1049 print merge state
1051 print merge state
1050 debugnamecomplete
1052 debugnamecomplete
1051 complete "names" - tags, open branch names, bookmark names
1053 complete "names" - tags, open branch names, bookmark names
1052 debugnodemap write and inspect on disk nodemap
1054 debugnodemap write and inspect on disk nodemap
1053 debugobsolete
1055 debugobsolete
1054 create arbitrary obsolete marker
1056 create arbitrary obsolete marker
1055 debugoptADV (no help text available)
1057 debugoptADV (no help text available)
1056 debugoptDEP (no help text available)
1058 debugoptDEP (no help text available)
1057 debugoptEXP (no help text available)
1059 debugoptEXP (no help text available)
1058 debugp1copies
1060 debugp1copies
1059 dump copy information compared to p1
1061 dump copy information compared to p1
1060 debugp2copies
1062 debugp2copies
1061 dump copy information compared to p2
1063 dump copy information compared to p2
1062 debugpathcomplete
1064 debugpathcomplete
1063 complete part or all of a tracked path
1065 complete part or all of a tracked path
1064 debugpathcopies
1066 debugpathcopies
1065 show copies between two revisions
1067 show copies between two revisions
1066 debugpeer establish a connection to a peer repository
1068 debugpeer establish a connection to a peer repository
1067 debugpickmergetool
1069 debugpickmergetool
1068 examine which merge tool is chosen for specified file
1070 examine which merge tool is chosen for specified file
1069 debugpushkey access the pushkey key/value protocol
1071 debugpushkey access the pushkey key/value protocol
1070 debugpvec (no help text available)
1072 debugpvec (no help text available)
1071 debugrebuilddirstate
1073 debugrebuilddirstate
1072 rebuild the dirstate as it would look like for the given
1074 rebuild the dirstate as it would look like for the given
1073 revision
1075 revision
1074 debugrebuildfncache
1076 debugrebuildfncache
1075 rebuild the fncache file
1077 rebuild the fncache file
1076 debugrename dump rename information
1078 debugrename dump rename information
1077 debugrequires
1079 debugrequires
1078 print the current repo requirements
1080 print the current repo requirements
1079 debugrevlog show data and statistics about a revlog
1081 debugrevlog show data and statistics about a revlog
1080 debugrevlogindex
1082 debugrevlogindex
1081 dump the contents of a revlog index
1083 dump the contents of a revlog index
1082 debugrevspec parse and apply a revision specification
1084 debugrevspec parse and apply a revision specification
1083 debugserve run a server with advanced settings
1085 debugserve run a server with advanced settings
1084 debugsetparents
1086 debugsetparents
1085 manually set the parents of the current working directory
1087 manually set the parents of the current working directory
1086 (DANGEROUS)
1088 (DANGEROUS)
1087 debugshell run an interactive Python interpreter
1089 debugshell run an interactive Python interpreter
1088 debugsidedata
1090 debugsidedata
1089 dump the side data for a cl/manifest/file revision
1091 dump the side data for a cl/manifest/file revision
1090 debugssl test a secure connection to a server
1092 debugssl test a secure connection to a server
1091 debugstrip strip changesets and all their descendants from the repository
1093 debugstrip strip changesets and all their descendants from the repository
1092 debugsub (no help text available)
1094 debugsub (no help text available)
1093 debugsuccessorssets
1095 debugsuccessorssets
1094 show set of successors for revision
1096 show set of successors for revision
1095 debugtagscache
1097 debugtagscache
1096 display the contents of .hg/cache/hgtagsfnodes1
1098 display the contents of .hg/cache/hgtagsfnodes1
1097 debugtemplate
1099 debugtemplate
1098 parse and apply a template
1100 parse and apply a template
1099 debuguigetpass
1101 debuguigetpass
1100 show prompt to type password
1102 show prompt to type password
1101 debuguiprompt
1103 debuguiprompt
1102 show plain prompt
1104 show plain prompt
1103 debugupdatecaches
1105 debugupdatecaches
1104 warm all known caches in the repository
1106 warm all known caches in the repository
1105 debugupgraderepo
1107 debugupgraderepo
1106 upgrade a repository to use different features
1108 upgrade a repository to use different features
1107 debugwalk show how files match on given patterns
1109 debugwalk show how files match on given patterns
1108 debugwhyunstable
1110 debugwhyunstable
1109 explain instabilities of a changeset
1111 explain instabilities of a changeset
1110 debugwireargs
1112 debugwireargs
1111 (no help text available)
1113 (no help text available)
1112 debugwireproto
1114 debugwireproto
1113 send wire protocol commands to a server
1115 send wire protocol commands to a server
1114
1116
1115 (use 'hg help -v debug' to show built-in aliases and global options)
1117 (use 'hg help -v debug' to show built-in aliases and global options)
1116
1118
1117 internals topic renders index of available sub-topics
1119 internals topic renders index of available sub-topics
1118
1120
1119 $ hg help internals
1121 $ hg help internals
1120 Technical implementation topics
1122 Technical implementation topics
1121 """""""""""""""""""""""""""""""
1123 """""""""""""""""""""""""""""""
1122
1124
1123 To access a subtopic, use "hg help internals.{subtopic-name}"
1125 To access a subtopic, use "hg help internals.{subtopic-name}"
1124
1126
1125 bid-merge Bid Merge Algorithm
1127 bid-merge Bid Merge Algorithm
1126 bundle2 Bundle2
1128 bundle2 Bundle2
1127 bundles Bundles
1129 bundles Bundles
1128 cbor CBOR
1130 cbor CBOR
1129 censor Censor
1131 censor Censor
1130 changegroups Changegroups
1132 changegroups Changegroups
1131 config Config Registrar
1133 config Config Registrar
1132 dirstate-v2 dirstate-v2 file format
1134 dirstate-v2 dirstate-v2 file format
1133 extensions Extension API
1135 extensions Extension API
1134 mergestate Mergestate
1136 mergestate Mergestate
1135 requirements Repository Requirements
1137 requirements Repository Requirements
1136 revlogs Revision Logs
1138 revlogs Revision Logs
1137 wireprotocol Wire Protocol
1139 wireprotocol Wire Protocol
1138 wireprotocolrpc
1140 wireprotocolrpc
1139 Wire Protocol RPC
1141 Wire Protocol RPC
1140 wireprotocolv2
1142 wireprotocolv2
1141 Wire Protocol Version 2
1143 Wire Protocol Version 2
1142
1144
1143 sub-topics can be accessed
1145 sub-topics can be accessed
1144
1146
1145 $ hg help internals.changegroups
1147 $ hg help internals.changegroups
1146 Changegroups
1148 Changegroups
1147 """"""""""""
1149 """"""""""""
1148
1150
1149 Changegroups are representations of repository revlog data, specifically
1151 Changegroups are representations of repository revlog data, specifically
1150 the changelog data, root/flat manifest data, treemanifest data, and
1152 the changelog data, root/flat manifest data, treemanifest data, and
1151 filelogs.
1153 filelogs.
1152
1154
1153 There are 4 versions of changegroups: "1", "2", "3" and "4". From a high-
1155 There are 4 versions of changegroups: "1", "2", "3" and "4". From a high-
1154 level, versions "1" and "2" are almost exactly the same, with the only
1156 level, versions "1" and "2" are almost exactly the same, with the only
1155 difference being an additional item in the *delta header*. Version "3"
1157 difference being an additional item in the *delta header*. Version "3"
1156 adds support for storage flags in the *delta header* and optionally
1158 adds support for storage flags in the *delta header* and optionally
1157 exchanging treemanifests (enabled by setting an option on the
1159 exchanging treemanifests (enabled by setting an option on the
1158 "changegroup" part in the bundle2). Version "4" adds support for
1160 "changegroup" part in the bundle2). Version "4" adds support for
1159 exchanging sidedata (additional revision metadata not part of the digest).
1161 exchanging sidedata (additional revision metadata not part of the digest).
1160
1162
1161 Changegroups when not exchanging treemanifests consist of 3 logical
1163 Changegroups when not exchanging treemanifests consist of 3 logical
1162 segments:
1164 segments:
1163
1165
1164 +---------------------------------+
1166 +---------------------------------+
1165 | | | |
1167 | | | |
1166 | changeset | manifest | filelogs |
1168 | changeset | manifest | filelogs |
1167 | | | |
1169 | | | |
1168 | | | |
1170 | | | |
1169 +---------------------------------+
1171 +---------------------------------+
1170
1172
1171 When exchanging treemanifests, there are 4 logical segments:
1173 When exchanging treemanifests, there are 4 logical segments:
1172
1174
1173 +-------------------------------------------------+
1175 +-------------------------------------------------+
1174 | | | | |
1176 | | | | |
1175 | changeset | root | treemanifests | filelogs |
1177 | changeset | root | treemanifests | filelogs |
1176 | | manifest | | |
1178 | | manifest | | |
1177 | | | | |
1179 | | | | |
1178 +-------------------------------------------------+
1180 +-------------------------------------------------+
1179
1181
1180 The principle building block of each segment is a *chunk*. A *chunk* is a
1182 The principle building block of each segment is a *chunk*. A *chunk* is a
1181 framed piece of data:
1183 framed piece of data:
1182
1184
1183 +---------------------------------------+
1185 +---------------------------------------+
1184 | | |
1186 | | |
1185 | length | data |
1187 | length | data |
1186 | (4 bytes) | (<length - 4> bytes) |
1188 | (4 bytes) | (<length - 4> bytes) |
1187 | | |
1189 | | |
1188 +---------------------------------------+
1190 +---------------------------------------+
1189
1191
1190 All integers are big-endian signed integers. Each chunk starts with a
1192 All integers are big-endian signed integers. Each chunk starts with a
1191 32-bit integer indicating the length of the entire chunk (including the
1193 32-bit integer indicating the length of the entire chunk (including the
1192 length field itself).
1194 length field itself).
1193
1195
1194 There is a special case chunk that has a value of 0 for the length
1196 There is a special case chunk that has a value of 0 for the length
1195 ("0x00000000"). We call this an *empty chunk*.
1197 ("0x00000000"). We call this an *empty chunk*.
1196
1198
1197 Delta Groups
1199 Delta Groups
1198 ============
1200 ============
1199
1201
1200 A *delta group* expresses the content of a revlog as a series of deltas,
1202 A *delta group* expresses the content of a revlog as a series of deltas,
1201 or patches against previous revisions.
1203 or patches against previous revisions.
1202
1204
1203 Delta groups consist of 0 or more *chunks* followed by the *empty chunk*
1205 Delta groups consist of 0 or more *chunks* followed by the *empty chunk*
1204 to signal the end of the delta group:
1206 to signal the end of the delta group:
1205
1207
1206 +------------------------------------------------------------------------+
1208 +------------------------------------------------------------------------+
1207 | | | | | |
1209 | | | | | |
1208 | chunk0 length | chunk0 data | chunk1 length | chunk1 data | 0x0 |
1210 | chunk0 length | chunk0 data | chunk1 length | chunk1 data | 0x0 |
1209 | (4 bytes) | (various) | (4 bytes) | (various) | (4 bytes) |
1211 | (4 bytes) | (various) | (4 bytes) | (various) | (4 bytes) |
1210 | | | | | |
1212 | | | | | |
1211 +------------------------------------------------------------------------+
1213 +------------------------------------------------------------------------+
1212
1214
1213 Each *chunk*'s data consists of the following:
1215 Each *chunk*'s data consists of the following:
1214
1216
1215 +---------------------------------------+
1217 +---------------------------------------+
1216 | | |
1218 | | |
1217 | delta header | delta data |
1219 | delta header | delta data |
1218 | (various by version) | (various) |
1220 | (various by version) | (various) |
1219 | | |
1221 | | |
1220 +---------------------------------------+
1222 +---------------------------------------+
1221
1223
1222 The *delta data* is a series of *delta*s that describe a diff from an
1224 The *delta data* is a series of *delta*s that describe a diff from an
1223 existing entry (either that the recipient already has, or previously
1225 existing entry (either that the recipient already has, or previously
1224 specified in the bundle/changegroup).
1226 specified in the bundle/changegroup).
1225
1227
1226 The *delta header* is different between versions "1", "2", "3" and "4" of
1228 The *delta header* is different between versions "1", "2", "3" and "4" of
1227 the changegroup format.
1229 the changegroup format.
1228
1230
1229 Version 1 (headerlen=80):
1231 Version 1 (headerlen=80):
1230
1232
1231 +------------------------------------------------------+
1233 +------------------------------------------------------+
1232 | | | | |
1234 | | | | |
1233 | node | p1 node | p2 node | link node |
1235 | node | p1 node | p2 node | link node |
1234 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
1236 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
1235 | | | | |
1237 | | | | |
1236 +------------------------------------------------------+
1238 +------------------------------------------------------+
1237
1239
1238 Version 2 (headerlen=100):
1240 Version 2 (headerlen=100):
1239
1241
1240 +------------------------------------------------------------------+
1242 +------------------------------------------------------------------+
1241 | | | | | |
1243 | | | | | |
1242 | node | p1 node | p2 node | base node | link node |
1244 | node | p1 node | p2 node | base node | link node |
1243 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
1245 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
1244 | | | | | |
1246 | | | | | |
1245 +------------------------------------------------------------------+
1247 +------------------------------------------------------------------+
1246
1248
1247 Version 3 (headerlen=102):
1249 Version 3 (headerlen=102):
1248
1250
1249 +------------------------------------------------------------------------------+
1251 +------------------------------------------------------------------------------+
1250 | | | | | | |
1252 | | | | | | |
1251 | node | p1 node | p2 node | base node | link node | flags |
1253 | node | p1 node | p2 node | base node | link node | flags |
1252 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (2 bytes) |
1254 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (2 bytes) |
1253 | | | | | | |
1255 | | | | | | |
1254 +------------------------------------------------------------------------------+
1256 +------------------------------------------------------------------------------+
1255
1257
1256 Version 4 (headerlen=103):
1258 Version 4 (headerlen=103):
1257
1259
1258 +------------------------------------------------------------------------------+----------+
1260 +------------------------------------------------------------------------------+----------+
1259 | | | | | | | |
1261 | | | | | | | |
1260 | node | p1 node | p2 node | base node | link node | flags | pflags |
1262 | node | p1 node | p2 node | base node | link node | flags | pflags |
1261 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (2 bytes) | (1 byte) |
1263 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (2 bytes) | (1 byte) |
1262 | | | | | | | |
1264 | | | | | | | |
1263 +------------------------------------------------------------------------------+----------+
1265 +------------------------------------------------------------------------------+----------+
1264
1266
1265 The *delta data* consists of "chunklen - 4 - headerlen" bytes, which
1267 The *delta data* consists of "chunklen - 4 - headerlen" bytes, which
1266 contain a series of *delta*s, densely packed (no separators). These deltas
1268 contain a series of *delta*s, densely packed (no separators). These deltas
1267 describe a diff from an existing entry (either that the recipient already
1269 describe a diff from an existing entry (either that the recipient already
1268 has, or previously specified in the bundle/changegroup). The format is
1270 has, or previously specified in the bundle/changegroup). The format is
1269 described more fully in "hg help internals.bdiff", but briefly:
1271 described more fully in "hg help internals.bdiff", but briefly:
1270
1272
1271 +---------------------------------------------------------------+
1273 +---------------------------------------------------------------+
1272 | | | | |
1274 | | | | |
1273 | start offset | end offset | new length | content |
1275 | start offset | end offset | new length | content |
1274 | (4 bytes) | (4 bytes) | (4 bytes) | (<new length> bytes) |
1276 | (4 bytes) | (4 bytes) | (4 bytes) | (<new length> bytes) |
1275 | | | | |
1277 | | | | |
1276 +---------------------------------------------------------------+
1278 +---------------------------------------------------------------+
1277
1279
1278 Please note that the length field in the delta data does *not* include
1280 Please note that the length field in the delta data does *not* include
1279 itself.
1281 itself.
1280
1282
1281 In version 1, the delta is always applied against the previous node from
1283 In version 1, the delta is always applied against the previous node from
1282 the changegroup or the first parent if this is the first entry in the
1284 the changegroup or the first parent if this is the first entry in the
1283 changegroup.
1285 changegroup.
1284
1286
1285 In version 2 and up, the delta base node is encoded in the entry in the
1287 In version 2 and up, the delta base node is encoded in the entry in the
1286 changegroup. This allows the delta to be expressed against any parent,
1288 changegroup. This allows the delta to be expressed against any parent,
1287 which can result in smaller deltas and more efficient encoding of data.
1289 which can result in smaller deltas and more efficient encoding of data.
1288
1290
1289 The *flags* field holds bitwise flags affecting the processing of revision
1291 The *flags* field holds bitwise flags affecting the processing of revision
1290 data. The following flags are defined:
1292 data. The following flags are defined:
1291
1293
1292 32768
1294 32768
1293 Censored revision. The revision's fulltext has been replaced by censor
1295 Censored revision. The revision's fulltext has been replaced by censor
1294 metadata. May only occur on file revisions.
1296 metadata. May only occur on file revisions.
1295
1297
1296 16384
1298 16384
1297 Ellipsis revision. Revision hash does not match data (likely due to
1299 Ellipsis revision. Revision hash does not match data (likely due to
1298 rewritten parents).
1300 rewritten parents).
1299
1301
1300 8192
1302 8192
1301 Externally stored. The revision fulltext contains "key:value" "\n"
1303 Externally stored. The revision fulltext contains "key:value" "\n"
1302 delimited metadata defining an object stored elsewhere. Used by the LFS
1304 delimited metadata defining an object stored elsewhere. Used by the LFS
1303 extension.
1305 extension.
1304
1306
1305 4096
1307 4096
1306 Contains copy information. This revision changes files in a way that
1308 Contains copy information. This revision changes files in a way that
1307 could affect copy tracing. This does *not* affect changegroup handling,
1309 could affect copy tracing. This does *not* affect changegroup handling,
1308 but is relevant for other parts of Mercurial.
1310 but is relevant for other parts of Mercurial.
1309
1311
1310 For historical reasons, the integer values are identical to revlog version
1312 For historical reasons, the integer values are identical to revlog version
1311 1 per-revision storage flags and correspond to bits being set in this
1313 1 per-revision storage flags and correspond to bits being set in this
1312 2-byte field. Bits were allocated starting from the most-significant bit,
1314 2-byte field. Bits were allocated starting from the most-significant bit,
1313 hence the reverse ordering and allocation of these flags.
1315 hence the reverse ordering and allocation of these flags.
1314
1316
1315 The *pflags* (protocol flags) field holds bitwise flags affecting the
1317 The *pflags* (protocol flags) field holds bitwise flags affecting the
1316 protocol itself. They are first in the header since they may affect the
1318 protocol itself. They are first in the header since they may affect the
1317 handling of the rest of the fields in a future version. They are defined
1319 handling of the rest of the fields in a future version. They are defined
1318 as such:
1320 as such:
1319
1321
1320 1 indicates whether to read a chunk of sidedata (of variable length) right
1322 1 indicates whether to read a chunk of sidedata (of variable length) right
1321 after the revision flags.
1323 after the revision flags.
1322
1324
1323 Changeset Segment
1325 Changeset Segment
1324 =================
1326 =================
1325
1327
1326 The *changeset segment* consists of a single *delta group* holding
1328 The *changeset segment* consists of a single *delta group* holding
1327 changelog data. The *empty chunk* at the end of the *delta group* denotes
1329 changelog data. The *empty chunk* at the end of the *delta group* denotes
1328 the boundary to the *manifest segment*.
1330 the boundary to the *manifest segment*.
1329
1331
1330 Manifest Segment
1332 Manifest Segment
1331 ================
1333 ================
1332
1334
1333 The *manifest segment* consists of a single *delta group* holding manifest
1335 The *manifest segment* consists of a single *delta group* holding manifest
1334 data. If treemanifests are in use, it contains only the manifest for the
1336 data. If treemanifests are in use, it contains only the manifest for the
1335 root directory of the repository. Otherwise, it contains the entire
1337 root directory of the repository. Otherwise, it contains the entire
1336 manifest data. The *empty chunk* at the end of the *delta group* denotes
1338 manifest data. The *empty chunk* at the end of the *delta group* denotes
1337 the boundary to the next segment (either the *treemanifests segment* or
1339 the boundary to the next segment (either the *treemanifests segment* or
1338 the *filelogs segment*, depending on version and the request options).
1340 the *filelogs segment*, depending on version and the request options).
1339
1341
1340 Treemanifests Segment
1342 Treemanifests Segment
1341 ---------------------
1343 ---------------------
1342
1344
1343 The *treemanifests segment* only exists in changegroup version "3" and
1345 The *treemanifests segment* only exists in changegroup version "3" and
1344 "4", and only if the 'treemanifest' param is part of the bundle2
1346 "4", and only if the 'treemanifest' param is part of the bundle2
1345 changegroup part (it is not possible to use changegroup version 3 or 4
1347 changegroup part (it is not possible to use changegroup version 3 or 4
1346 outside of bundle2). Aside from the filenames in the *treemanifests
1348 outside of bundle2). Aside from the filenames in the *treemanifests
1347 segment* containing a trailing "/" character, it behaves identically to
1349 segment* containing a trailing "/" character, it behaves identically to
1348 the *filelogs segment* (see below). The final sub-segment is followed by
1350 the *filelogs segment* (see below). The final sub-segment is followed by
1349 an *empty chunk* (logically, a sub-segment with filename size 0). This
1351 an *empty chunk* (logically, a sub-segment with filename size 0). This
1350 denotes the boundary to the *filelogs segment*.
1352 denotes the boundary to the *filelogs segment*.
1351
1353
1352 Filelogs Segment
1354 Filelogs Segment
1353 ================
1355 ================
1354
1356
1355 The *filelogs segment* consists of multiple sub-segments, each
1357 The *filelogs segment* consists of multiple sub-segments, each
1356 corresponding to an individual file whose data is being described:
1358 corresponding to an individual file whose data is being described:
1357
1359
1358 +--------------------------------------------------+
1360 +--------------------------------------------------+
1359 | | | | | |
1361 | | | | | |
1360 | filelog0 | filelog1 | filelog2 | ... | 0x0 |
1362 | filelog0 | filelog1 | filelog2 | ... | 0x0 |
1361 | | | | | (4 bytes) |
1363 | | | | | (4 bytes) |
1362 | | | | | |
1364 | | | | | |
1363 +--------------------------------------------------+
1365 +--------------------------------------------------+
1364
1366
1365 The final filelog sub-segment is followed by an *empty chunk* (logically,
1367 The final filelog sub-segment is followed by an *empty chunk* (logically,
1366 a sub-segment with filename size 0). This denotes the end of the segment
1368 a sub-segment with filename size 0). This denotes the end of the segment
1367 and of the overall changegroup.
1369 and of the overall changegroup.
1368
1370
1369 Each filelog sub-segment consists of the following:
1371 Each filelog sub-segment consists of the following:
1370
1372
1371 +------------------------------------------------------+
1373 +------------------------------------------------------+
1372 | | | |
1374 | | | |
1373 | filename length | filename | delta group |
1375 | filename length | filename | delta group |
1374 | (4 bytes) | (<length - 4> bytes) | (various) |
1376 | (4 bytes) | (<length - 4> bytes) | (various) |
1375 | | | |
1377 | | | |
1376 +------------------------------------------------------+
1378 +------------------------------------------------------+
1377
1379
1378 That is, a *chunk* consisting of the filename (not terminated or padded)
1380 That is, a *chunk* consisting of the filename (not terminated or padded)
1379 followed by N chunks constituting the *delta group* for this file. The
1381 followed by N chunks constituting the *delta group* for this file. The
1380 *empty chunk* at the end of each *delta group* denotes the boundary to the
1382 *empty chunk* at the end of each *delta group* denotes the boundary to the
1381 next filelog sub-segment.
1383 next filelog sub-segment.
1382
1384
1383 non-existent subtopics print an error
1385 non-existent subtopics print an error
1384
1386
1385 $ hg help internals.foo
1387 $ hg help internals.foo
1386 abort: no such help topic: internals.foo
1388 abort: no such help topic: internals.foo
1387 (try 'hg help --keyword foo')
1389 (try 'hg help --keyword foo')
1388 [10]
1390 [10]
1389
1391
1390 test advanced, deprecated and experimental options are hidden in command help
1392 test advanced, deprecated and experimental options are hidden in command help
1391 $ hg help debugoptADV
1393 $ hg help debugoptADV
1392 hg debugoptADV
1394 hg debugoptADV
1393
1395
1394 (no help text available)
1396 (no help text available)
1395
1397
1396 options:
1398 options:
1397
1399
1398 (some details hidden, use --verbose to show complete help)
1400 (some details hidden, use --verbose to show complete help)
1399 $ hg help debugoptDEP
1401 $ hg help debugoptDEP
1400 hg debugoptDEP
1402 hg debugoptDEP
1401
1403
1402 (no help text available)
1404 (no help text available)
1403
1405
1404 options:
1406 options:
1405
1407
1406 (some details hidden, use --verbose to show complete help)
1408 (some details hidden, use --verbose to show complete help)
1407
1409
1408 $ hg help debugoptEXP
1410 $ hg help debugoptEXP
1409 hg debugoptEXP
1411 hg debugoptEXP
1410
1412
1411 (no help text available)
1413 (no help text available)
1412
1414
1413 options:
1415 options:
1414
1416
1415 (some details hidden, use --verbose to show complete help)
1417 (some details hidden, use --verbose to show complete help)
1416
1418
1417 test advanced, deprecated and experimental options are shown with -v
1419 test advanced, deprecated and experimental options are shown with -v
1418 $ hg help -v debugoptADV | grep aopt
1420 $ hg help -v debugoptADV | grep aopt
1419 --aopt option is (ADVANCED)
1421 --aopt option is (ADVANCED)
1420 $ hg help -v debugoptDEP | grep dopt
1422 $ hg help -v debugoptDEP | grep dopt
1421 --dopt option is (DEPRECATED)
1423 --dopt option is (DEPRECATED)
1422 $ hg help -v debugoptEXP | grep eopt
1424 $ hg help -v debugoptEXP | grep eopt
1423 --eopt option is (EXPERIMENTAL)
1425 --eopt option is (EXPERIMENTAL)
1424
1426
1425 #if gettext
1427 #if gettext
1426 test deprecated option is hidden with translation with untranslated description
1428 test deprecated option is hidden with translation with untranslated description
1427 (use many globy for not failing on changed transaction)
1429 (use many globy for not failing on changed transaction)
1428 $ LANGUAGE=sv hg help debugoptDEP
1430 $ LANGUAGE=sv hg help debugoptDEP
1429 hg debugoptDEP
1431 hg debugoptDEP
1430
1432
1431 (*) (glob)
1433 (*) (glob)
1432
1434
1433 options:
1435 options:
1434
1436
1435 (some details hidden, use --verbose to show complete help)
1437 (some details hidden, use --verbose to show complete help)
1436 #endif
1438 #endif
1437
1439
1438 Test commands that collide with topics (issue4240)
1440 Test commands that collide with topics (issue4240)
1439
1441
1440 $ hg config -hq
1442 $ hg config -hq
1441 hg config [-u] [NAME]...
1443 hg config [-u] [NAME]...
1442
1444
1443 show combined config settings from all hgrc files
1445 show combined config settings from all hgrc files
1444 $ hg showconfig -hq
1446 $ hg showconfig -hq
1445 hg config [-u] [NAME]...
1447 hg config [-u] [NAME]...
1446
1448
1447 show combined config settings from all hgrc files
1449 show combined config settings from all hgrc files
1448
1450
1449 Test a help topic
1451 Test a help topic
1450
1452
1451 $ hg help dates
1453 $ hg help dates
1452 Date Formats
1454 Date Formats
1453 """"""""""""
1455 """"""""""""
1454
1456
1455 Some commands allow the user to specify a date, e.g.:
1457 Some commands allow the user to specify a date, e.g.:
1456
1458
1457 - backout, commit, import, tag: Specify the commit date.
1459 - backout, commit, import, tag: Specify the commit date.
1458 - log, revert, update: Select revision(s) by date.
1460 - log, revert, update: Select revision(s) by date.
1459
1461
1460 Many date formats are valid. Here are some examples:
1462 Many date formats are valid. Here are some examples:
1461
1463
1462 - "Wed Dec 6 13:18:29 2006" (local timezone assumed)
1464 - "Wed Dec 6 13:18:29 2006" (local timezone assumed)
1463 - "Dec 6 13:18 -0600" (year assumed, time offset provided)
1465 - "Dec 6 13:18 -0600" (year assumed, time offset provided)
1464 - "Dec 6 13:18 UTC" (UTC and GMT are aliases for +0000)
1466 - "Dec 6 13:18 UTC" (UTC and GMT are aliases for +0000)
1465 - "Dec 6" (midnight)
1467 - "Dec 6" (midnight)
1466 - "13:18" (today assumed)
1468 - "13:18" (today assumed)
1467 - "3:39" (3:39AM assumed)
1469 - "3:39" (3:39AM assumed)
1468 - "3:39pm" (15:39)
1470 - "3:39pm" (15:39)
1469 - "2006-12-06 13:18:29" (ISO 8601 format)
1471 - "2006-12-06 13:18:29" (ISO 8601 format)
1470 - "2006-12-6 13:18"
1472 - "2006-12-6 13:18"
1471 - "2006-12-6"
1473 - "2006-12-6"
1472 - "12-6"
1474 - "12-6"
1473 - "12/6"
1475 - "12/6"
1474 - "12/6/6" (Dec 6 2006)
1476 - "12/6/6" (Dec 6 2006)
1475 - "today" (midnight)
1477 - "today" (midnight)
1476 - "yesterday" (midnight)
1478 - "yesterday" (midnight)
1477 - "now" - right now
1479 - "now" - right now
1478
1480
1479 Lastly, there is Mercurial's internal format:
1481 Lastly, there is Mercurial's internal format:
1480
1482
1481 - "1165411109 0" (Wed Dec 6 13:18:29 2006 UTC)
1483 - "1165411109 0" (Wed Dec 6 13:18:29 2006 UTC)
1482
1484
1483 This is the internal representation format for dates. The first number is
1485 This is the internal representation format for dates. The first number is
1484 the number of seconds since the epoch (1970-01-01 00:00 UTC). The second
1486 the number of seconds since the epoch (1970-01-01 00:00 UTC). The second
1485 is the offset of the local timezone, in seconds west of UTC (negative if
1487 is the offset of the local timezone, in seconds west of UTC (negative if
1486 the timezone is east of UTC).
1488 the timezone is east of UTC).
1487
1489
1488 The log command also accepts date ranges:
1490 The log command also accepts date ranges:
1489
1491
1490 - "<DATE" - at or before a given date/time
1492 - "<DATE" - at or before a given date/time
1491 - ">DATE" - on or after a given date/time
1493 - ">DATE" - on or after a given date/time
1492 - "DATE to DATE" - a date range, inclusive
1494 - "DATE to DATE" - a date range, inclusive
1493 - "-DAYS" - within a given number of days from today
1495 - "-DAYS" - within a given number of days from today
1494
1496
1495 Test repeated config section name
1497 Test repeated config section name
1496
1498
1497 $ hg help config.host
1499 $ hg help config.host
1498 "http_proxy.host"
1500 "http_proxy.host"
1499 Host name and (optional) port of the proxy server, for example
1501 Host name and (optional) port of the proxy server, for example
1500 "myproxy:8000".
1502 "myproxy:8000".
1501
1503
1502 "smtp.host"
1504 "smtp.host"
1503 Host name of mail server, e.g. "mail.example.com".
1505 Host name of mail server, e.g. "mail.example.com".
1504
1506
1505
1507
1506 Test section name with dot
1508 Test section name with dot
1507
1509
1508 $ hg help config.ui.username
1510 $ hg help config.ui.username
1509 "ui.username"
1511 "ui.username"
1510 The committer of a changeset created when running "commit". Typically
1512 The committer of a changeset created when running "commit". Typically
1511 a person's name and email address, e.g. "Fred Widget
1513 a person's name and email address, e.g. "Fred Widget
1512 <fred@example.com>". Environment variables in the username are
1514 <fred@example.com>". Environment variables in the username are
1513 expanded.
1515 expanded.
1514
1516
1515 (default: "$EMAIL" or "username@hostname". If the username in hgrc is
1517 (default: "$EMAIL" or "username@hostname". If the username in hgrc is
1516 empty, e.g. if the system admin set "username =" in the system hgrc,
1518 empty, e.g. if the system admin set "username =" in the system hgrc,
1517 it has to be specified manually or in a different hgrc file)
1519 it has to be specified manually or in a different hgrc file)
1518
1520
1519
1521
1520 $ hg help config.annotate.git
1522 $ hg help config.annotate.git
1521 abort: help section not found: config.annotate.git
1523 abort: help section not found: config.annotate.git
1522 [10]
1524 [10]
1523
1525
1524 $ hg help config.update.check
1526 $ hg help config.update.check
1525 "commands.update.check"
1527 "commands.update.check"
1526 Determines what level of checking 'hg update' will perform before
1528 Determines what level of checking 'hg update' will perform before
1527 moving to a destination revision. Valid values are "abort", "none",
1529 moving to a destination revision. Valid values are "abort", "none",
1528 "linear", and "noconflict".
1530 "linear", and "noconflict".
1529
1531
1530 - "abort" always fails if the working directory has uncommitted
1532 - "abort" always fails if the working directory has uncommitted
1531 changes.
1533 changes.
1532 - "none" performs no checking, and may result in a merge with
1534 - "none" performs no checking, and may result in a merge with
1533 uncommitted changes.
1535 uncommitted changes.
1534 - "linear" allows any update as long as it follows a straight line in
1536 - "linear" allows any update as long as it follows a straight line in
1535 the revision history, and may trigger a merge with uncommitted
1537 the revision history, and may trigger a merge with uncommitted
1536 changes.
1538 changes.
1537 - "noconflict" will allow any update which would not trigger a merge
1539 - "noconflict" will allow any update which would not trigger a merge
1538 with uncommitted changes, if any are present.
1540 with uncommitted changes, if any are present.
1539
1541
1540 (default: "linear")
1542 (default: "linear")
1541
1543
1542
1544
1543 $ hg help config.commands.update.check
1545 $ hg help config.commands.update.check
1544 "commands.update.check"
1546 "commands.update.check"
1545 Determines what level of checking 'hg update' will perform before
1547 Determines what level of checking 'hg update' will perform before
1546 moving to a destination revision. Valid values are "abort", "none",
1548 moving to a destination revision. Valid values are "abort", "none",
1547 "linear", and "noconflict".
1549 "linear", and "noconflict".
1548
1550
1549 - "abort" always fails if the working directory has uncommitted
1551 - "abort" always fails if the working directory has uncommitted
1550 changes.
1552 changes.
1551 - "none" performs no checking, and may result in a merge with
1553 - "none" performs no checking, and may result in a merge with
1552 uncommitted changes.
1554 uncommitted changes.
1553 - "linear" allows any update as long as it follows a straight line in
1555 - "linear" allows any update as long as it follows a straight line in
1554 the revision history, and may trigger a merge with uncommitted
1556 the revision history, and may trigger a merge with uncommitted
1555 changes.
1557 changes.
1556 - "noconflict" will allow any update which would not trigger a merge
1558 - "noconflict" will allow any update which would not trigger a merge
1557 with uncommitted changes, if any are present.
1559 with uncommitted changes, if any are present.
1558
1560
1559 (default: "linear")
1561 (default: "linear")
1560
1562
1561
1563
1562 $ hg help config.ommands.update.check
1564 $ hg help config.ommands.update.check
1563 abort: help section not found: config.ommands.update.check
1565 abort: help section not found: config.ommands.update.check
1564 [10]
1566 [10]
1565
1567
1566 Unrelated trailing paragraphs shouldn't be included
1568 Unrelated trailing paragraphs shouldn't be included
1567
1569
1568 $ hg help config.extramsg | grep '^$'
1570 $ hg help config.extramsg | grep '^$'
1569
1571
1570
1572
1571 Test capitalized section name
1573 Test capitalized section name
1572
1574
1573 $ hg help scripting.HGPLAIN > /dev/null
1575 $ hg help scripting.HGPLAIN > /dev/null
1574
1576
1575 Help subsection:
1577 Help subsection:
1576
1578
1577 $ hg help config.charsets |grep "Email example:" > /dev/null
1579 $ hg help config.charsets |grep "Email example:" > /dev/null
1578 [1]
1580 [1]
1579
1581
1580 Show nested definitions
1582 Show nested definitions
1581 ("profiling.type"[break]"ls"[break]"stat"[break])
1583 ("profiling.type"[break]"ls"[break]"stat"[break])
1582
1584
1583 $ hg help config.type | egrep '^$'|wc -l
1585 $ hg help config.type | egrep '^$'|wc -l
1584 \s*3 (re)
1586 \s*3 (re)
1585
1587
1586 $ hg help config.profiling.type.ls
1588 $ hg help config.profiling.type.ls
1587 "profiling.type.ls"
1589 "profiling.type.ls"
1588 Use Python's built-in instrumenting profiler. This profiler works on
1590 Use Python's built-in instrumenting profiler. This profiler works on
1589 all platforms, but each line number it reports is the first line of
1591 all platforms, but each line number it reports is the first line of
1590 a function. This restriction makes it difficult to identify the
1592 a function. This restriction makes it difficult to identify the
1591 expensive parts of a non-trivial function.
1593 expensive parts of a non-trivial function.
1592
1594
1593
1595
1594 Separate sections from subsections
1596 Separate sections from subsections
1595
1597
1596 $ hg help config.format | egrep '^ ("|-)|^\s*$' | uniq
1598 $ hg help config.format | egrep '^ ("|-)|^\s*$' | uniq
1597 "format"
1599 "format"
1598 --------
1600 --------
1599
1601
1600 "usegeneraldelta"
1602 "usegeneraldelta"
1601
1603
1602 "dotencode"
1604 "dotencode"
1603
1605
1604 "usefncache"
1606 "usefncache"
1605
1607
1606 "use-dirstate-v2"
1608 "use-dirstate-v2"
1607
1609
1608 "use-dirstate-v2.automatic-upgrade-of-mismatching-repositories"
1610 "use-dirstate-v2.automatic-upgrade-of-mismatching-repositories"
1609
1611
1610 "use-dirstate-v2.automatic-upgrade-of-mismatching-repositories:quiet"
1612 "use-dirstate-v2.automatic-upgrade-of-mismatching-repositories:quiet"
1611
1613
1612 "use-dirstate-tracked-hint"
1614 "use-dirstate-tracked-hint"
1613
1615
1614 "use-dirstate-tracked-hint.automatic-upgrade-of-mismatching-repositories"
1616 "use-dirstate-tracked-hint.automatic-upgrade-of-mismatching-repositories"
1615
1617
1616 "use-dirstate-tracked-hint.automatic-upgrade-of-mismatching-repositories:quiet"
1618 "use-dirstate-tracked-hint.automatic-upgrade-of-mismatching-repositories:quiet"
1617
1619
1618 "use-persistent-nodemap"
1620 "use-persistent-nodemap"
1619
1621
1620 "use-share-safe"
1622 "use-share-safe"
1621
1623
1622 "use-share-safe.automatic-upgrade-of-mismatching-repositories"
1624 "use-share-safe.automatic-upgrade-of-mismatching-repositories"
1623
1625
1624 "use-share-safe.automatic-upgrade-of-mismatching-repositories:quiet"
1626 "use-share-safe.automatic-upgrade-of-mismatching-repositories:quiet"
1625
1627
1626 "usestore"
1628 "usestore"
1627
1629
1628 "sparse-revlog"
1630 "sparse-revlog"
1629
1631
1630 "revlog-compression"
1632 "revlog-compression"
1631
1633
1632 "bookmarks-in-store"
1634 "bookmarks-in-store"
1633
1635
1634 "profiling"
1636 "profiling"
1635 -----------
1637 -----------
1636
1638
1637 "format"
1639 "format"
1638
1640
1639 "progress"
1641 "progress"
1640 ----------
1642 ----------
1641
1643
1642 "format"
1644 "format"
1643
1645
1644
1646
1645 Last item in help config.*:
1647 Last item in help config.*:
1646
1648
1647 $ hg help config.`hg help config|grep '^ "'| \
1649 $ hg help config.`hg help config|grep '^ "'| \
1648 > tail -1|sed 's![ "]*!!g'`| \
1650 > tail -1|sed 's![ "]*!!g'`| \
1649 > grep 'hg help -c config' > /dev/null
1651 > grep 'hg help -c config' > /dev/null
1650 [1]
1652 [1]
1651
1653
1652 note to use help -c for general hg help config:
1654 note to use help -c for general hg help config:
1653
1655
1654 $ hg help config |grep 'hg help -c config' > /dev/null
1656 $ hg help config |grep 'hg help -c config' > /dev/null
1655
1657
1656 Test templating help
1658 Test templating help
1657
1659
1658 $ hg help templating | egrep '(desc|diffstat|firstline|nonempty) '
1660 $ hg help templating | egrep '(desc|diffstat|firstline|nonempty) '
1659 desc String. The text of the changeset description.
1661 desc String. The text of the changeset description.
1660 diffstat String. Statistics of changes with the following format:
1662 diffstat String. Statistics of changes with the following format:
1661 firstline Any text. Returns the first line of text.
1663 firstline Any text. Returns the first line of text.
1662 nonempty Any text. Returns '(none)' if the string is empty.
1664 nonempty Any text. Returns '(none)' if the string is empty.
1663
1665
1664 Test deprecated items
1666 Test deprecated items
1665
1667
1666 $ hg help -v templating | grep currentbookmark
1668 $ hg help -v templating | grep currentbookmark
1667 currentbookmark
1669 currentbookmark
1668 $ hg help templating | (grep currentbookmark || true)
1670 $ hg help templating | (grep currentbookmark || true)
1669
1671
1670 Test help hooks
1672 Test help hooks
1671
1673
1672 $ cat > helphook1.py <<EOF
1674 $ cat > helphook1.py <<EOF
1673 > from mercurial import help
1675 > from mercurial import help
1674 >
1676 >
1675 > def rewrite(ui, topic, doc):
1677 > def rewrite(ui, topic, doc):
1676 > return doc + b'\nhelphook1\n'
1678 > return doc + b'\nhelphook1\n'
1677 >
1679 >
1678 > def extsetup(ui):
1680 > def extsetup(ui):
1679 > help.addtopichook(b'revisions', rewrite)
1681 > help.addtopichook(b'revisions', rewrite)
1680 > EOF
1682 > EOF
1681 $ cat > helphook2.py <<EOF
1683 $ cat > helphook2.py <<EOF
1682 > from mercurial import help
1684 > from mercurial import help
1683 >
1685 >
1684 > def rewrite(ui, topic, doc):
1686 > def rewrite(ui, topic, doc):
1685 > return doc + b'\nhelphook2\n'
1687 > return doc + b'\nhelphook2\n'
1686 >
1688 >
1687 > def extsetup(ui):
1689 > def extsetup(ui):
1688 > help.addtopichook(b'revisions', rewrite)
1690 > help.addtopichook(b'revisions', rewrite)
1689 > EOF
1691 > EOF
1690 $ echo '[extensions]' >> $HGRCPATH
1692 $ echo '[extensions]' >> $HGRCPATH
1691 $ echo "helphook1 = `pwd`/helphook1.py" >> $HGRCPATH
1693 $ echo "helphook1 = `pwd`/helphook1.py" >> $HGRCPATH
1692 $ echo "helphook2 = `pwd`/helphook2.py" >> $HGRCPATH
1694 $ echo "helphook2 = `pwd`/helphook2.py" >> $HGRCPATH
1693 $ hg help revsets | grep helphook
1695 $ hg help revsets | grep helphook
1694 helphook1
1696 helphook1
1695 helphook2
1697 helphook2
1696
1698
1697 help -c should only show debug --debug
1699 help -c should only show debug --debug
1698
1700
1699 $ hg help -c --debug|egrep debug|wc -l|egrep '^\s*0\s*$'
1701 $ hg help -c --debug|egrep debug|wc -l|egrep '^\s*0\s*$'
1700 [1]
1702 [1]
1701
1703
1702 help -c should only show deprecated for -v
1704 help -c should only show deprecated for -v
1703
1705
1704 $ hg help -c -v|egrep DEPRECATED|wc -l|egrep '^\s*0\s*$'
1706 $ hg help -c -v|egrep DEPRECATED|wc -l|egrep '^\s*0\s*$'
1705 [1]
1707 [1]
1706
1708
1707 Test -s / --system
1709 Test -s / --system
1708
1710
1709 $ hg help config.files -s windows |grep 'etc/mercurial' | \
1711 $ hg help config.files -s windows |grep 'etc/mercurial' | \
1710 > wc -l | sed -e 's/ //g'
1712 > wc -l | sed -e 's/ //g'
1711 0
1713 0
1712 $ hg help config.files --system unix | grep 'USER' | \
1714 $ hg help config.files --system unix | grep 'USER' | \
1713 > wc -l | sed -e 's/ //g'
1715 > wc -l | sed -e 's/ //g'
1714 0
1716 0
1715
1717
1716 Test -e / -c / -k combinations
1718 Test -e / -c / -k combinations
1717
1719
1718 $ hg help -c|egrep '^[A-Z].*:|^ debug'
1720 $ hg help -c|egrep '^[A-Z].*:|^ debug'
1719 Commands:
1721 Commands:
1720 $ hg help -e|egrep '^[A-Z].*:|^ debug'
1722 $ hg help -e|egrep '^[A-Z].*:|^ debug'
1721 Extensions:
1723 Extensions:
1722 $ hg help -k|egrep '^[A-Z].*:|^ debug'
1724 $ hg help -k|egrep '^[A-Z].*:|^ debug'
1723 Topics:
1725 Topics:
1724 Commands:
1726 Commands:
1725 Extensions:
1727 Extensions:
1726 Extension Commands:
1728 Extension Commands:
1727 $ hg help -c schemes
1729 $ hg help -c schemes
1728 abort: no such help topic: schemes
1730 abort: no such help topic: schemes
1729 (try 'hg help --keyword schemes')
1731 (try 'hg help --keyword schemes')
1730 [10]
1732 [10]
1731 $ hg help -e schemes |head -1
1733 $ hg help -e schemes |head -1
1732 schemes extension - extend schemes with shortcuts to repository swarms
1734 schemes extension - extend schemes with shortcuts to repository swarms
1733 $ hg help -c -k dates |egrep '^(Topics|Extensions|Commands):'
1735 $ hg help -c -k dates |egrep '^(Topics|Extensions|Commands):'
1734 Commands:
1736 Commands:
1735 $ hg help -e -k a |egrep '^(Topics|Extensions|Commands):'
1737 $ hg help -e -k a |egrep '^(Topics|Extensions|Commands):'
1736 Extensions:
1738 Extensions:
1737 $ hg help -e -c -k date |egrep '^(Topics|Extensions|Commands):'
1739 $ hg help -e -c -k date |egrep '^(Topics|Extensions|Commands):'
1738 Extensions:
1740 Extensions:
1739 Commands:
1741 Commands:
1740 $ hg help -c commit > /dev/null
1742 $ hg help -c commit > /dev/null
1741 $ hg help -e -c commit > /dev/null
1743 $ hg help -e -c commit > /dev/null
1742 $ hg help -e commit
1744 $ hg help -e commit
1743 abort: no such help topic: commit
1745 abort: no such help topic: commit
1744 (try 'hg help --keyword commit')
1746 (try 'hg help --keyword commit')
1745 [10]
1747 [10]
1746
1748
1747 Test keyword search help
1749 Test keyword search help
1748
1750
1749 $ cat > prefixedname.py <<EOF
1751 $ cat > prefixedname.py <<EOF
1750 > '''matched against word "clone"
1752 > '''matched against word "clone"
1751 > '''
1753 > '''
1752 > EOF
1754 > EOF
1753 $ echo '[extensions]' >> $HGRCPATH
1755 $ echo '[extensions]' >> $HGRCPATH
1754 $ echo "dot.dot.prefixedname = `pwd`/prefixedname.py" >> $HGRCPATH
1756 $ echo "dot.dot.prefixedname = `pwd`/prefixedname.py" >> $HGRCPATH
1755 $ hg help -k clone
1757 $ hg help -k clone
1756 Topics:
1758 Topics:
1757
1759
1758 config Configuration Files
1760 config Configuration Files
1759 extensions Using Additional Features
1761 extensions Using Additional Features
1760 glossary Glossary
1762 glossary Glossary
1761 phases Working with Phases
1763 phases Working with Phases
1762 subrepos Subrepositories
1764 subrepos Subrepositories
1763 urls URL Paths
1765 urls URL Paths
1764
1766
1765 Commands:
1767 Commands:
1766
1768
1767 bookmarks create a new bookmark or list existing bookmarks
1769 bookmarks create a new bookmark or list existing bookmarks
1768 clone make a copy of an existing repository
1770 clone make a copy of an existing repository
1769 paths show aliases for remote repositories
1771 paths show aliases for remote repositories
1770 pull pull changes from the specified source
1772 pull pull changes from the specified source
1771 update update working directory (or switch revisions)
1773 update update working directory (or switch revisions)
1772
1774
1773 Extensions:
1775 Extensions:
1774
1776
1775 clonebundles advertise pre-generated bundles to seed clones
1777 clonebundles advertise pre-generated bundles to seed clones
1776 narrow create clones which fetch history data for subset of files
1778 narrow create clones which fetch history data for subset of files
1777 (EXPERIMENTAL)
1779 (EXPERIMENTAL)
1778 prefixedname matched against word "clone"
1780 prefixedname matched against word "clone"
1779 relink recreates hardlinks between repository clones
1781 relink recreates hardlinks between repository clones
1780
1782
1781 Extension Commands:
1783 Extension Commands:
1782
1784
1783 qclone clone main and patch repository at same time
1785 qclone clone main and patch repository at same time
1784
1786
1785 Test unfound topic
1787 Test unfound topic
1786
1788
1787 $ hg help nonexistingtopicthatwillneverexisteverever
1789 $ hg help nonexistingtopicthatwillneverexisteverever
1788 abort: no such help topic: nonexistingtopicthatwillneverexisteverever
1790 abort: no such help topic: nonexistingtopicthatwillneverexisteverever
1789 (try 'hg help --keyword nonexistingtopicthatwillneverexisteverever')
1791 (try 'hg help --keyword nonexistingtopicthatwillneverexisteverever')
1790 [10]
1792 [10]
1791
1793
1792 Test unfound keyword
1794 Test unfound keyword
1793
1795
1794 $ hg help --keyword nonexistingwordthatwillneverexisteverever
1796 $ hg help --keyword nonexistingwordthatwillneverexisteverever
1795 abort: no matches
1797 abort: no matches
1796 (try 'hg help' for a list of topics)
1798 (try 'hg help' for a list of topics)
1797 [10]
1799 [10]
1798
1800
1799 Test omit indicating for help
1801 Test omit indicating for help
1800
1802
1801 $ cat > addverboseitems.py <<EOF
1803 $ cat > addverboseitems.py <<EOF
1802 > r'''extension to test omit indicating.
1804 > r'''extension to test omit indicating.
1803 >
1805 >
1804 > This paragraph is never omitted (for extension)
1806 > This paragraph is never omitted (for extension)
1805 >
1807 >
1806 > .. container:: verbose
1808 > .. container:: verbose
1807 >
1809 >
1808 > This paragraph is omitted,
1810 > This paragraph is omitted,
1809 > if :hg:\`help\` is invoked without \`\`-v\`\` (for extension)
1811 > if :hg:\`help\` is invoked without \`\`-v\`\` (for extension)
1810 >
1812 >
1811 > This paragraph is never omitted, too (for extension)
1813 > This paragraph is never omitted, too (for extension)
1812 > '''
1814 > '''
1813 > from mercurial import commands, help
1815 > from mercurial import commands, help
1814 > testtopic = br"""This paragraph is never omitted (for topic).
1816 > testtopic = br"""This paragraph is never omitted (for topic).
1815 >
1817 >
1816 > .. container:: verbose
1818 > .. container:: verbose
1817 >
1819 >
1818 > This paragraph is omitted,
1820 > This paragraph is omitted,
1819 > if :hg:\`help\` is invoked without \`\`-v\`\` (for topic)
1821 > if :hg:\`help\` is invoked without \`\`-v\`\` (for topic)
1820 >
1822 >
1821 > This paragraph is never omitted, too (for topic)
1823 > This paragraph is never omitted, too (for topic)
1822 > """
1824 > """
1823 > def extsetup(ui):
1825 > def extsetup(ui):
1824 > help.helptable.append(([b"topic-containing-verbose"],
1826 > help.helptable.append(([b"topic-containing-verbose"],
1825 > b"This is the topic to test omit indicating.",
1827 > b"This is the topic to test omit indicating.",
1826 > lambda ui: testtopic))
1828 > lambda ui: testtopic))
1827 > EOF
1829 > EOF
1828 $ echo '[extensions]' >> $HGRCPATH
1830 $ echo '[extensions]' >> $HGRCPATH
1829 $ echo "addverboseitems = `pwd`/addverboseitems.py" >> $HGRCPATH
1831 $ echo "addverboseitems = `pwd`/addverboseitems.py" >> $HGRCPATH
1830 $ hg help addverboseitems
1832 $ hg help addverboseitems
1831 addverboseitems extension - extension to test omit indicating.
1833 addverboseitems extension - extension to test omit indicating.
1832
1834
1833 This paragraph is never omitted (for extension)
1835 This paragraph is never omitted (for extension)
1834
1836
1835 This paragraph is never omitted, too (for extension)
1837 This paragraph is never omitted, too (for extension)
1836
1838
1837 (some details hidden, use --verbose to show complete help)
1839 (some details hidden, use --verbose to show complete help)
1838
1840
1839 no commands defined
1841 no commands defined
1840 $ hg help -v addverboseitems
1842 $ hg help -v addverboseitems
1841 addverboseitems extension - extension to test omit indicating.
1843 addverboseitems extension - extension to test omit indicating.
1842
1844
1843 This paragraph is never omitted (for extension)
1845 This paragraph is never omitted (for extension)
1844
1846
1845 This paragraph is omitted, if 'hg help' is invoked without "-v" (for
1847 This paragraph is omitted, if 'hg help' is invoked without "-v" (for
1846 extension)
1848 extension)
1847
1849
1848 This paragraph is never omitted, too (for extension)
1850 This paragraph is never omitted, too (for extension)
1849
1851
1850 no commands defined
1852 no commands defined
1851 $ hg help topic-containing-verbose
1853 $ hg help topic-containing-verbose
1852 This is the topic to test omit indicating.
1854 This is the topic to test omit indicating.
1853 """"""""""""""""""""""""""""""""""""""""""
1855 """"""""""""""""""""""""""""""""""""""""""
1854
1856
1855 This paragraph is never omitted (for topic).
1857 This paragraph is never omitted (for topic).
1856
1858
1857 This paragraph is never omitted, too (for topic)
1859 This paragraph is never omitted, too (for topic)
1858
1860
1859 (some details hidden, use --verbose to show complete help)
1861 (some details hidden, use --verbose to show complete help)
1860 $ hg help -v topic-containing-verbose
1862 $ hg help -v topic-containing-verbose
1861 This is the topic to test omit indicating.
1863 This is the topic to test omit indicating.
1862 """"""""""""""""""""""""""""""""""""""""""
1864 """"""""""""""""""""""""""""""""""""""""""
1863
1865
1864 This paragraph is never omitted (for topic).
1866 This paragraph is never omitted (for topic).
1865
1867
1866 This paragraph is omitted, if 'hg help' is invoked without "-v" (for
1868 This paragraph is omitted, if 'hg help' is invoked without "-v" (for
1867 topic)
1869 topic)
1868
1870
1869 This paragraph is never omitted, too (for topic)
1871 This paragraph is never omitted, too (for topic)
1870
1872
1871 Test section lookup
1873 Test section lookup
1872
1874
1873 $ hg help revset.merge
1875 $ hg help revset.merge
1874 "merge()"
1876 "merge()"
1875 Changeset is a merge changeset.
1877 Changeset is a merge changeset.
1876
1878
1877 $ hg help glossary.dag
1879 $ hg help glossary.dag
1878 DAG
1880 DAG
1879 The repository of changesets of a distributed version control system
1881 The repository of changesets of a distributed version control system
1880 (DVCS) can be described as a directed acyclic graph (DAG), consisting
1882 (DVCS) can be described as a directed acyclic graph (DAG), consisting
1881 of nodes and edges, where nodes correspond to changesets and edges
1883 of nodes and edges, where nodes correspond to changesets and edges
1882 imply a parent -> child relation. This graph can be visualized by
1884 imply a parent -> child relation. This graph can be visualized by
1883 graphical tools such as 'hg log --graph'. In Mercurial, the DAG is
1885 graphical tools such as 'hg log --graph'. In Mercurial, the DAG is
1884 limited by the requirement for children to have at most two parents.
1886 limited by the requirement for children to have at most two parents.
1885
1887
1886
1888
1887 $ hg help hgrc.paths
1889 $ hg help hgrc.paths
1888 "paths"
1890 "paths"
1889 -------
1891 -------
1890
1892
1891 Assigns symbolic names and behavior to repositories.
1893 Assigns symbolic names and behavior to repositories.
1892
1894
1893 Options are symbolic names defining the URL or directory that is the
1895 Options are symbolic names defining the URL or directory that is the
1894 location of the repository. Example:
1896 location of the repository. Example:
1895
1897
1896 [paths]
1898 [paths]
1897 my_server = https://example.com/my_repo
1899 my_server = https://example.com/my_repo
1898 local_path = /home/me/repo
1900 local_path = /home/me/repo
1899
1901
1900 These symbolic names can be used from the command line. To pull from
1902 These symbolic names can be used from the command line. To pull from
1901 "my_server": 'hg pull my_server'. To push to "local_path": 'hg push
1903 "my_server": 'hg pull my_server'. To push to "local_path": 'hg push
1902 local_path'. You can check 'hg help urls' for details about valid URLs.
1904 local_path'. You can check 'hg help urls' for details about valid URLs.
1903
1905
1904 Options containing colons (":") denote sub-options that can influence
1906 Options containing colons (":") denote sub-options that can influence
1905 behavior for that specific path. Example:
1907 behavior for that specific path. Example:
1906
1908
1907 [paths]
1909 [paths]
1908 my_server = https://example.com/my_path
1910 my_server = https://example.com/my_path
1909 my_server:pushurl = ssh://example.com/my_path
1911 my_server:pushurl = ssh://example.com/my_path
1910
1912
1911 Paths using the 'path://otherpath' scheme will inherit the sub-options
1913 Paths using the 'path://otherpath' scheme will inherit the sub-options
1912 value from the path they point to.
1914 value from the path they point to.
1913
1915
1914 The following sub-options can be defined:
1916 The following sub-options can be defined:
1915
1917
1916 "multi-urls"
1918 "multi-urls"
1917 A boolean option. When enabled the value of the '[paths]' entry will be
1919 A boolean option. When enabled the value of the '[paths]' entry will be
1918 parsed as a list and the alias will resolve to multiple destination. If
1920 parsed as a list and the alias will resolve to multiple destination. If
1919 some of the list entry use the 'path://' syntax, the suboption will be
1921 some of the list entry use the 'path://' syntax, the suboption will be
1920 inherited individually.
1922 inherited individually.
1921
1923
1922 "pushurl"
1924 "pushurl"
1923 The URL to use for push operations. If not defined, the location
1925 The URL to use for push operations. If not defined, the location
1924 defined by the path's main entry is used.
1926 defined by the path's main entry is used.
1925
1927
1926 "pushrev"
1928 "pushrev"
1927 A revset defining which revisions to push by default.
1929 A revset defining which revisions to push by default.
1928
1930
1929 When 'hg push' is executed without a "-r" argument, the revset defined
1931 When 'hg push' is executed without a "-r" argument, the revset defined
1930 by this sub-option is evaluated to determine what to push.
1932 by this sub-option is evaluated to determine what to push.
1931
1933
1932 For example, a value of "." will push the working directory's revision
1934 For example, a value of "." will push the working directory's revision
1933 by default.
1935 by default.
1934
1936
1935 Revsets specifying bookmarks will not result in the bookmark being
1937 Revsets specifying bookmarks will not result in the bookmark being
1936 pushed.
1938 pushed.
1937
1939
1938 "bookmarks.mode"
1940 "bookmarks.mode"
1939 How bookmark will be dealt during the exchange. It support the following
1941 How bookmark will be dealt during the exchange. It support the following
1940 value
1942 value
1941
1943
1942 - "default": the default behavior, local and remote bookmarks are
1944 - "default": the default behavior, local and remote bookmarks are
1943 "merged" on push/pull.
1945 "merged" on push/pull.
1944 - "mirror": when pulling, replace local bookmarks by remote bookmarks.
1946 - "mirror": when pulling, replace local bookmarks by remote bookmarks.
1945 This is useful to replicate a repository, or as an optimization.
1947 This is useful to replicate a repository, or as an optimization.
1946 - "ignore": ignore bookmarks during exchange. (This currently only
1948 - "ignore": ignore bookmarks during exchange. (This currently only
1947 affect pulling)
1949 affect pulling)
1948
1950
1949 The following special named paths exist:
1951 The following special named paths exist:
1950
1952
1951 "default"
1953 "default"
1952 The URL or directory to use when no source or remote is specified.
1954 The URL or directory to use when no source or remote is specified.
1953
1955
1954 'hg clone' will automatically define this path to the location the
1956 'hg clone' will automatically define this path to the location the
1955 repository was cloned from.
1957 repository was cloned from.
1956
1958
1957 "default-push"
1959 "default-push"
1958 (deprecated) The URL or directory for the default 'hg push' location.
1960 (deprecated) The URL or directory for the default 'hg push' location.
1959 "default:pushurl" should be used instead.
1961 "default:pushurl" should be used instead.
1960
1962
1961 $ hg help glossary.mcguffin
1963 $ hg help glossary.mcguffin
1962 abort: help section not found: glossary.mcguffin
1964 abort: help section not found: glossary.mcguffin
1963 [10]
1965 [10]
1964
1966
1965 $ hg help glossary.mc.guffin
1967 $ hg help glossary.mc.guffin
1966 abort: help section not found: glossary.mc.guffin
1968 abort: help section not found: glossary.mc.guffin
1967 [10]
1969 [10]
1968
1970
1969 $ hg help template.files
1971 $ hg help template.files
1970 files List of strings. All files modified, added, or removed by
1972 files List of strings. All files modified, added, or removed by
1971 this changeset.
1973 this changeset.
1972 files(pattern)
1974 files(pattern)
1973 All files of the current changeset matching the pattern. See
1975 All files of the current changeset matching the pattern. See
1974 'hg help patterns'.
1976 'hg help patterns'.
1975
1977
1976 Test section lookup by translated message
1978 Test section lookup by translated message
1977
1979
1978 str.lower() instead of encoding.lower(str) on translated message might
1980 str.lower() instead of encoding.lower(str) on translated message might
1979 make message meaningless, because some encoding uses 0x41(A) - 0x5a(Z)
1981 make message meaningless, because some encoding uses 0x41(A) - 0x5a(Z)
1980 as the second or later byte of multi-byte character.
1982 as the second or later byte of multi-byte character.
1981
1983
1982 For example, "\x8bL\x98^" (translation of "record" in ja_JP.cp932)
1984 For example, "\x8bL\x98^" (translation of "record" in ja_JP.cp932)
1983 contains 0x4c (L). str.lower() replaces 0x4c(L) by 0x6c(l) and this
1985 contains 0x4c (L). str.lower() replaces 0x4c(L) by 0x6c(l) and this
1984 replacement makes message meaningless.
1986 replacement makes message meaningless.
1985
1987
1986 This tests that section lookup by translated string isn't broken by
1988 This tests that section lookup by translated string isn't broken by
1987 such str.lower().
1989 such str.lower().
1988
1990
1989 $ "$PYTHON" <<EOF
1991 $ "$PYTHON" <<EOF
1990 > def escape(s):
1992 > def escape(s):
1991 > return b''.join(br'\\u%x' % ord(uc) for uc in s.decode('cp932'))
1993 > return b''.join(br'\\u%x' % ord(uc) for uc in s.decode('cp932'))
1992 > # translation of "record" in ja_JP.cp932
1994 > # translation of "record" in ja_JP.cp932
1993 > upper = b"\x8bL\x98^"
1995 > upper = b"\x8bL\x98^"
1994 > # str.lower()-ed section name should be treated as different one
1996 > # str.lower()-ed section name should be treated as different one
1995 > lower = b"\x8bl\x98^"
1997 > lower = b"\x8bl\x98^"
1996 > with open('ambiguous.py', 'wb') as fp:
1998 > with open('ambiguous.py', 'wb') as fp:
1997 > fp.write(b"""# ambiguous section names in ja_JP.cp932
1999 > fp.write(b"""# ambiguous section names in ja_JP.cp932
1998 > u'''summary of extension
2000 > u'''summary of extension
1999 >
2001 >
2000 > %s
2002 > %s
2001 > ----
2003 > ----
2002 >
2004 >
2003 > Upper name should show only this message
2005 > Upper name should show only this message
2004 >
2006 >
2005 > %s
2007 > %s
2006 > ----
2008 > ----
2007 >
2009 >
2008 > Lower name should show only this message
2010 > Lower name should show only this message
2009 >
2011 >
2010 > subsequent section
2012 > subsequent section
2011 > ------------------
2013 > ------------------
2012 >
2014 >
2013 > This should be hidden at 'hg help ambiguous' with section name.
2015 > This should be hidden at 'hg help ambiguous' with section name.
2014 > '''
2016 > '''
2015 > """ % (escape(upper), escape(lower)))
2017 > """ % (escape(upper), escape(lower)))
2016 > EOF
2018 > EOF
2017
2019
2018 $ cat >> $HGRCPATH <<EOF
2020 $ cat >> $HGRCPATH <<EOF
2019 > [extensions]
2021 > [extensions]
2020 > ambiguous = ./ambiguous.py
2022 > ambiguous = ./ambiguous.py
2021 > EOF
2023 > EOF
2022
2024
2023 $ "$PYTHON" <<EOF | sh
2025 $ "$PYTHON" <<EOF | sh
2024 > from mercurial.utils import procutil
2026 > from mercurial.utils import procutil
2025 > upper = b"\x8bL\x98^"
2027 > upper = b"\x8bL\x98^"
2026 > procutil.stdout.write(b"hg --encoding cp932 help -e ambiguous.%s\n" % upper)
2028 > procutil.stdout.write(b"hg --encoding cp932 help -e ambiguous.%s\n" % upper)
2027 > EOF
2029 > EOF
2028 \x8bL\x98^ (esc)
2030 \x8bL\x98^ (esc)
2029 ----
2031 ----
2030
2032
2031 Upper name should show only this message
2033 Upper name should show only this message
2032
2034
2033
2035
2034 $ "$PYTHON" <<EOF | sh
2036 $ "$PYTHON" <<EOF | sh
2035 > from mercurial.utils import procutil
2037 > from mercurial.utils import procutil
2036 > lower = b"\x8bl\x98^"
2038 > lower = b"\x8bl\x98^"
2037 > procutil.stdout.write(b"hg --encoding cp932 help -e ambiguous.%s\n" % lower)
2039 > procutil.stdout.write(b"hg --encoding cp932 help -e ambiguous.%s\n" % lower)
2038 > EOF
2040 > EOF
2039 \x8bl\x98^ (esc)
2041 \x8bl\x98^ (esc)
2040 ----
2042 ----
2041
2043
2042 Lower name should show only this message
2044 Lower name should show only this message
2043
2045
2044
2046
2045 $ cat >> $HGRCPATH <<EOF
2047 $ cat >> $HGRCPATH <<EOF
2046 > [extensions]
2048 > [extensions]
2047 > ambiguous = !
2049 > ambiguous = !
2048 > EOF
2050 > EOF
2049
2051
2050 Show help content of disabled extensions
2052 Show help content of disabled extensions
2051
2053
2052 $ cat >> $HGRCPATH <<EOF
2054 $ cat >> $HGRCPATH <<EOF
2053 > [extensions]
2055 > [extensions]
2054 > ambiguous = !./ambiguous.py
2056 > ambiguous = !./ambiguous.py
2055 > EOF
2057 > EOF
2056 $ hg help -e ambiguous
2058 $ hg help -e ambiguous
2057 ambiguous extension - (no help text available)
2059 ambiguous extension - (no help text available)
2058
2060
2059 (use 'hg help extensions' for information on enabling extensions)
2061 (use 'hg help extensions' for information on enabling extensions)
2060
2062
2061 Test dynamic list of merge tools only shows up once
2063 Test dynamic list of merge tools only shows up once
2062 $ hg help merge-tools
2064 $ hg help merge-tools
2063 Merge Tools
2065 Merge Tools
2064 """""""""""
2066 """""""""""
2065
2067
2066 To merge files Mercurial uses merge tools.
2068 To merge files Mercurial uses merge tools.
2067
2069
2068 A merge tool combines two different versions of a file into a merged file.
2070 A merge tool combines two different versions of a file into a merged file.
2069 Merge tools are given the two files and the greatest common ancestor of
2071 Merge tools are given the two files and the greatest common ancestor of
2070 the two file versions, so they can determine the changes made on both
2072 the two file versions, so they can determine the changes made on both
2071 branches.
2073 branches.
2072
2074
2073 Merge tools are used both for 'hg resolve', 'hg merge', 'hg update', 'hg
2075 Merge tools are used both for 'hg resolve', 'hg merge', 'hg update', 'hg
2074 backout' and in several extensions.
2076 backout' and in several extensions.
2075
2077
2076 Usually, the merge tool tries to automatically reconcile the files by
2078 Usually, the merge tool tries to automatically reconcile the files by
2077 combining all non-overlapping changes that occurred separately in the two
2079 combining all non-overlapping changes that occurred separately in the two
2078 different evolutions of the same initial base file. Furthermore, some
2080 different evolutions of the same initial base file. Furthermore, some
2079 interactive merge programs make it easier to manually resolve conflicting
2081 interactive merge programs make it easier to manually resolve conflicting
2080 merges, either in a graphical way, or by inserting some conflict markers.
2082 merges, either in a graphical way, or by inserting some conflict markers.
2081 Mercurial does not include any interactive merge programs but relies on
2083 Mercurial does not include any interactive merge programs but relies on
2082 external tools for that.
2084 external tools for that.
2083
2085
2084 Available merge tools
2086 Available merge tools
2085 =====================
2087 =====================
2086
2088
2087 External merge tools and their properties are configured in the merge-
2089 External merge tools and their properties are configured in the merge-
2088 tools configuration section - see hgrc(5) - but they can often just be
2090 tools configuration section - see hgrc(5) - but they can often just be
2089 named by their executable.
2091 named by their executable.
2090
2092
2091 A merge tool is generally usable if its executable can be found on the
2093 A merge tool is generally usable if its executable can be found on the
2092 system and if it can handle the merge. The executable is found if it is an
2094 system and if it can handle the merge. The executable is found if it is an
2093 absolute or relative executable path or the name of an application in the
2095 absolute or relative executable path or the name of an application in the
2094 executable search path. The tool is assumed to be able to handle the merge
2096 executable search path. The tool is assumed to be able to handle the merge
2095 if it can handle symlinks if the file is a symlink, if it can handle
2097 if it can handle symlinks if the file is a symlink, if it can handle
2096 binary files if the file is binary, and if a GUI is available if the tool
2098 binary files if the file is binary, and if a GUI is available if the tool
2097 requires a GUI.
2099 requires a GUI.
2098
2100
2099 There are some internal merge tools which can be used. The internal merge
2101 There are some internal merge tools which can be used. The internal merge
2100 tools are:
2102 tools are:
2101
2103
2102 ":dump"
2104 ":dump"
2103 Creates three versions of the files to merge, containing the contents of
2105 Creates three versions of the files to merge, containing the contents of
2104 local, other and base. These files can then be used to perform a merge
2106 local, other and base. These files can then be used to perform a merge
2105 manually. If the file to be merged is named "a.txt", these files will
2107 manually. If the file to be merged is named "a.txt", these files will
2106 accordingly be named "a.txt.local", "a.txt.other" and "a.txt.base" and
2108 accordingly be named "a.txt.local", "a.txt.other" and "a.txt.base" and
2107 they will be placed in the same directory as "a.txt".
2109 they will be placed in the same directory as "a.txt".
2108
2110
2109 This implies premerge. Therefore, files aren't dumped, if premerge runs
2111 This implies premerge. Therefore, files aren't dumped, if premerge runs
2110 successfully. Use :forcedump to forcibly write files out.
2112 successfully. Use :forcedump to forcibly write files out.
2111
2113
2112 (actual capabilities: binary, symlink)
2114 (actual capabilities: binary, symlink)
2113
2115
2114 ":fail"
2116 ":fail"
2115 Rather than attempting to merge files that were modified on both
2117 Rather than attempting to merge files that were modified on both
2116 branches, it marks them as unresolved. The resolve command must be used
2118 branches, it marks them as unresolved. The resolve command must be used
2117 to resolve these conflicts.
2119 to resolve these conflicts.
2118
2120
2119 (actual capabilities: binary, symlink)
2121 (actual capabilities: binary, symlink)
2120
2122
2121 ":forcedump"
2123 ":forcedump"
2122 Creates three versions of the files as same as :dump, but omits
2124 Creates three versions of the files as same as :dump, but omits
2123 premerge.
2125 premerge.
2124
2126
2125 (actual capabilities: binary, symlink)
2127 (actual capabilities: binary, symlink)
2126
2128
2127 ":local"
2129 ":local"
2128 Uses the local 'p1()' version of files as the merged version.
2130 Uses the local 'p1()' version of files as the merged version.
2129
2131
2130 (actual capabilities: binary, symlink)
2132 (actual capabilities: binary, symlink)
2131
2133
2132 ":merge"
2134 ":merge"
2133 Uses the internal non-interactive simple merge algorithm for merging
2135 Uses the internal non-interactive simple merge algorithm for merging
2134 files. It will fail if there are any conflicts and leave markers in the
2136 files. It will fail if there are any conflicts and leave markers in the
2135 partially merged file. Markers will have two sections, one for each side
2137 partially merged file. Markers will have two sections, one for each side
2136 of merge.
2138 of merge.
2137
2139
2138 ":merge-local"
2140 ":merge-local"
2139 Like :merge, but resolve all conflicts non-interactively in favor of the
2141 Like :merge, but resolve all conflicts non-interactively in favor of the
2140 local 'p1()' changes.
2142 local 'p1()' changes.
2141
2143
2142 ":merge-other"
2144 ":merge-other"
2143 Like :merge, but resolve all conflicts non-interactively in favor of the
2145 Like :merge, but resolve all conflicts non-interactively in favor of the
2144 other 'p2()' changes.
2146 other 'p2()' changes.
2145
2147
2146 ":merge3"
2148 ":merge3"
2147 Uses the internal non-interactive simple merge algorithm for merging
2149 Uses the internal non-interactive simple merge algorithm for merging
2148 files. It will fail if there are any conflicts and leave markers in the
2150 files. It will fail if there are any conflicts and leave markers in the
2149 partially merged file. Marker will have three sections, one from each
2151 partially merged file. Marker will have three sections, one from each
2150 side of the merge and one for the base content.
2152 side of the merge and one for the base content.
2151
2153
2152 ":mergediff"
2154 ":mergediff"
2153 Uses the internal non-interactive simple merge algorithm for merging
2155 Uses the internal non-interactive simple merge algorithm for merging
2154 files. It will fail if there are any conflicts and leave markers in the
2156 files. It will fail if there are any conflicts and leave markers in the
2155 partially merged file. The marker will have two sections, one with the
2157 partially merged file. The marker will have two sections, one with the
2156 content from one side of the merge, and one with a diff from the base
2158 content from one side of the merge, and one with a diff from the base
2157 content to the content on the other side. (experimental)
2159 content to the content on the other side. (experimental)
2158
2160
2159 ":other"
2161 ":other"
2160 Uses the other 'p2()' version of files as the merged version.
2162 Uses the other 'p2()' version of files as the merged version.
2161
2163
2162 (actual capabilities: binary, symlink)
2164 (actual capabilities: binary, symlink)
2163
2165
2164 ":prompt"
2166 ":prompt"
2165 Asks the user which of the local 'p1()' or the other 'p2()' version to
2167 Asks the user which of the local 'p1()' or the other 'p2()' version to
2166 keep as the merged version.
2168 keep as the merged version.
2167
2169
2168 (actual capabilities: binary, symlink)
2170 (actual capabilities: binary, symlink)
2169
2171
2170 ":tagmerge"
2172 ":tagmerge"
2171 Uses the internal tag merge algorithm (experimental).
2173 Uses the internal tag merge algorithm (experimental).
2172
2174
2173 ":union"
2175 ":union"
2174 Uses the internal non-interactive simple merge algorithm for merging
2176 Uses the internal non-interactive simple merge algorithm for merging
2175 files. It will use both local and other sides for conflict regions by
2177 files. It will use both local and other sides for conflict regions by
2176 adding local on top of other. No markers are inserted.
2178 adding local on top of other. No markers are inserted.
2177
2179
2178 ":union-other-first"
2180 ":union-other-first"
2179 Like :union, but add other on top of local.
2181 Like :union, but add other on top of local.
2180
2182
2181 Internal tools are always available and do not require a GUI but will by
2183 Internal tools are always available and do not require a GUI but will by
2182 default not handle symlinks or binary files. See next section for detail
2184 default not handle symlinks or binary files. See next section for detail
2183 about "actual capabilities" described above.
2185 about "actual capabilities" described above.
2184
2186
2185 Choosing a merge tool
2187 Choosing a merge tool
2186 =====================
2188 =====================
2187
2189
2188 Mercurial uses these rules when deciding which merge tool to use:
2190 Mercurial uses these rules when deciding which merge tool to use:
2189
2191
2190 1. If a tool has been specified with the --tool option to merge or
2192 1. If a tool has been specified with the --tool option to merge or
2191 resolve, it is used. If it is the name of a tool in the merge-tools
2193 resolve, it is used. If it is the name of a tool in the merge-tools
2192 configuration, its configuration is used. Otherwise the specified tool
2194 configuration, its configuration is used. Otherwise the specified tool
2193 must be executable by the shell.
2195 must be executable by the shell.
2194 2. If the "HGMERGE" environment variable is present, its value is used and
2196 2. If the "HGMERGE" environment variable is present, its value is used and
2195 must be executable by the shell.
2197 must be executable by the shell.
2196 3. If the filename of the file to be merged matches any of the patterns in
2198 3. If the filename of the file to be merged matches any of the patterns in
2197 the merge-patterns configuration section, the first usable merge tool
2199 the merge-patterns configuration section, the first usable merge tool
2198 corresponding to a matching pattern is used.
2200 corresponding to a matching pattern is used.
2199 4. If ui.merge is set it will be considered next. If the value is not the
2201 4. If ui.merge is set it will be considered next. If the value is not the
2200 name of a configured tool, the specified value is used and must be
2202 name of a configured tool, the specified value is used and must be
2201 executable by the shell. Otherwise the named tool is used if it is
2203 executable by the shell. Otherwise the named tool is used if it is
2202 usable.
2204 usable.
2203 5. If any usable merge tools are present in the merge-tools configuration
2205 5. If any usable merge tools are present in the merge-tools configuration
2204 section, the one with the highest priority is used.
2206 section, the one with the highest priority is used.
2205 6. If a program named "hgmerge" can be found on the system, it is used -
2207 6. If a program named "hgmerge" can be found on the system, it is used -
2206 but it will by default not be used for symlinks and binary files.
2208 but it will by default not be used for symlinks and binary files.
2207 7. If the file to be merged is not binary and is not a symlink, then
2209 7. If the file to be merged is not binary and is not a symlink, then
2208 internal ":merge" is used.
2210 internal ":merge" is used.
2209 8. Otherwise, ":prompt" is used.
2211 8. Otherwise, ":prompt" is used.
2210
2212
2211 For historical reason, Mercurial treats merge tools as below while
2213 For historical reason, Mercurial treats merge tools as below while
2212 examining rules above.
2214 examining rules above.
2213
2215
2214 step specified via binary symlink
2216 step specified via binary symlink
2215 ----------------------------------
2217 ----------------------------------
2216 1. --tool o/o o/o
2218 1. --tool o/o o/o
2217 2. HGMERGE o/o o/o
2219 2. HGMERGE o/o o/o
2218 3. merge-patterns o/o(*) x/?(*)
2220 3. merge-patterns o/o(*) x/?(*)
2219 4. ui.merge x/?(*) x/?(*)
2221 4. ui.merge x/?(*) x/?(*)
2220
2222
2221 Each capability column indicates Mercurial behavior for internal/external
2223 Each capability column indicates Mercurial behavior for internal/external
2222 merge tools at examining each rule.
2224 merge tools at examining each rule.
2223
2225
2224 - "o": "assume that a tool has capability"
2226 - "o": "assume that a tool has capability"
2225 - "x": "assume that a tool does not have capability"
2227 - "x": "assume that a tool does not have capability"
2226 - "?": "check actual capability of a tool"
2228 - "?": "check actual capability of a tool"
2227
2229
2228 If "merge.strict-capability-check" configuration is true, Mercurial checks
2230 If "merge.strict-capability-check" configuration is true, Mercurial checks
2229 capabilities of merge tools strictly in (*) cases above (= each capability
2231 capabilities of merge tools strictly in (*) cases above (= each capability
2230 column becomes "?/?"). It is false by default for backward compatibility.
2232 column becomes "?/?"). It is false by default for backward compatibility.
2231
2233
2232 Note:
2234 Note:
2233 After selecting a merge program, Mercurial will by default attempt to
2235 After selecting a merge program, Mercurial will by default attempt to
2234 merge the files using a simple merge algorithm first. Only if it
2236 merge the files using a simple merge algorithm first. Only if it
2235 doesn't succeed because of conflicting changes will Mercurial actually
2237 doesn't succeed because of conflicting changes will Mercurial actually
2236 execute the merge program. Whether to use the simple merge algorithm
2238 execute the merge program. Whether to use the simple merge algorithm
2237 first can be controlled by the premerge setting of the merge tool.
2239 first can be controlled by the premerge setting of the merge tool.
2238 Premerge is enabled by default unless the file is binary or a symlink.
2240 Premerge is enabled by default unless the file is binary or a symlink.
2239
2241
2240 See the merge-tools and ui sections of hgrc(5) for details on the
2242 See the merge-tools and ui sections of hgrc(5) for details on the
2241 configuration of merge tools.
2243 configuration of merge tools.
2242
2244
2243 Compression engines listed in `hg help bundlespec`
2245 Compression engines listed in `hg help bundlespec`
2244
2246
2245 $ hg help bundlespec | grep gzip
2247 $ hg help bundlespec | grep gzip
2246 "v1" bundles can only use the "gzip", "bzip2", and "none" compression
2248 "v1" bundles can only use the "gzip", "bzip2", and "none" compression
2247 An algorithm that produces smaller bundles than "gzip".
2249 An algorithm that produces smaller bundles than "gzip".
2248 This engine will likely produce smaller bundles than "gzip" but will be
2250 This engine will likely produce smaller bundles than "gzip" but will be
2249 "gzip"
2251 "gzip"
2250 better compression than "gzip". It also frequently yields better (?)
2252 better compression than "gzip". It also frequently yields better (?)
2251
2253
2252 Test usage of section marks in help documents
2254 Test usage of section marks in help documents
2253
2255
2254 $ cd "$TESTDIR"/../doc
2256 $ cd "$TESTDIR"/../doc
2255 $ "$PYTHON" check-seclevel.py
2257 $ "$PYTHON" check-seclevel.py
2256 $ cd $TESTTMP
2258 $ cd $TESTTMP
2257
2259
2258 #if serve
2260 #if serve
2259
2261
2260 Test the help pages in hgweb.
2262 Test the help pages in hgweb.
2261
2263
2262 Dish up an empty repo; serve it cold.
2264 Dish up an empty repo; serve it cold.
2263
2265
2264 $ hg init "$TESTTMP/test"
2266 $ hg init "$TESTTMP/test"
2265 $ hg serve -R "$TESTTMP/test" -n test -p $HGPORT -d --pid-file=hg.pid
2267 $ hg serve -R "$TESTTMP/test" -n test -p $HGPORT -d --pid-file=hg.pid
2266 $ cat hg.pid >> $DAEMON_PIDS
2268 $ cat hg.pid >> $DAEMON_PIDS
2267
2269
2268 $ get-with-headers.py $LOCALIP:$HGPORT "help"
2270 $ get-with-headers.py $LOCALIP:$HGPORT "help"
2269 200 Script output follows
2271 200 Script output follows
2270
2272
2271 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2273 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2272 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
2274 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
2273 <head>
2275 <head>
2274 <link rel="icon" href="/static/hgicon.png" type="image/png" />
2276 <link rel="icon" href="/static/hgicon.png" type="image/png" />
2275 <meta name="robots" content="index, nofollow" />
2277 <meta name="robots" content="index, nofollow" />
2276 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
2278 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
2277 <script type="text/javascript" src="/static/mercurial.js"></script>
2279 <script type="text/javascript" src="/static/mercurial.js"></script>
2278
2280
2279 <title>Help: Index</title>
2281 <title>Help: Index</title>
2280 </head>
2282 </head>
2281 <body>
2283 <body>
2282
2284
2283 <div class="container">
2285 <div class="container">
2284 <div class="menu">
2286 <div class="menu">
2285 <div class="logo">
2287 <div class="logo">
2286 <a href="https://mercurial-scm.org/">
2288 <a href="https://mercurial-scm.org/">
2287 <img src="/static/hglogo.png" alt="mercurial" /></a>
2289 <img src="/static/hglogo.png" alt="mercurial" /></a>
2288 </div>
2290 </div>
2289 <ul>
2291 <ul>
2290 <li><a href="/shortlog">log</a></li>
2292 <li><a href="/shortlog">log</a></li>
2291 <li><a href="/graph">graph</a></li>
2293 <li><a href="/graph">graph</a></li>
2292 <li><a href="/tags">tags</a></li>
2294 <li><a href="/tags">tags</a></li>
2293 <li><a href="/bookmarks">bookmarks</a></li>
2295 <li><a href="/bookmarks">bookmarks</a></li>
2294 <li><a href="/branches">branches</a></li>
2296 <li><a href="/branches">branches</a></li>
2295 </ul>
2297 </ul>
2296 <ul>
2298 <ul>
2297 <li class="active">help</li>
2299 <li class="active">help</li>
2298 </ul>
2300 </ul>
2299 </div>
2301 </div>
2300
2302
2301 <div class="main">
2303 <div class="main">
2302 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
2304 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
2303
2305
2304 <form class="search" action="/log">
2306 <form class="search" action="/log">
2305
2307
2306 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
2308 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
2307 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
2309 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
2308 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
2310 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
2309 </form>
2311 </form>
2310 <table class="bigtable">
2312 <table class="bigtable">
2311 <tr><td colspan="2"><h2><a name="topics" href="#topics">Topics</a></h2></td></tr>
2313 <tr><td colspan="2"><h2><a name="topics" href="#topics">Topics</a></h2></td></tr>
2312
2314
2313 <tr><td>
2315 <tr><td>
2314 <a href="/help/bundlespec">
2316 <a href="/help/bundlespec">
2315 bundlespec
2317 bundlespec
2316 </a>
2318 </a>
2317 </td><td>
2319 </td><td>
2318 Bundle File Formats
2320 Bundle File Formats
2319 </td></tr>
2321 </td></tr>
2320 <tr><td>
2322 <tr><td>
2321 <a href="/help/color">
2323 <a href="/help/color">
2322 color
2324 color
2323 </a>
2325 </a>
2324 </td><td>
2326 </td><td>
2325 Colorizing Outputs
2327 Colorizing Outputs
2326 </td></tr>
2328 </td></tr>
2327 <tr><td>
2329 <tr><td>
2328 <a href="/help/config">
2330 <a href="/help/config">
2329 config
2331 config
2330 </a>
2332 </a>
2331 </td><td>
2333 </td><td>
2332 Configuration Files
2334 Configuration Files
2333 </td></tr>
2335 </td></tr>
2334 <tr><td>
2336 <tr><td>
2335 <a href="/help/dates">
2337 <a href="/help/dates">
2336 dates
2338 dates
2337 </a>
2339 </a>
2338 </td><td>
2340 </td><td>
2339 Date Formats
2341 Date Formats
2340 </td></tr>
2342 </td></tr>
2341 <tr><td>
2343 <tr><td>
2342 <a href="/help/deprecated">
2344 <a href="/help/deprecated">
2343 deprecated
2345 deprecated
2344 </a>
2346 </a>
2345 </td><td>
2347 </td><td>
2346 Deprecated Features
2348 Deprecated Features
2347 </td></tr>
2349 </td></tr>
2348 <tr><td>
2350 <tr><td>
2349 <a href="/help/diffs">
2351 <a href="/help/diffs">
2350 diffs
2352 diffs
2351 </a>
2353 </a>
2352 </td><td>
2354 </td><td>
2353 Diff Formats
2355 Diff Formats
2354 </td></tr>
2356 </td></tr>
2355 <tr><td>
2357 <tr><td>
2356 <a href="/help/environment">
2358 <a href="/help/environment">
2357 environment
2359 environment
2358 </a>
2360 </a>
2359 </td><td>
2361 </td><td>
2360 Environment Variables
2362 Environment Variables
2361 </td></tr>
2363 </td></tr>
2362 <tr><td>
2364 <tr><td>
2363 <a href="/help/evolution">
2365 <a href="/help/evolution">
2364 evolution
2366 evolution
2365 </a>
2367 </a>
2366 </td><td>
2368 </td><td>
2367 Safely rewriting history (EXPERIMENTAL)
2369 Safely rewriting history (EXPERIMENTAL)
2368 </td></tr>
2370 </td></tr>
2369 <tr><td>
2371 <tr><td>
2370 <a href="/help/extensions">
2372 <a href="/help/extensions">
2371 extensions
2373 extensions
2372 </a>
2374 </a>
2373 </td><td>
2375 </td><td>
2374 Using Additional Features
2376 Using Additional Features
2375 </td></tr>
2377 </td></tr>
2376 <tr><td>
2378 <tr><td>
2377 <a href="/help/filesets">
2379 <a href="/help/filesets">
2378 filesets
2380 filesets
2379 </a>
2381 </a>
2380 </td><td>
2382 </td><td>
2381 Specifying File Sets
2383 Specifying File Sets
2382 </td></tr>
2384 </td></tr>
2383 <tr><td>
2385 <tr><td>
2384 <a href="/help/flags">
2386 <a href="/help/flags">
2385 flags
2387 flags
2386 </a>
2388 </a>
2387 </td><td>
2389 </td><td>
2388 Command-line flags
2390 Command-line flags
2389 </td></tr>
2391 </td></tr>
2390 <tr><td>
2392 <tr><td>
2391 <a href="/help/glossary">
2393 <a href="/help/glossary">
2392 glossary
2394 glossary
2393 </a>
2395 </a>
2394 </td><td>
2396 </td><td>
2395 Glossary
2397 Glossary
2396 </td></tr>
2398 </td></tr>
2397 <tr><td>
2399 <tr><td>
2398 <a href="/help/hgignore">
2400 <a href="/help/hgignore">
2399 hgignore
2401 hgignore
2400 </a>
2402 </a>
2401 </td><td>
2403 </td><td>
2402 Syntax for Mercurial Ignore Files
2404 Syntax for Mercurial Ignore Files
2403 </td></tr>
2405 </td></tr>
2404 <tr><td>
2406 <tr><td>
2405 <a href="/help/hgweb">
2407 <a href="/help/hgweb">
2406 hgweb
2408 hgweb
2407 </a>
2409 </a>
2408 </td><td>
2410 </td><td>
2409 Configuring hgweb
2411 Configuring hgweb
2410 </td></tr>
2412 </td></tr>
2411 <tr><td>
2413 <tr><td>
2412 <a href="/help/internals">
2414 <a href="/help/internals">
2413 internals
2415 internals
2414 </a>
2416 </a>
2415 </td><td>
2417 </td><td>
2416 Technical implementation topics
2418 Technical implementation topics
2417 </td></tr>
2419 </td></tr>
2418 <tr><td>
2420 <tr><td>
2419 <a href="/help/merge-tools">
2421 <a href="/help/merge-tools">
2420 merge-tools
2422 merge-tools
2421 </a>
2423 </a>
2422 </td><td>
2424 </td><td>
2423 Merge Tools
2425 Merge Tools
2424 </td></tr>
2426 </td></tr>
2425 <tr><td>
2427 <tr><td>
2426 <a href="/help/pager">
2428 <a href="/help/pager">
2427 pager
2429 pager
2428 </a>
2430 </a>
2429 </td><td>
2431 </td><td>
2430 Pager Support
2432 Pager Support
2431 </td></tr>
2433 </td></tr>
2432 <tr><td>
2434 <tr><td>
2433 <a href="/help/patterns">
2435 <a href="/help/patterns">
2434 patterns
2436 patterns
2435 </a>
2437 </a>
2436 </td><td>
2438 </td><td>
2437 File Name Patterns
2439 File Name Patterns
2438 </td></tr>
2440 </td></tr>
2439 <tr><td>
2441 <tr><td>
2440 <a href="/help/phases">
2442 <a href="/help/phases">
2441 phases
2443 phases
2442 </a>
2444 </a>
2443 </td><td>
2445 </td><td>
2444 Working with Phases
2446 Working with Phases
2445 </td></tr>
2447 </td></tr>
2446 <tr><td>
2448 <tr><td>
2447 <a href="/help/revisions">
2449 <a href="/help/revisions">
2448 revisions
2450 revisions
2449 </a>
2451 </a>
2450 </td><td>
2452 </td><td>
2451 Specifying Revisions
2453 Specifying Revisions
2452 </td></tr>
2454 </td></tr>
2453 <tr><td>
2455 <tr><td>
2454 <a href="/help/rust">
2456 <a href="/help/rust">
2455 rust
2457 rust
2456 </a>
2458 </a>
2457 </td><td>
2459 </td><td>
2458 Rust in Mercurial
2460 Rust in Mercurial
2459 </td></tr>
2461 </td></tr>
2460 <tr><td>
2462 <tr><td>
2461 <a href="/help/scripting">
2463 <a href="/help/scripting">
2462 scripting
2464 scripting
2463 </a>
2465 </a>
2464 </td><td>
2466 </td><td>
2465 Using Mercurial from scripts and automation
2467 Using Mercurial from scripts and automation
2466 </td></tr>
2468 </td></tr>
2467 <tr><td>
2469 <tr><td>
2468 <a href="/help/subrepos">
2470 <a href="/help/subrepos">
2469 subrepos
2471 subrepos
2470 </a>
2472 </a>
2471 </td><td>
2473 </td><td>
2472 Subrepositories
2474 Subrepositories
2473 </td></tr>
2475 </td></tr>
2474 <tr><td>
2476 <tr><td>
2475 <a href="/help/templating">
2477 <a href="/help/templating">
2476 templating
2478 templating
2477 </a>
2479 </a>
2478 </td><td>
2480 </td><td>
2479 Template Usage
2481 Template Usage
2480 </td></tr>
2482 </td></tr>
2481 <tr><td>
2483 <tr><td>
2482 <a href="/help/urls">
2484 <a href="/help/urls">
2483 urls
2485 urls
2484 </a>
2486 </a>
2485 </td><td>
2487 </td><td>
2486 URL Paths
2488 URL Paths
2487 </td></tr>
2489 </td></tr>
2488 <tr><td>
2490 <tr><td>
2489 <a href="/help/topic-containing-verbose">
2491 <a href="/help/topic-containing-verbose">
2490 topic-containing-verbose
2492 topic-containing-verbose
2491 </a>
2493 </a>
2492 </td><td>
2494 </td><td>
2493 This is the topic to test omit indicating.
2495 This is the topic to test omit indicating.
2494 </td></tr>
2496 </td></tr>
2495
2497
2496
2498
2497 <tr><td colspan="2"><h2><a name="main" href="#main">Main Commands</a></h2></td></tr>
2499 <tr><td colspan="2"><h2><a name="main" href="#main">Main Commands</a></h2></td></tr>
2498
2500
2499 <tr><td>
2501 <tr><td>
2500 <a href="/help/abort">
2502 <a href="/help/abort">
2501 abort
2503 abort
2502 </a>
2504 </a>
2503 </td><td>
2505 </td><td>
2504 abort an unfinished operation (EXPERIMENTAL)
2506 abort an unfinished operation (EXPERIMENTAL)
2505 </td></tr>
2507 </td></tr>
2506 <tr><td>
2508 <tr><td>
2507 <a href="/help/add">
2509 <a href="/help/add">
2508 add
2510 add
2509 </a>
2511 </a>
2510 </td><td>
2512 </td><td>
2511 add the specified files on the next commit
2513 add the specified files on the next commit
2512 </td></tr>
2514 </td></tr>
2513 <tr><td>
2515 <tr><td>
2514 <a href="/help/annotate">
2516 <a href="/help/annotate">
2515 annotate
2517 annotate
2516 </a>
2518 </a>
2517 </td><td>
2519 </td><td>
2518 show changeset information by line for each file
2520 show changeset information by line for each file
2519 </td></tr>
2521 </td></tr>
2520 <tr><td>
2522 <tr><td>
2521 <a href="/help/clone">
2523 <a href="/help/clone">
2522 clone
2524 clone
2523 </a>
2525 </a>
2524 </td><td>
2526 </td><td>
2525 make a copy of an existing repository
2527 make a copy of an existing repository
2526 </td></tr>
2528 </td></tr>
2527 <tr><td>
2529 <tr><td>
2528 <a href="/help/commit">
2530 <a href="/help/commit">
2529 commit
2531 commit
2530 </a>
2532 </a>
2531 </td><td>
2533 </td><td>
2532 commit the specified files or all outstanding changes
2534 commit the specified files or all outstanding changes
2533 </td></tr>
2535 </td></tr>
2534 <tr><td>
2536 <tr><td>
2535 <a href="/help/continue">
2537 <a href="/help/continue">
2536 continue
2538 continue
2537 </a>
2539 </a>
2538 </td><td>
2540 </td><td>
2539 resumes an interrupted operation (EXPERIMENTAL)
2541 resumes an interrupted operation (EXPERIMENTAL)
2540 </td></tr>
2542 </td></tr>
2541 <tr><td>
2543 <tr><td>
2542 <a href="/help/diff">
2544 <a href="/help/diff">
2543 diff
2545 diff
2544 </a>
2546 </a>
2545 </td><td>
2547 </td><td>
2546 diff repository (or selected files)
2548 diff repository (or selected files)
2547 </td></tr>
2549 </td></tr>
2548 <tr><td>
2550 <tr><td>
2549 <a href="/help/export">
2551 <a href="/help/export">
2550 export
2552 export
2551 </a>
2553 </a>
2552 </td><td>
2554 </td><td>
2553 dump the header and diffs for one or more changesets
2555 dump the header and diffs for one or more changesets
2554 </td></tr>
2556 </td></tr>
2555 <tr><td>
2557 <tr><td>
2556 <a href="/help/forget">
2558 <a href="/help/forget">
2557 forget
2559 forget
2558 </a>
2560 </a>
2559 </td><td>
2561 </td><td>
2560 forget the specified files on the next commit
2562 forget the specified files on the next commit
2561 </td></tr>
2563 </td></tr>
2562 <tr><td>
2564 <tr><td>
2563 <a href="/help/init">
2565 <a href="/help/init">
2564 init
2566 init
2565 </a>
2567 </a>
2566 </td><td>
2568 </td><td>
2567 create a new repository in the given directory
2569 create a new repository in the given directory
2568 </td></tr>
2570 </td></tr>
2569 <tr><td>
2571 <tr><td>
2570 <a href="/help/log">
2572 <a href="/help/log">
2571 log
2573 log
2572 </a>
2574 </a>
2573 </td><td>
2575 </td><td>
2574 show revision history of entire repository or files
2576 show revision history of entire repository or files
2575 </td></tr>
2577 </td></tr>
2576 <tr><td>
2578 <tr><td>
2577 <a href="/help/merge">
2579 <a href="/help/merge">
2578 merge
2580 merge
2579 </a>
2581 </a>
2580 </td><td>
2582 </td><td>
2581 merge another revision into working directory
2583 merge another revision into working directory
2582 </td></tr>
2584 </td></tr>
2583 <tr><td>
2585 <tr><td>
2584 <a href="/help/pull">
2586 <a href="/help/pull">
2585 pull
2587 pull
2586 </a>
2588 </a>
2587 </td><td>
2589 </td><td>
2588 pull changes from the specified source
2590 pull changes from the specified source
2589 </td></tr>
2591 </td></tr>
2590 <tr><td>
2592 <tr><td>
2591 <a href="/help/push">
2593 <a href="/help/push">
2592 push
2594 push
2593 </a>
2595 </a>
2594 </td><td>
2596 </td><td>
2595 push changes to the specified destination
2597 push changes to the specified destination
2596 </td></tr>
2598 </td></tr>
2597 <tr><td>
2599 <tr><td>
2598 <a href="/help/remove">
2600 <a href="/help/remove">
2599 remove
2601 remove
2600 </a>
2602 </a>
2601 </td><td>
2603 </td><td>
2602 remove the specified files on the next commit
2604 remove the specified files on the next commit
2603 </td></tr>
2605 </td></tr>
2604 <tr><td>
2606 <tr><td>
2605 <a href="/help/serve">
2607 <a href="/help/serve">
2606 serve
2608 serve
2607 </a>
2609 </a>
2608 </td><td>
2610 </td><td>
2609 start stand-alone webserver
2611 start stand-alone webserver
2610 </td></tr>
2612 </td></tr>
2611 <tr><td>
2613 <tr><td>
2612 <a href="/help/status">
2614 <a href="/help/status">
2613 status
2615 status
2614 </a>
2616 </a>
2615 </td><td>
2617 </td><td>
2616 show changed files in the working directory
2618 show changed files in the working directory
2617 </td></tr>
2619 </td></tr>
2618 <tr><td>
2620 <tr><td>
2619 <a href="/help/summary">
2621 <a href="/help/summary">
2620 summary
2622 summary
2621 </a>
2623 </a>
2622 </td><td>
2624 </td><td>
2623 summarize working directory state
2625 summarize working directory state
2624 </td></tr>
2626 </td></tr>
2625 <tr><td>
2627 <tr><td>
2626 <a href="/help/update">
2628 <a href="/help/update">
2627 update
2629 update
2628 </a>
2630 </a>
2629 </td><td>
2631 </td><td>
2630 update working directory (or switch revisions)
2632 update working directory (or switch revisions)
2631 </td></tr>
2633 </td></tr>
2632
2634
2633
2635
2634
2636
2635 <tr><td colspan="2"><h2><a name="other" href="#other">Other Commands</a></h2></td></tr>
2637 <tr><td colspan="2"><h2><a name="other" href="#other">Other Commands</a></h2></td></tr>
2636
2638
2637 <tr><td>
2639 <tr><td>
2638 <a href="/help/addremove">
2640 <a href="/help/addremove">
2639 addremove
2641 addremove
2640 </a>
2642 </a>
2641 </td><td>
2643 </td><td>
2642 add all new files, delete all missing files
2644 add all new files, delete all missing files
2643 </td></tr>
2645 </td></tr>
2644 <tr><td>
2646 <tr><td>
2645 <a href="/help/archive">
2647 <a href="/help/archive">
2646 archive
2648 archive
2647 </a>
2649 </a>
2648 </td><td>
2650 </td><td>
2649 create an unversioned archive of a repository revision
2651 create an unversioned archive of a repository revision
2650 </td></tr>
2652 </td></tr>
2651 <tr><td>
2653 <tr><td>
2652 <a href="/help/backout">
2654 <a href="/help/backout">
2653 backout
2655 backout
2654 </a>
2656 </a>
2655 </td><td>
2657 </td><td>
2656 reverse effect of earlier changeset
2658 reverse effect of earlier changeset
2657 </td></tr>
2659 </td></tr>
2658 <tr><td>
2660 <tr><td>
2659 <a href="/help/bisect">
2661 <a href="/help/bisect">
2660 bisect
2662 bisect
2661 </a>
2663 </a>
2662 </td><td>
2664 </td><td>
2663 subdivision search of changesets
2665 subdivision search of changesets
2664 </td></tr>
2666 </td></tr>
2665 <tr><td>
2667 <tr><td>
2666 <a href="/help/bookmarks">
2668 <a href="/help/bookmarks">
2667 bookmarks
2669 bookmarks
2668 </a>
2670 </a>
2669 </td><td>
2671 </td><td>
2670 create a new bookmark or list existing bookmarks
2672 create a new bookmark or list existing bookmarks
2671 </td></tr>
2673 </td></tr>
2672 <tr><td>
2674 <tr><td>
2673 <a href="/help/branch">
2675 <a href="/help/branch">
2674 branch
2676 branch
2675 </a>
2677 </a>
2676 </td><td>
2678 </td><td>
2677 set or show the current branch name
2679 set or show the current branch name
2678 </td></tr>
2680 </td></tr>
2679 <tr><td>
2681 <tr><td>
2680 <a href="/help/branches">
2682 <a href="/help/branches">
2681 branches
2683 branches
2682 </a>
2684 </a>
2683 </td><td>
2685 </td><td>
2684 list repository named branches
2686 list repository named branches
2685 </td></tr>
2687 </td></tr>
2686 <tr><td>
2688 <tr><td>
2687 <a href="/help/bundle">
2689 <a href="/help/bundle">
2688 bundle
2690 bundle
2689 </a>
2691 </a>
2690 </td><td>
2692 </td><td>
2691 create a bundle file
2693 create a bundle file
2692 </td></tr>
2694 </td></tr>
2693 <tr><td>
2695 <tr><td>
2694 <a href="/help/cat">
2696 <a href="/help/cat">
2695 cat
2697 cat
2696 </a>
2698 </a>
2697 </td><td>
2699 </td><td>
2698 output the current or given revision of files
2700 output the current or given revision of files
2699 </td></tr>
2701 </td></tr>
2700 <tr><td>
2702 <tr><td>
2701 <a href="/help/config">
2703 <a href="/help/config">
2702 config
2704 config
2703 </a>
2705 </a>
2704 </td><td>
2706 </td><td>
2705 show combined config settings from all hgrc files
2707 show combined config settings from all hgrc files
2706 </td></tr>
2708 </td></tr>
2707 <tr><td>
2709 <tr><td>
2708 <a href="/help/copy">
2710 <a href="/help/copy">
2709 copy
2711 copy
2710 </a>
2712 </a>
2711 </td><td>
2713 </td><td>
2712 mark files as copied for the next commit
2714 mark files as copied for the next commit
2713 </td></tr>
2715 </td></tr>
2714 <tr><td>
2716 <tr><td>
2715 <a href="/help/files">
2717 <a href="/help/files">
2716 files
2718 files
2717 </a>
2719 </a>
2718 </td><td>
2720 </td><td>
2719 list tracked files
2721 list tracked files
2720 </td></tr>
2722 </td></tr>
2721 <tr><td>
2723 <tr><td>
2722 <a href="/help/graft">
2724 <a href="/help/graft">
2723 graft
2725 graft
2724 </a>
2726 </a>
2725 </td><td>
2727 </td><td>
2726 copy changes from other branches onto the current branch
2728 copy changes from other branches onto the current branch
2727 </td></tr>
2729 </td></tr>
2728 <tr><td>
2730 <tr><td>
2729 <a href="/help/grep">
2731 <a href="/help/grep">
2730 grep
2732 grep
2731 </a>
2733 </a>
2732 </td><td>
2734 </td><td>
2733 search for a pattern in specified files
2735 search for a pattern in specified files
2734 </td></tr>
2736 </td></tr>
2735 <tr><td>
2737 <tr><td>
2736 <a href="/help/hashelp">
2738 <a href="/help/hashelp">
2737 hashelp
2739 hashelp
2738 </a>
2740 </a>
2739 </td><td>
2741 </td><td>
2740 Extension command's help
2742 Extension command's help
2741 </td></tr>
2743 </td></tr>
2742 <tr><td>
2744 <tr><td>
2743 <a href="/help/heads">
2745 <a href="/help/heads">
2744 heads
2746 heads
2745 </a>
2747 </a>
2746 </td><td>
2748 </td><td>
2747 show branch heads
2749 show branch heads
2748 </td></tr>
2750 </td></tr>
2749 <tr><td>
2751 <tr><td>
2750 <a href="/help/help">
2752 <a href="/help/help">
2751 help
2753 help
2752 </a>
2754 </a>
2753 </td><td>
2755 </td><td>
2754 show help for a given topic or a help overview
2756 show help for a given topic or a help overview
2755 </td></tr>
2757 </td></tr>
2756 <tr><td>
2758 <tr><td>
2757 <a href="/help/hgalias">
2759 <a href="/help/hgalias">
2758 hgalias
2760 hgalias
2759 </a>
2761 </a>
2760 </td><td>
2762 </td><td>
2761 My doc
2763 My doc
2762 </td></tr>
2764 </td></tr>
2763 <tr><td>
2765 <tr><td>
2764 <a href="/help/hgaliasnodoc">
2766 <a href="/help/hgaliasnodoc">
2765 hgaliasnodoc
2767 hgaliasnodoc
2766 </a>
2768 </a>
2767 </td><td>
2769 </td><td>
2768 summarize working directory state
2770 summarize working directory state
2769 </td></tr>
2771 </td></tr>
2770 <tr><td>
2772 <tr><td>
2771 <a href="/help/identify">
2773 <a href="/help/identify">
2772 identify
2774 identify
2773 </a>
2775 </a>
2774 </td><td>
2776 </td><td>
2775 identify the working directory or specified revision
2777 identify the working directory or specified revision
2776 </td></tr>
2778 </td></tr>
2777 <tr><td>
2779 <tr><td>
2778 <a href="/help/import">
2780 <a href="/help/import">
2779 import
2781 import
2780 </a>
2782 </a>
2781 </td><td>
2783 </td><td>
2782 import an ordered set of patches
2784 import an ordered set of patches
2783 </td></tr>
2785 </td></tr>
2784 <tr><td>
2786 <tr><td>
2785 <a href="/help/incoming">
2787 <a href="/help/incoming">
2786 incoming
2788 incoming
2787 </a>
2789 </a>
2788 </td><td>
2790 </td><td>
2789 show new changesets found in source
2791 show new changesets found in source
2790 </td></tr>
2792 </td></tr>
2791 <tr><td>
2793 <tr><td>
2792 <a href="/help/manifest">
2794 <a href="/help/manifest">
2793 manifest
2795 manifest
2794 </a>
2796 </a>
2795 </td><td>
2797 </td><td>
2796 output the current or given revision of the project manifest
2798 output the current or given revision of the project manifest
2797 </td></tr>
2799 </td></tr>
2798 <tr><td>
2800 <tr><td>
2799 <a href="/help/nohelp">
2801 <a href="/help/nohelp">
2800 nohelp
2802 nohelp
2801 </a>
2803 </a>
2802 </td><td>
2804 </td><td>
2803 (no help text available)
2805 (no help text available)
2804 </td></tr>
2806 </td></tr>
2805 <tr><td>
2807 <tr><td>
2806 <a href="/help/outgoing">
2808 <a href="/help/outgoing">
2807 outgoing
2809 outgoing
2808 </a>
2810 </a>
2809 </td><td>
2811 </td><td>
2810 show changesets not found in the destination
2812 show changesets not found in the destination
2811 </td></tr>
2813 </td></tr>
2812 <tr><td>
2814 <tr><td>
2813 <a href="/help/paths">
2815 <a href="/help/paths">
2814 paths
2816 paths
2815 </a>
2817 </a>
2816 </td><td>
2818 </td><td>
2817 show aliases for remote repositories
2819 show aliases for remote repositories
2818 </td></tr>
2820 </td></tr>
2819 <tr><td>
2821 <tr><td>
2820 <a href="/help/phase">
2822 <a href="/help/phase">
2821 phase
2823 phase
2822 </a>
2824 </a>
2823 </td><td>
2825 </td><td>
2824 set or show the current phase name
2826 set or show the current phase name
2825 </td></tr>
2827 </td></tr>
2826 <tr><td>
2828 <tr><td>
2827 <a href="/help/purge">
2829 <a href="/help/purge">
2828 purge
2830 purge
2829 </a>
2831 </a>
2830 </td><td>
2832 </td><td>
2831 removes files not tracked by Mercurial
2833 removes files not tracked by Mercurial
2832 </td></tr>
2834 </td></tr>
2833 <tr><td>
2835 <tr><td>
2834 <a href="/help/recover">
2836 <a href="/help/recover">
2835 recover
2837 recover
2836 </a>
2838 </a>
2837 </td><td>
2839 </td><td>
2838 roll back an interrupted transaction
2840 roll back an interrupted transaction
2839 </td></tr>
2841 </td></tr>
2840 <tr><td>
2842 <tr><td>
2841 <a href="/help/rename">
2843 <a href="/help/rename">
2842 rename
2844 rename
2843 </a>
2845 </a>
2844 </td><td>
2846 </td><td>
2845 rename files; equivalent of copy + remove
2847 rename files; equivalent of copy + remove
2846 </td></tr>
2848 </td></tr>
2847 <tr><td>
2849 <tr><td>
2848 <a href="/help/resolve">
2850 <a href="/help/resolve">
2849 resolve
2851 resolve
2850 </a>
2852 </a>
2851 </td><td>
2853 </td><td>
2852 redo merges or set/view the merge status of files
2854 redo merges or set/view the merge status of files
2853 </td></tr>
2855 </td></tr>
2854 <tr><td>
2856 <tr><td>
2855 <a href="/help/revert">
2857 <a href="/help/revert">
2856 revert
2858 revert
2857 </a>
2859 </a>
2858 </td><td>
2860 </td><td>
2859 restore files to their checkout state
2861 restore files to their checkout state
2860 </td></tr>
2862 </td></tr>
2861 <tr><td>
2863 <tr><td>
2862 <a href="/help/root">
2864 <a href="/help/root">
2863 root
2865 root
2864 </a>
2866 </a>
2865 </td><td>
2867 </td><td>
2866 print the root (top) of the current working directory
2868 print the root (top) of the current working directory
2867 </td></tr>
2869 </td></tr>
2868 <tr><td>
2870 <tr><td>
2869 <a href="/help/shellalias">
2871 <a href="/help/shellalias">
2870 shellalias
2872 shellalias
2871 </a>
2873 </a>
2872 </td><td>
2874 </td><td>
2873 (no help text available)
2875 (no help text available)
2874 </td></tr>
2876 </td></tr>
2875 <tr><td>
2877 <tr><td>
2876 <a href="/help/shelve">
2878 <a href="/help/shelve">
2877 shelve
2879 shelve
2878 </a>
2880 </a>
2879 </td><td>
2881 </td><td>
2880 save and set aside changes from the working directory
2882 save and set aside changes from the working directory
2881 </td></tr>
2883 </td></tr>
2882 <tr><td>
2884 <tr><td>
2883 <a href="/help/tag">
2885 <a href="/help/tag">
2884 tag
2886 tag
2885 </a>
2887 </a>
2886 </td><td>
2888 </td><td>
2887 add one or more tags for the current or given revision
2889 add one or more tags for the current or given revision
2888 </td></tr>
2890 </td></tr>
2889 <tr><td>
2891 <tr><td>
2890 <a href="/help/tags">
2892 <a href="/help/tags">
2891 tags
2893 tags
2892 </a>
2894 </a>
2893 </td><td>
2895 </td><td>
2894 list repository tags
2896 list repository tags
2895 </td></tr>
2897 </td></tr>
2896 <tr><td>
2898 <tr><td>
2897 <a href="/help/unbundle">
2899 <a href="/help/unbundle">
2898 unbundle
2900 unbundle
2899 </a>
2901 </a>
2900 </td><td>
2902 </td><td>
2901 apply one or more bundle files
2903 apply one or more bundle files
2902 </td></tr>
2904 </td></tr>
2903 <tr><td>
2905 <tr><td>
2904 <a href="/help/unshelve">
2906 <a href="/help/unshelve">
2905 unshelve
2907 unshelve
2906 </a>
2908 </a>
2907 </td><td>
2909 </td><td>
2908 restore a shelved change to the working directory
2910 restore a shelved change to the working directory
2909 </td></tr>
2911 </td></tr>
2910 <tr><td>
2912 <tr><td>
2911 <a href="/help/verify">
2913 <a href="/help/verify">
2912 verify
2914 verify
2913 </a>
2915 </a>
2914 </td><td>
2916 </td><td>
2915 verify the integrity of the repository
2917 verify the integrity of the repository
2916 </td></tr>
2918 </td></tr>
2917 <tr><td>
2919 <tr><td>
2918 <a href="/help/version">
2920 <a href="/help/version">
2919 version
2921 version
2920 </a>
2922 </a>
2921 </td><td>
2923 </td><td>
2922 output version and copyright information
2924 output version and copyright information
2923 </td></tr>
2925 </td></tr>
2924
2926
2925
2927
2926 </table>
2928 </table>
2927 </div>
2929 </div>
2928 </div>
2930 </div>
2929
2931
2930
2932
2931
2933
2932 </body>
2934 </body>
2933 </html>
2935 </html>
2934
2936
2935
2937
2936 $ get-with-headers.py $LOCALIP:$HGPORT "help/add"
2938 $ get-with-headers.py $LOCALIP:$HGPORT "help/add"
2937 200 Script output follows
2939 200 Script output follows
2938
2940
2939 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2941 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
2940 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
2942 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
2941 <head>
2943 <head>
2942 <link rel="icon" href="/static/hgicon.png" type="image/png" />
2944 <link rel="icon" href="/static/hgicon.png" type="image/png" />
2943 <meta name="robots" content="index, nofollow" />
2945 <meta name="robots" content="index, nofollow" />
2944 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
2946 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
2945 <script type="text/javascript" src="/static/mercurial.js"></script>
2947 <script type="text/javascript" src="/static/mercurial.js"></script>
2946
2948
2947 <title>Help: add</title>
2949 <title>Help: add</title>
2948 </head>
2950 </head>
2949 <body>
2951 <body>
2950
2952
2951 <div class="container">
2953 <div class="container">
2952 <div class="menu">
2954 <div class="menu">
2953 <div class="logo">
2955 <div class="logo">
2954 <a href="https://mercurial-scm.org/">
2956 <a href="https://mercurial-scm.org/">
2955 <img src="/static/hglogo.png" alt="mercurial" /></a>
2957 <img src="/static/hglogo.png" alt="mercurial" /></a>
2956 </div>
2958 </div>
2957 <ul>
2959 <ul>
2958 <li><a href="/shortlog">log</a></li>
2960 <li><a href="/shortlog">log</a></li>
2959 <li><a href="/graph">graph</a></li>
2961 <li><a href="/graph">graph</a></li>
2960 <li><a href="/tags">tags</a></li>
2962 <li><a href="/tags">tags</a></li>
2961 <li><a href="/bookmarks">bookmarks</a></li>
2963 <li><a href="/bookmarks">bookmarks</a></li>
2962 <li><a href="/branches">branches</a></li>
2964 <li><a href="/branches">branches</a></li>
2963 </ul>
2965 </ul>
2964 <ul>
2966 <ul>
2965 <li class="active"><a href="/help">help</a></li>
2967 <li class="active"><a href="/help">help</a></li>
2966 </ul>
2968 </ul>
2967 </div>
2969 </div>
2968
2970
2969 <div class="main">
2971 <div class="main">
2970 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
2972 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
2971 <h3>Help: add</h3>
2973 <h3>Help: add</h3>
2972
2974
2973 <form class="search" action="/log">
2975 <form class="search" action="/log">
2974
2976
2975 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
2977 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
2976 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
2978 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
2977 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
2979 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
2978 </form>
2980 </form>
2979 <div id="doc">
2981 <div id="doc">
2980 <p>
2982 <p>
2981 hg add [OPTION]... [FILE]...
2983 hg add [OPTION]... [FILE]...
2982 </p>
2984 </p>
2983 <p>
2985 <p>
2984 add the specified files on the next commit
2986 add the specified files on the next commit
2985 </p>
2987 </p>
2986 <p>
2988 <p>
2987 Schedule files to be version controlled and added to the
2989 Schedule files to be version controlled and added to the
2988 repository.
2990 repository.
2989 </p>
2991 </p>
2990 <p>
2992 <p>
2991 The files will be added to the repository at the next commit. To
2993 The files will be added to the repository at the next commit. To
2992 undo an add before that, see 'hg forget'.
2994 undo an add before that, see 'hg forget'.
2993 </p>
2995 </p>
2994 <p>
2996 <p>
2995 If no names are given, add all files to the repository (except
2997 If no names are given, add all files to the repository (except
2996 files matching &quot;.hgignore&quot;).
2998 files matching &quot;.hgignore&quot;).
2997 </p>
2999 </p>
2998 <p>
3000 <p>
2999 Examples:
3001 Examples:
3000 </p>
3002 </p>
3001 <ul>
3003 <ul>
3002 <li> New (unknown) files are added automatically by 'hg add':
3004 <li> New (unknown) files are added automatically by 'hg add':
3003 <pre>
3005 <pre>
3004 \$ ls (re)
3006 \$ ls (re)
3005 foo.c
3007 foo.c
3006 \$ hg status (re)
3008 \$ hg status (re)
3007 ? foo.c
3009 ? foo.c
3008 \$ hg add (re)
3010 \$ hg add (re)
3009 adding foo.c
3011 adding foo.c
3010 \$ hg status (re)
3012 \$ hg status (re)
3011 A foo.c
3013 A foo.c
3012 </pre>
3014 </pre>
3013 <li> Specific files to be added can be specified:
3015 <li> Specific files to be added can be specified:
3014 <pre>
3016 <pre>
3015 \$ ls (re)
3017 \$ ls (re)
3016 bar.c foo.c
3018 bar.c foo.c
3017 \$ hg status (re)
3019 \$ hg status (re)
3018 ? bar.c
3020 ? bar.c
3019 ? foo.c
3021 ? foo.c
3020 \$ hg add bar.c (re)
3022 \$ hg add bar.c (re)
3021 \$ hg status (re)
3023 \$ hg status (re)
3022 A bar.c
3024 A bar.c
3023 ? foo.c
3025 ? foo.c
3024 </pre>
3026 </pre>
3025 </ul>
3027 </ul>
3026 <p>
3028 <p>
3027 Returns 0 if all files are successfully added.
3029 Returns 0 if all files are successfully added.
3028 </p>
3030 </p>
3029 <p>
3031 <p>
3030 options ([+] can be repeated):
3032 options ([+] can be repeated):
3031 </p>
3033 </p>
3032 <table>
3034 <table>
3033 <tr><td>-I</td>
3035 <tr><td>-I</td>
3034 <td>--include PATTERN [+]</td>
3036 <td>--include PATTERN [+]</td>
3035 <td>include names matching the given patterns</td></tr>
3037 <td>include names matching the given patterns</td></tr>
3036 <tr><td>-X</td>
3038 <tr><td>-X</td>
3037 <td>--exclude PATTERN [+]</td>
3039 <td>--exclude PATTERN [+]</td>
3038 <td>exclude names matching the given patterns</td></tr>
3040 <td>exclude names matching the given patterns</td></tr>
3039 <tr><td>-S</td>
3041 <tr><td>-S</td>
3040 <td>--subrepos</td>
3042 <td>--subrepos</td>
3041 <td>recurse into subrepositories</td></tr>
3043 <td>recurse into subrepositories</td></tr>
3042 <tr><td>-n</td>
3044 <tr><td>-n</td>
3043 <td>--dry-run</td>
3045 <td>--dry-run</td>
3044 <td>do not perform actions, just print output</td></tr>
3046 <td>do not perform actions, just print output</td></tr>
3045 </table>
3047 </table>
3046 <p>
3048 <p>
3047 global options ([+] can be repeated):
3049 global options ([+] can be repeated):
3048 </p>
3050 </p>
3049 <table>
3051 <table>
3050 <tr><td>-R</td>
3052 <tr><td>-R</td>
3051 <td>--repository REPO</td>
3053 <td>--repository REPO</td>
3052 <td>repository root directory or name of overlay bundle file</td></tr>
3054 <td>repository root directory or name of overlay bundle file</td></tr>
3053 <tr><td></td>
3055 <tr><td></td>
3054 <td>--cwd DIR</td>
3056 <td>--cwd DIR</td>
3055 <td>change working directory</td></tr>
3057 <td>change working directory</td></tr>
3056 <tr><td>-y</td>
3058 <tr><td>-y</td>
3057 <td>--noninteractive</td>
3059 <td>--noninteractive</td>
3058 <td>do not prompt, automatically pick the first choice for all prompts</td></tr>
3060 <td>do not prompt, automatically pick the first choice for all prompts</td></tr>
3059 <tr><td>-q</td>
3061 <tr><td>-q</td>
3060 <td>--quiet</td>
3062 <td>--quiet</td>
3061 <td>suppress output</td></tr>
3063 <td>suppress output</td></tr>
3062 <tr><td>-v</td>
3064 <tr><td>-v</td>
3063 <td>--verbose</td>
3065 <td>--verbose</td>
3064 <td>enable additional output</td></tr>
3066 <td>enable additional output</td></tr>
3065 <tr><td></td>
3067 <tr><td></td>
3066 <td>--color TYPE</td>
3068 <td>--color TYPE</td>
3067 <td>when to colorize (boolean, always, auto, never, or debug)</td></tr>
3069 <td>when to colorize (boolean, always, auto, never, or debug)</td></tr>
3068 <tr><td></td>
3070 <tr><td></td>
3069 <td>--config CONFIG [+]</td>
3071 <td>--config CONFIG [+]</td>
3070 <td>set/override config option (use 'section.name=value')</td></tr>
3072 <td>set/override config option (use 'section.name=value')</td></tr>
3071 <tr><td></td>
3073 <tr><td></td>
3072 <td>--debug</td>
3074 <td>--debug</td>
3073 <td>enable debugging output</td></tr>
3075 <td>enable debugging output</td></tr>
3074 <tr><td></td>
3076 <tr><td></td>
3075 <td>--debugger</td>
3077 <td>--debugger</td>
3076 <td>start debugger</td></tr>
3078 <td>start debugger</td></tr>
3077 <tr><td></td>
3079 <tr><td></td>
3078 <td>--encoding ENCODE</td>
3080 <td>--encoding ENCODE</td>
3079 <td>set the charset encoding (default: ascii)</td></tr>
3081 <td>set the charset encoding (default: ascii)</td></tr>
3080 <tr><td></td>
3082 <tr><td></td>
3081 <td>--encodingmode MODE</td>
3083 <td>--encodingmode MODE</td>
3082 <td>set the charset encoding mode (default: strict)</td></tr>
3084 <td>set the charset encoding mode (default: strict)</td></tr>
3083 <tr><td></td>
3085 <tr><td></td>
3084 <td>--traceback</td>
3086 <td>--traceback</td>
3085 <td>always print a traceback on exception</td></tr>
3087 <td>always print a traceback on exception</td></tr>
3086 <tr><td></td>
3088 <tr><td></td>
3087 <td>--time</td>
3089 <td>--time</td>
3088 <td>time how long the command takes</td></tr>
3090 <td>time how long the command takes</td></tr>
3089 <tr><td></td>
3091 <tr><td></td>
3090 <td>--profile</td>
3092 <td>--profile</td>
3091 <td>print command execution profile</td></tr>
3093 <td>print command execution profile</td></tr>
3092 <tr><td></td>
3094 <tr><td></td>
3093 <td>--version</td>
3095 <td>--version</td>
3094 <td>output version information and exit</td></tr>
3096 <td>output version information and exit</td></tr>
3095 <tr><td>-h</td>
3097 <tr><td>-h</td>
3096 <td>--help</td>
3098 <td>--help</td>
3097 <td>display help and exit</td></tr>
3099 <td>display help and exit</td></tr>
3098 <tr><td></td>
3100 <tr><td></td>
3099 <td>--hidden</td>
3101 <td>--hidden</td>
3100 <td>consider hidden changesets</td></tr>
3102 <td>consider hidden changesets</td></tr>
3101 <tr><td></td>
3103 <tr><td></td>
3102 <td>--pager TYPE</td>
3104 <td>--pager TYPE</td>
3103 <td>when to paginate (boolean, always, auto, or never) (default: auto)</td></tr>
3105 <td>when to paginate (boolean, always, auto, or never) (default: auto)</td></tr>
3104 </table>
3106 </table>
3105
3107
3106 </div>
3108 </div>
3107 </div>
3109 </div>
3108 </div>
3110 </div>
3109
3111
3110
3112
3111
3113
3112 </body>
3114 </body>
3113 </html>
3115 </html>
3114
3116
3115
3117
3116 $ get-with-headers.py $LOCALIP:$HGPORT "help/remove"
3118 $ get-with-headers.py $LOCALIP:$HGPORT "help/remove"
3117 200 Script output follows
3119 200 Script output follows
3118
3120
3119 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3121 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3120 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3122 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3121 <head>
3123 <head>
3122 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3124 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3123 <meta name="robots" content="index, nofollow" />
3125 <meta name="robots" content="index, nofollow" />
3124 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3126 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3125 <script type="text/javascript" src="/static/mercurial.js"></script>
3127 <script type="text/javascript" src="/static/mercurial.js"></script>
3126
3128
3127 <title>Help: remove</title>
3129 <title>Help: remove</title>
3128 </head>
3130 </head>
3129 <body>
3131 <body>
3130
3132
3131 <div class="container">
3133 <div class="container">
3132 <div class="menu">
3134 <div class="menu">
3133 <div class="logo">
3135 <div class="logo">
3134 <a href="https://mercurial-scm.org/">
3136 <a href="https://mercurial-scm.org/">
3135 <img src="/static/hglogo.png" alt="mercurial" /></a>
3137 <img src="/static/hglogo.png" alt="mercurial" /></a>
3136 </div>
3138 </div>
3137 <ul>
3139 <ul>
3138 <li><a href="/shortlog">log</a></li>
3140 <li><a href="/shortlog">log</a></li>
3139 <li><a href="/graph">graph</a></li>
3141 <li><a href="/graph">graph</a></li>
3140 <li><a href="/tags">tags</a></li>
3142 <li><a href="/tags">tags</a></li>
3141 <li><a href="/bookmarks">bookmarks</a></li>
3143 <li><a href="/bookmarks">bookmarks</a></li>
3142 <li><a href="/branches">branches</a></li>
3144 <li><a href="/branches">branches</a></li>
3143 </ul>
3145 </ul>
3144 <ul>
3146 <ul>
3145 <li class="active"><a href="/help">help</a></li>
3147 <li class="active"><a href="/help">help</a></li>
3146 </ul>
3148 </ul>
3147 </div>
3149 </div>
3148
3150
3149 <div class="main">
3151 <div class="main">
3150 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3152 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3151 <h3>Help: remove</h3>
3153 <h3>Help: remove</h3>
3152
3154
3153 <form class="search" action="/log">
3155 <form class="search" action="/log">
3154
3156
3155 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3157 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3156 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3158 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3157 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3159 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3158 </form>
3160 </form>
3159 <div id="doc">
3161 <div id="doc">
3160 <p>
3162 <p>
3161 hg remove [OPTION]... FILE...
3163 hg remove [OPTION]... FILE...
3162 </p>
3164 </p>
3163 <p>
3165 <p>
3164 aliases: rm
3166 aliases: rm
3165 </p>
3167 </p>
3166 <p>
3168 <p>
3167 remove the specified files on the next commit
3169 remove the specified files on the next commit
3168 </p>
3170 </p>
3169 <p>
3171 <p>
3170 Schedule the indicated files for removal from the current branch.
3172 Schedule the indicated files for removal from the current branch.
3171 </p>
3173 </p>
3172 <p>
3174 <p>
3173 This command schedules the files to be removed at the next commit.
3175 This command schedules the files to be removed at the next commit.
3174 To undo a remove before that, see 'hg revert'. To undo added
3176 To undo a remove before that, see 'hg revert'. To undo added
3175 files, see 'hg forget'.
3177 files, see 'hg forget'.
3176 </p>
3178 </p>
3177 <p>
3179 <p>
3178 -A/--after can be used to remove only files that have already
3180 -A/--after can be used to remove only files that have already
3179 been deleted, -f/--force can be used to force deletion, and -Af
3181 been deleted, -f/--force can be used to force deletion, and -Af
3180 can be used to remove files from the next revision without
3182 can be used to remove files from the next revision without
3181 deleting them from the working directory.
3183 deleting them from the working directory.
3182 </p>
3184 </p>
3183 <p>
3185 <p>
3184 The following table details the behavior of remove for different
3186 The following table details the behavior of remove for different
3185 file states (columns) and option combinations (rows). The file
3187 file states (columns) and option combinations (rows). The file
3186 states are Added [A], Clean [C], Modified [M] and Missing [!]
3188 states are Added [A], Clean [C], Modified [M] and Missing [!]
3187 (as reported by 'hg status'). The actions are Warn, Remove
3189 (as reported by 'hg status'). The actions are Warn, Remove
3188 (from branch) and Delete (from disk):
3190 (from branch) and Delete (from disk):
3189 </p>
3191 </p>
3190 <table>
3192 <table>
3191 <tr><td>opt/state</td>
3193 <tr><td>opt/state</td>
3192 <td>A</td>
3194 <td>A</td>
3193 <td>C</td>
3195 <td>C</td>
3194 <td>M</td>
3196 <td>M</td>
3195 <td>!</td></tr>
3197 <td>!</td></tr>
3196 <tr><td>none</td>
3198 <tr><td>none</td>
3197 <td>W</td>
3199 <td>W</td>
3198 <td>RD</td>
3200 <td>RD</td>
3199 <td>W</td>
3201 <td>W</td>
3200 <td>R</td></tr>
3202 <td>R</td></tr>
3201 <tr><td>-f</td>
3203 <tr><td>-f</td>
3202 <td>R</td>
3204 <td>R</td>
3203 <td>RD</td>
3205 <td>RD</td>
3204 <td>RD</td>
3206 <td>RD</td>
3205 <td>R</td></tr>
3207 <td>R</td></tr>
3206 <tr><td>-A</td>
3208 <tr><td>-A</td>
3207 <td>W</td>
3209 <td>W</td>
3208 <td>W</td>
3210 <td>W</td>
3209 <td>W</td>
3211 <td>W</td>
3210 <td>R</td></tr>
3212 <td>R</td></tr>
3211 <tr><td>-Af</td>
3213 <tr><td>-Af</td>
3212 <td>R</td>
3214 <td>R</td>
3213 <td>R</td>
3215 <td>R</td>
3214 <td>R</td>
3216 <td>R</td>
3215 <td>R</td></tr>
3217 <td>R</td></tr>
3216 </table>
3218 </table>
3217 <p>
3219 <p>
3218 <b>Note:</b>
3220 <b>Note:</b>
3219 </p>
3221 </p>
3220 <p>
3222 <p>
3221 'hg remove' never deletes files in Added [A] state from the
3223 'hg remove' never deletes files in Added [A] state from the
3222 working directory, not even if &quot;--force&quot; is specified.
3224 working directory, not even if &quot;--force&quot; is specified.
3223 </p>
3225 </p>
3224 <p>
3226 <p>
3225 Returns 0 on success, 1 if any warnings encountered.
3227 Returns 0 on success, 1 if any warnings encountered.
3226 </p>
3228 </p>
3227 <p>
3229 <p>
3228 options ([+] can be repeated):
3230 options ([+] can be repeated):
3229 </p>
3231 </p>
3230 <table>
3232 <table>
3231 <tr><td>-A</td>
3233 <tr><td>-A</td>
3232 <td>--after</td>
3234 <td>--after</td>
3233 <td>record delete for missing files</td></tr>
3235 <td>record delete for missing files</td></tr>
3234 <tr><td>-f</td>
3236 <tr><td>-f</td>
3235 <td>--force</td>
3237 <td>--force</td>
3236 <td>forget added files, delete modified files</td></tr>
3238 <td>forget added files, delete modified files</td></tr>
3237 <tr><td>-S</td>
3239 <tr><td>-S</td>
3238 <td>--subrepos</td>
3240 <td>--subrepos</td>
3239 <td>recurse into subrepositories</td></tr>
3241 <td>recurse into subrepositories</td></tr>
3240 <tr><td>-I</td>
3242 <tr><td>-I</td>
3241 <td>--include PATTERN [+]</td>
3243 <td>--include PATTERN [+]</td>
3242 <td>include names matching the given patterns</td></tr>
3244 <td>include names matching the given patterns</td></tr>
3243 <tr><td>-X</td>
3245 <tr><td>-X</td>
3244 <td>--exclude PATTERN [+]</td>
3246 <td>--exclude PATTERN [+]</td>
3245 <td>exclude names matching the given patterns</td></tr>
3247 <td>exclude names matching the given patterns</td></tr>
3246 <tr><td>-n</td>
3248 <tr><td>-n</td>
3247 <td>--dry-run</td>
3249 <td>--dry-run</td>
3248 <td>do not perform actions, just print output</td></tr>
3250 <td>do not perform actions, just print output</td></tr>
3249 </table>
3251 </table>
3250 <p>
3252 <p>
3251 global options ([+] can be repeated):
3253 global options ([+] can be repeated):
3252 </p>
3254 </p>
3253 <table>
3255 <table>
3254 <tr><td>-R</td>
3256 <tr><td>-R</td>
3255 <td>--repository REPO</td>
3257 <td>--repository REPO</td>
3256 <td>repository root directory or name of overlay bundle file</td></tr>
3258 <td>repository root directory or name of overlay bundle file</td></tr>
3257 <tr><td></td>
3259 <tr><td></td>
3258 <td>--cwd DIR</td>
3260 <td>--cwd DIR</td>
3259 <td>change working directory</td></tr>
3261 <td>change working directory</td></tr>
3260 <tr><td>-y</td>
3262 <tr><td>-y</td>
3261 <td>--noninteractive</td>
3263 <td>--noninteractive</td>
3262 <td>do not prompt, automatically pick the first choice for all prompts</td></tr>
3264 <td>do not prompt, automatically pick the first choice for all prompts</td></tr>
3263 <tr><td>-q</td>
3265 <tr><td>-q</td>
3264 <td>--quiet</td>
3266 <td>--quiet</td>
3265 <td>suppress output</td></tr>
3267 <td>suppress output</td></tr>
3266 <tr><td>-v</td>
3268 <tr><td>-v</td>
3267 <td>--verbose</td>
3269 <td>--verbose</td>
3268 <td>enable additional output</td></tr>
3270 <td>enable additional output</td></tr>
3269 <tr><td></td>
3271 <tr><td></td>
3270 <td>--color TYPE</td>
3272 <td>--color TYPE</td>
3271 <td>when to colorize (boolean, always, auto, never, or debug)</td></tr>
3273 <td>when to colorize (boolean, always, auto, never, or debug)</td></tr>
3272 <tr><td></td>
3274 <tr><td></td>
3273 <td>--config CONFIG [+]</td>
3275 <td>--config CONFIG [+]</td>
3274 <td>set/override config option (use 'section.name=value')</td></tr>
3276 <td>set/override config option (use 'section.name=value')</td></tr>
3275 <tr><td></td>
3277 <tr><td></td>
3276 <td>--debug</td>
3278 <td>--debug</td>
3277 <td>enable debugging output</td></tr>
3279 <td>enable debugging output</td></tr>
3278 <tr><td></td>
3280 <tr><td></td>
3279 <td>--debugger</td>
3281 <td>--debugger</td>
3280 <td>start debugger</td></tr>
3282 <td>start debugger</td></tr>
3281 <tr><td></td>
3283 <tr><td></td>
3282 <td>--encoding ENCODE</td>
3284 <td>--encoding ENCODE</td>
3283 <td>set the charset encoding (default: ascii)</td></tr>
3285 <td>set the charset encoding (default: ascii)</td></tr>
3284 <tr><td></td>
3286 <tr><td></td>
3285 <td>--encodingmode MODE</td>
3287 <td>--encodingmode MODE</td>
3286 <td>set the charset encoding mode (default: strict)</td></tr>
3288 <td>set the charset encoding mode (default: strict)</td></tr>
3287 <tr><td></td>
3289 <tr><td></td>
3288 <td>--traceback</td>
3290 <td>--traceback</td>
3289 <td>always print a traceback on exception</td></tr>
3291 <td>always print a traceback on exception</td></tr>
3290 <tr><td></td>
3292 <tr><td></td>
3291 <td>--time</td>
3293 <td>--time</td>
3292 <td>time how long the command takes</td></tr>
3294 <td>time how long the command takes</td></tr>
3293 <tr><td></td>
3295 <tr><td></td>
3294 <td>--profile</td>
3296 <td>--profile</td>
3295 <td>print command execution profile</td></tr>
3297 <td>print command execution profile</td></tr>
3296 <tr><td></td>
3298 <tr><td></td>
3297 <td>--version</td>
3299 <td>--version</td>
3298 <td>output version information and exit</td></tr>
3300 <td>output version information and exit</td></tr>
3299 <tr><td>-h</td>
3301 <tr><td>-h</td>
3300 <td>--help</td>
3302 <td>--help</td>
3301 <td>display help and exit</td></tr>
3303 <td>display help and exit</td></tr>
3302 <tr><td></td>
3304 <tr><td></td>
3303 <td>--hidden</td>
3305 <td>--hidden</td>
3304 <td>consider hidden changesets</td></tr>
3306 <td>consider hidden changesets</td></tr>
3305 <tr><td></td>
3307 <tr><td></td>
3306 <td>--pager TYPE</td>
3308 <td>--pager TYPE</td>
3307 <td>when to paginate (boolean, always, auto, or never) (default: auto)</td></tr>
3309 <td>when to paginate (boolean, always, auto, or never) (default: auto)</td></tr>
3308 </table>
3310 </table>
3309
3311
3310 </div>
3312 </div>
3311 </div>
3313 </div>
3312 </div>
3314 </div>
3313
3315
3314
3316
3315
3317
3316 </body>
3318 </body>
3317 </html>
3319 </html>
3318
3320
3319
3321
3320 $ get-with-headers.py $LOCALIP:$HGPORT "help/dates"
3322 $ get-with-headers.py $LOCALIP:$HGPORT "help/dates"
3321 200 Script output follows
3323 200 Script output follows
3322
3324
3323 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3325 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3324 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3326 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3325 <head>
3327 <head>
3326 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3328 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3327 <meta name="robots" content="index, nofollow" />
3329 <meta name="robots" content="index, nofollow" />
3328 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3330 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3329 <script type="text/javascript" src="/static/mercurial.js"></script>
3331 <script type="text/javascript" src="/static/mercurial.js"></script>
3330
3332
3331 <title>Help: dates</title>
3333 <title>Help: dates</title>
3332 </head>
3334 </head>
3333 <body>
3335 <body>
3334
3336
3335 <div class="container">
3337 <div class="container">
3336 <div class="menu">
3338 <div class="menu">
3337 <div class="logo">
3339 <div class="logo">
3338 <a href="https://mercurial-scm.org/">
3340 <a href="https://mercurial-scm.org/">
3339 <img src="/static/hglogo.png" alt="mercurial" /></a>
3341 <img src="/static/hglogo.png" alt="mercurial" /></a>
3340 </div>
3342 </div>
3341 <ul>
3343 <ul>
3342 <li><a href="/shortlog">log</a></li>
3344 <li><a href="/shortlog">log</a></li>
3343 <li><a href="/graph">graph</a></li>
3345 <li><a href="/graph">graph</a></li>
3344 <li><a href="/tags">tags</a></li>
3346 <li><a href="/tags">tags</a></li>
3345 <li><a href="/bookmarks">bookmarks</a></li>
3347 <li><a href="/bookmarks">bookmarks</a></li>
3346 <li><a href="/branches">branches</a></li>
3348 <li><a href="/branches">branches</a></li>
3347 </ul>
3349 </ul>
3348 <ul>
3350 <ul>
3349 <li class="active"><a href="/help">help</a></li>
3351 <li class="active"><a href="/help">help</a></li>
3350 </ul>
3352 </ul>
3351 </div>
3353 </div>
3352
3354
3353 <div class="main">
3355 <div class="main">
3354 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3356 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3355 <h3>Help: dates</h3>
3357 <h3>Help: dates</h3>
3356
3358
3357 <form class="search" action="/log">
3359 <form class="search" action="/log">
3358
3360
3359 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3361 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3360 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3362 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3361 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3363 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3362 </form>
3364 </form>
3363 <div id="doc">
3365 <div id="doc">
3364 <h1>Date Formats</h1>
3366 <h1>Date Formats</h1>
3365 <p>
3367 <p>
3366 Some commands allow the user to specify a date, e.g.:
3368 Some commands allow the user to specify a date, e.g.:
3367 </p>
3369 </p>
3368 <ul>
3370 <ul>
3369 <li> backout, commit, import, tag: Specify the commit date.
3371 <li> backout, commit, import, tag: Specify the commit date.
3370 <li> log, revert, update: Select revision(s) by date.
3372 <li> log, revert, update: Select revision(s) by date.
3371 </ul>
3373 </ul>
3372 <p>
3374 <p>
3373 Many date formats are valid. Here are some examples:
3375 Many date formats are valid. Here are some examples:
3374 </p>
3376 </p>
3375 <ul>
3377 <ul>
3376 <li> &quot;Wed Dec 6 13:18:29 2006&quot; (local timezone assumed)
3378 <li> &quot;Wed Dec 6 13:18:29 2006&quot; (local timezone assumed)
3377 <li> &quot;Dec 6 13:18 -0600&quot; (year assumed, time offset provided)
3379 <li> &quot;Dec 6 13:18 -0600&quot; (year assumed, time offset provided)
3378 <li> &quot;Dec 6 13:18 UTC&quot; (UTC and GMT are aliases for +0000)
3380 <li> &quot;Dec 6 13:18 UTC&quot; (UTC and GMT are aliases for +0000)
3379 <li> &quot;Dec 6&quot; (midnight)
3381 <li> &quot;Dec 6&quot; (midnight)
3380 <li> &quot;13:18&quot; (today assumed)
3382 <li> &quot;13:18&quot; (today assumed)
3381 <li> &quot;3:39&quot; (3:39AM assumed)
3383 <li> &quot;3:39&quot; (3:39AM assumed)
3382 <li> &quot;3:39pm&quot; (15:39)
3384 <li> &quot;3:39pm&quot; (15:39)
3383 <li> &quot;2006-12-06 13:18:29&quot; (ISO 8601 format)
3385 <li> &quot;2006-12-06 13:18:29&quot; (ISO 8601 format)
3384 <li> &quot;2006-12-6 13:18&quot;
3386 <li> &quot;2006-12-6 13:18&quot;
3385 <li> &quot;2006-12-6&quot;
3387 <li> &quot;2006-12-6&quot;
3386 <li> &quot;12-6&quot;
3388 <li> &quot;12-6&quot;
3387 <li> &quot;12/6&quot;
3389 <li> &quot;12/6&quot;
3388 <li> &quot;12/6/6&quot; (Dec 6 2006)
3390 <li> &quot;12/6/6&quot; (Dec 6 2006)
3389 <li> &quot;today&quot; (midnight)
3391 <li> &quot;today&quot; (midnight)
3390 <li> &quot;yesterday&quot; (midnight)
3392 <li> &quot;yesterday&quot; (midnight)
3391 <li> &quot;now&quot; - right now
3393 <li> &quot;now&quot; - right now
3392 </ul>
3394 </ul>
3393 <p>
3395 <p>
3394 Lastly, there is Mercurial's internal format:
3396 Lastly, there is Mercurial's internal format:
3395 </p>
3397 </p>
3396 <ul>
3398 <ul>
3397 <li> &quot;1165411109 0&quot; (Wed Dec 6 13:18:29 2006 UTC)
3399 <li> &quot;1165411109 0&quot; (Wed Dec 6 13:18:29 2006 UTC)
3398 </ul>
3400 </ul>
3399 <p>
3401 <p>
3400 This is the internal representation format for dates. The first number
3402 This is the internal representation format for dates. The first number
3401 is the number of seconds since the epoch (1970-01-01 00:00 UTC). The
3403 is the number of seconds since the epoch (1970-01-01 00:00 UTC). The
3402 second is the offset of the local timezone, in seconds west of UTC
3404 second is the offset of the local timezone, in seconds west of UTC
3403 (negative if the timezone is east of UTC).
3405 (negative if the timezone is east of UTC).
3404 </p>
3406 </p>
3405 <p>
3407 <p>
3406 The log command also accepts date ranges:
3408 The log command also accepts date ranges:
3407 </p>
3409 </p>
3408 <ul>
3410 <ul>
3409 <li> &quot;&lt;DATE&quot; - at or before a given date/time
3411 <li> &quot;&lt;DATE&quot; - at or before a given date/time
3410 <li> &quot;&gt;DATE&quot; - on or after a given date/time
3412 <li> &quot;&gt;DATE&quot; - on or after a given date/time
3411 <li> &quot;DATE to DATE&quot; - a date range, inclusive
3413 <li> &quot;DATE to DATE&quot; - a date range, inclusive
3412 <li> &quot;-DAYS&quot; - within a given number of days from today
3414 <li> &quot;-DAYS&quot; - within a given number of days from today
3413 </ul>
3415 </ul>
3414
3416
3415 </div>
3417 </div>
3416 </div>
3418 </div>
3417 </div>
3419 </div>
3418
3420
3419
3421
3420
3422
3421 </body>
3423 </body>
3422 </html>
3424 </html>
3423
3425
3424
3426
3425 $ get-with-headers.py $LOCALIP:$HGPORT "help/pager"
3427 $ get-with-headers.py $LOCALIP:$HGPORT "help/pager"
3426 200 Script output follows
3428 200 Script output follows
3427
3429
3428 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3430 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3429 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3431 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3430 <head>
3432 <head>
3431 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3433 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3432 <meta name="robots" content="index, nofollow" />
3434 <meta name="robots" content="index, nofollow" />
3433 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3435 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3434 <script type="text/javascript" src="/static/mercurial.js"></script>
3436 <script type="text/javascript" src="/static/mercurial.js"></script>
3435
3437
3436 <title>Help: pager</title>
3438 <title>Help: pager</title>
3437 </head>
3439 </head>
3438 <body>
3440 <body>
3439
3441
3440 <div class="container">
3442 <div class="container">
3441 <div class="menu">
3443 <div class="menu">
3442 <div class="logo">
3444 <div class="logo">
3443 <a href="https://mercurial-scm.org/">
3445 <a href="https://mercurial-scm.org/">
3444 <img src="/static/hglogo.png" alt="mercurial" /></a>
3446 <img src="/static/hglogo.png" alt="mercurial" /></a>
3445 </div>
3447 </div>
3446 <ul>
3448 <ul>
3447 <li><a href="/shortlog">log</a></li>
3449 <li><a href="/shortlog">log</a></li>
3448 <li><a href="/graph">graph</a></li>
3450 <li><a href="/graph">graph</a></li>
3449 <li><a href="/tags">tags</a></li>
3451 <li><a href="/tags">tags</a></li>
3450 <li><a href="/bookmarks">bookmarks</a></li>
3452 <li><a href="/bookmarks">bookmarks</a></li>
3451 <li><a href="/branches">branches</a></li>
3453 <li><a href="/branches">branches</a></li>
3452 </ul>
3454 </ul>
3453 <ul>
3455 <ul>
3454 <li class="active"><a href="/help">help</a></li>
3456 <li class="active"><a href="/help">help</a></li>
3455 </ul>
3457 </ul>
3456 </div>
3458 </div>
3457
3459
3458 <div class="main">
3460 <div class="main">
3459 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3461 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3460 <h3>Help: pager</h3>
3462 <h3>Help: pager</h3>
3461
3463
3462 <form class="search" action="/log">
3464 <form class="search" action="/log">
3463
3465
3464 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3466 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3465 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3467 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3466 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3468 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3467 </form>
3469 </form>
3468 <div id="doc">
3470 <div id="doc">
3469 <h1>Pager Support</h1>
3471 <h1>Pager Support</h1>
3470 <p>
3472 <p>
3471 Some Mercurial commands can produce a lot of output, and Mercurial will
3473 Some Mercurial commands can produce a lot of output, and Mercurial will
3472 attempt to use a pager to make those commands more pleasant.
3474 attempt to use a pager to make those commands more pleasant.
3473 </p>
3475 </p>
3474 <p>
3476 <p>
3475 To set the pager that should be used, set the application variable:
3477 To set the pager that should be used, set the application variable:
3476 </p>
3478 </p>
3477 <pre>
3479 <pre>
3478 [pager]
3480 [pager]
3479 pager = less -FRX
3481 pager = less -FRX
3480 </pre>
3482 </pre>
3481 <p>
3483 <p>
3482 If no pager is set in the user or repository configuration, Mercurial uses the
3484 If no pager is set in the user or repository configuration, Mercurial uses the
3483 environment variable $PAGER. If $PAGER is not set, pager.pager from the default
3485 environment variable $PAGER. If $PAGER is not set, pager.pager from the default
3484 or system configuration is used. If none of these are set, a default pager will
3486 or system configuration is used. If none of these are set, a default pager will
3485 be used, typically 'less' on Unix and 'more' on Windows.
3487 be used, typically 'less' on Unix and 'more' on Windows.
3486 </p>
3488 </p>
3487 <p>
3489 <p>
3488 You can disable the pager for certain commands by adding them to the
3490 You can disable the pager for certain commands by adding them to the
3489 pager.ignore list:
3491 pager.ignore list:
3490 </p>
3492 </p>
3491 <pre>
3493 <pre>
3492 [pager]
3494 [pager]
3493 ignore = version, help, update
3495 ignore = version, help, update
3494 </pre>
3496 </pre>
3495 <p>
3497 <p>
3496 To ignore global commands like 'hg version' or 'hg help', you have
3498 To ignore global commands like 'hg version' or 'hg help', you have
3497 to specify them in your user configuration file.
3499 to specify them in your user configuration file.
3498 </p>
3500 </p>
3499 <p>
3501 <p>
3500 To control whether the pager is used at all for an individual command,
3502 To control whether the pager is used at all for an individual command,
3501 you can use --pager=&lt;value&gt;:
3503 you can use --pager=&lt;value&gt;:
3502 </p>
3504 </p>
3503 <ul>
3505 <ul>
3504 <li> use as needed: 'auto'.
3506 <li> use as needed: 'auto'.
3505 <li> require the pager: 'yes' or 'on'.
3507 <li> require the pager: 'yes' or 'on'.
3506 <li> suppress the pager: 'no' or 'off' (any unrecognized value will also work).
3508 <li> suppress the pager: 'no' or 'off' (any unrecognized value will also work).
3507 </ul>
3509 </ul>
3508 <p>
3510 <p>
3509 To globally turn off all attempts to use a pager, set:
3511 To globally turn off all attempts to use a pager, set:
3510 </p>
3512 </p>
3511 <pre>
3513 <pre>
3512 [ui]
3514 [ui]
3513 paginate = never
3515 paginate = never
3514 </pre>
3516 </pre>
3515 <p>
3517 <p>
3516 which will prevent the pager from running.
3518 which will prevent the pager from running.
3517 </p>
3519 </p>
3518
3520
3519 </div>
3521 </div>
3520 </div>
3522 </div>
3521 </div>
3523 </div>
3522
3524
3523
3525
3524
3526
3525 </body>
3527 </body>
3526 </html>
3528 </html>
3527
3529
3528
3530
3529 Sub-topic indexes rendered properly
3531 Sub-topic indexes rendered properly
3530
3532
3531 $ get-with-headers.py $LOCALIP:$HGPORT "help/internals"
3533 $ get-with-headers.py $LOCALIP:$HGPORT "help/internals"
3532 200 Script output follows
3534 200 Script output follows
3533
3535
3534 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3536 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3535 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3537 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3536 <head>
3538 <head>
3537 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3539 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3538 <meta name="robots" content="index, nofollow" />
3540 <meta name="robots" content="index, nofollow" />
3539 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3541 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3540 <script type="text/javascript" src="/static/mercurial.js"></script>
3542 <script type="text/javascript" src="/static/mercurial.js"></script>
3541
3543
3542 <title>Help: internals</title>
3544 <title>Help: internals</title>
3543 </head>
3545 </head>
3544 <body>
3546 <body>
3545
3547
3546 <div class="container">
3548 <div class="container">
3547 <div class="menu">
3549 <div class="menu">
3548 <div class="logo">
3550 <div class="logo">
3549 <a href="https://mercurial-scm.org/">
3551 <a href="https://mercurial-scm.org/">
3550 <img src="/static/hglogo.png" alt="mercurial" /></a>
3552 <img src="/static/hglogo.png" alt="mercurial" /></a>
3551 </div>
3553 </div>
3552 <ul>
3554 <ul>
3553 <li><a href="/shortlog">log</a></li>
3555 <li><a href="/shortlog">log</a></li>
3554 <li><a href="/graph">graph</a></li>
3556 <li><a href="/graph">graph</a></li>
3555 <li><a href="/tags">tags</a></li>
3557 <li><a href="/tags">tags</a></li>
3556 <li><a href="/bookmarks">bookmarks</a></li>
3558 <li><a href="/bookmarks">bookmarks</a></li>
3557 <li><a href="/branches">branches</a></li>
3559 <li><a href="/branches">branches</a></li>
3558 </ul>
3560 </ul>
3559 <ul>
3561 <ul>
3560 <li><a href="/help">help</a></li>
3562 <li><a href="/help">help</a></li>
3561 </ul>
3563 </ul>
3562 </div>
3564 </div>
3563
3565
3564 <div class="main">
3566 <div class="main">
3565 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3567 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3566
3568
3567 <form class="search" action="/log">
3569 <form class="search" action="/log">
3568
3570
3569 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3571 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3570 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3572 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3571 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3573 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3572 </form>
3574 </form>
3573 <table class="bigtable">
3575 <table class="bigtable">
3574 <tr><td colspan="2"><h2><a name="topics" href="#topics">Topics</a></h2></td></tr>
3576 <tr><td colspan="2"><h2><a name="topics" href="#topics">Topics</a></h2></td></tr>
3575
3577
3576 <tr><td>
3578 <tr><td>
3577 <a href="/help/internals.bid-merge">
3579 <a href="/help/internals.bid-merge">
3578 bid-merge
3580 bid-merge
3579 </a>
3581 </a>
3580 </td><td>
3582 </td><td>
3581 Bid Merge Algorithm
3583 Bid Merge Algorithm
3582 </td></tr>
3584 </td></tr>
3583 <tr><td>
3585 <tr><td>
3584 <a href="/help/internals.bundle2">
3586 <a href="/help/internals.bundle2">
3585 bundle2
3587 bundle2
3586 </a>
3588 </a>
3587 </td><td>
3589 </td><td>
3588 Bundle2
3590 Bundle2
3589 </td></tr>
3591 </td></tr>
3590 <tr><td>
3592 <tr><td>
3591 <a href="/help/internals.bundles">
3593 <a href="/help/internals.bundles">
3592 bundles
3594 bundles
3593 </a>
3595 </a>
3594 </td><td>
3596 </td><td>
3595 Bundles
3597 Bundles
3596 </td></tr>
3598 </td></tr>
3597 <tr><td>
3599 <tr><td>
3598 <a href="/help/internals.cbor">
3600 <a href="/help/internals.cbor">
3599 cbor
3601 cbor
3600 </a>
3602 </a>
3601 </td><td>
3603 </td><td>
3602 CBOR
3604 CBOR
3603 </td></tr>
3605 </td></tr>
3604 <tr><td>
3606 <tr><td>
3605 <a href="/help/internals.censor">
3607 <a href="/help/internals.censor">
3606 censor
3608 censor
3607 </a>
3609 </a>
3608 </td><td>
3610 </td><td>
3609 Censor
3611 Censor
3610 </td></tr>
3612 </td></tr>
3611 <tr><td>
3613 <tr><td>
3612 <a href="/help/internals.changegroups">
3614 <a href="/help/internals.changegroups">
3613 changegroups
3615 changegroups
3614 </a>
3616 </a>
3615 </td><td>
3617 </td><td>
3616 Changegroups
3618 Changegroups
3617 </td></tr>
3619 </td></tr>
3618 <tr><td>
3620 <tr><td>
3619 <a href="/help/internals.config">
3621 <a href="/help/internals.config">
3620 config
3622 config
3621 </a>
3623 </a>
3622 </td><td>
3624 </td><td>
3623 Config Registrar
3625 Config Registrar
3624 </td></tr>
3626 </td></tr>
3625 <tr><td>
3627 <tr><td>
3626 <a href="/help/internals.dirstate-v2">
3628 <a href="/help/internals.dirstate-v2">
3627 dirstate-v2
3629 dirstate-v2
3628 </a>
3630 </a>
3629 </td><td>
3631 </td><td>
3630 dirstate-v2 file format
3632 dirstate-v2 file format
3631 </td></tr>
3633 </td></tr>
3632 <tr><td>
3634 <tr><td>
3633 <a href="/help/internals.extensions">
3635 <a href="/help/internals.extensions">
3634 extensions
3636 extensions
3635 </a>
3637 </a>
3636 </td><td>
3638 </td><td>
3637 Extension API
3639 Extension API
3638 </td></tr>
3640 </td></tr>
3639 <tr><td>
3641 <tr><td>
3640 <a href="/help/internals.mergestate">
3642 <a href="/help/internals.mergestate">
3641 mergestate
3643 mergestate
3642 </a>
3644 </a>
3643 </td><td>
3645 </td><td>
3644 Mergestate
3646 Mergestate
3645 </td></tr>
3647 </td></tr>
3646 <tr><td>
3648 <tr><td>
3647 <a href="/help/internals.requirements">
3649 <a href="/help/internals.requirements">
3648 requirements
3650 requirements
3649 </a>
3651 </a>
3650 </td><td>
3652 </td><td>
3651 Repository Requirements
3653 Repository Requirements
3652 </td></tr>
3654 </td></tr>
3653 <tr><td>
3655 <tr><td>
3654 <a href="/help/internals.revlogs">
3656 <a href="/help/internals.revlogs">
3655 revlogs
3657 revlogs
3656 </a>
3658 </a>
3657 </td><td>
3659 </td><td>
3658 Revision Logs
3660 Revision Logs
3659 </td></tr>
3661 </td></tr>
3660 <tr><td>
3662 <tr><td>
3661 <a href="/help/internals.wireprotocol">
3663 <a href="/help/internals.wireprotocol">
3662 wireprotocol
3664 wireprotocol
3663 </a>
3665 </a>
3664 </td><td>
3666 </td><td>
3665 Wire Protocol
3667 Wire Protocol
3666 </td></tr>
3668 </td></tr>
3667 <tr><td>
3669 <tr><td>
3668 <a href="/help/internals.wireprotocolrpc">
3670 <a href="/help/internals.wireprotocolrpc">
3669 wireprotocolrpc
3671 wireprotocolrpc
3670 </a>
3672 </a>
3671 </td><td>
3673 </td><td>
3672 Wire Protocol RPC
3674 Wire Protocol RPC
3673 </td></tr>
3675 </td></tr>
3674 <tr><td>
3676 <tr><td>
3675 <a href="/help/internals.wireprotocolv2">
3677 <a href="/help/internals.wireprotocolv2">
3676 wireprotocolv2
3678 wireprotocolv2
3677 </a>
3679 </a>
3678 </td><td>
3680 </td><td>
3679 Wire Protocol Version 2
3681 Wire Protocol Version 2
3680 </td></tr>
3682 </td></tr>
3681
3683
3682
3684
3683
3685
3684
3686
3685
3687
3686 </table>
3688 </table>
3687 </div>
3689 </div>
3688 </div>
3690 </div>
3689
3691
3690
3692
3691
3693
3692 </body>
3694 </body>
3693 </html>
3695 </html>
3694
3696
3695
3697
3696 Sub-topic topics rendered properly
3698 Sub-topic topics rendered properly
3697
3699
3698 $ get-with-headers.py $LOCALIP:$HGPORT "help/internals.changegroups"
3700 $ get-with-headers.py $LOCALIP:$HGPORT "help/internals.changegroups"
3699 200 Script output follows
3701 200 Script output follows
3700
3702
3701 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3703 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
3702 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3704 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
3703 <head>
3705 <head>
3704 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3706 <link rel="icon" href="/static/hgicon.png" type="image/png" />
3705 <meta name="robots" content="index, nofollow" />
3707 <meta name="robots" content="index, nofollow" />
3706 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3708 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
3707 <script type="text/javascript" src="/static/mercurial.js"></script>
3709 <script type="text/javascript" src="/static/mercurial.js"></script>
3708
3710
3709 <title>Help: internals.changegroups</title>
3711 <title>Help: internals.changegroups</title>
3710 </head>
3712 </head>
3711 <body>
3713 <body>
3712
3714
3713 <div class="container">
3715 <div class="container">
3714 <div class="menu">
3716 <div class="menu">
3715 <div class="logo">
3717 <div class="logo">
3716 <a href="https://mercurial-scm.org/">
3718 <a href="https://mercurial-scm.org/">
3717 <img src="/static/hglogo.png" alt="mercurial" /></a>
3719 <img src="/static/hglogo.png" alt="mercurial" /></a>
3718 </div>
3720 </div>
3719 <ul>
3721 <ul>
3720 <li><a href="/shortlog">log</a></li>
3722 <li><a href="/shortlog">log</a></li>
3721 <li><a href="/graph">graph</a></li>
3723 <li><a href="/graph">graph</a></li>
3722 <li><a href="/tags">tags</a></li>
3724 <li><a href="/tags">tags</a></li>
3723 <li><a href="/bookmarks">bookmarks</a></li>
3725 <li><a href="/bookmarks">bookmarks</a></li>
3724 <li><a href="/branches">branches</a></li>
3726 <li><a href="/branches">branches</a></li>
3725 </ul>
3727 </ul>
3726 <ul>
3728 <ul>
3727 <li class="active"><a href="/help">help</a></li>
3729 <li class="active"><a href="/help">help</a></li>
3728 </ul>
3730 </ul>
3729 </div>
3731 </div>
3730
3732
3731 <div class="main">
3733 <div class="main">
3732 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3734 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
3733 <h3>Help: internals.changegroups</h3>
3735 <h3>Help: internals.changegroups</h3>
3734
3736
3735 <form class="search" action="/log">
3737 <form class="search" action="/log">
3736
3738
3737 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3739 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
3738 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3740 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
3739 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3741 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
3740 </form>
3742 </form>
3741 <div id="doc">
3743 <div id="doc">
3742 <h1>Changegroups</h1>
3744 <h1>Changegroups</h1>
3743 <p>
3745 <p>
3744 Changegroups are representations of repository revlog data, specifically
3746 Changegroups are representations of repository revlog data, specifically
3745 the changelog data, root/flat manifest data, treemanifest data, and
3747 the changelog data, root/flat manifest data, treemanifest data, and
3746 filelogs.
3748 filelogs.
3747 </p>
3749 </p>
3748 <p>
3750 <p>
3749 There are 4 versions of changegroups: &quot;1&quot;, &quot;2&quot;, &quot;3&quot; and &quot;4&quot;. From a
3751 There are 4 versions of changegroups: &quot;1&quot;, &quot;2&quot;, &quot;3&quot; and &quot;4&quot;. From a
3750 high-level, versions &quot;1&quot; and &quot;2&quot; are almost exactly the same, with the
3752 high-level, versions &quot;1&quot; and &quot;2&quot; are almost exactly the same, with the
3751 only difference being an additional item in the *delta header*. Version
3753 only difference being an additional item in the *delta header*. Version
3752 &quot;3&quot; adds support for storage flags in the *delta header* and optionally
3754 &quot;3&quot; adds support for storage flags in the *delta header* and optionally
3753 exchanging treemanifests (enabled by setting an option on the
3755 exchanging treemanifests (enabled by setting an option on the
3754 &quot;changegroup&quot; part in the bundle2). Version &quot;4&quot; adds support for exchanging
3756 &quot;changegroup&quot; part in the bundle2). Version &quot;4&quot; adds support for exchanging
3755 sidedata (additional revision metadata not part of the digest).
3757 sidedata (additional revision metadata not part of the digest).
3756 </p>
3758 </p>
3757 <p>
3759 <p>
3758 Changegroups when not exchanging treemanifests consist of 3 logical
3760 Changegroups when not exchanging treemanifests consist of 3 logical
3759 segments:
3761 segments:
3760 </p>
3762 </p>
3761 <pre>
3763 <pre>
3762 +---------------------------------+
3764 +---------------------------------+
3763 | | | |
3765 | | | |
3764 | changeset | manifest | filelogs |
3766 | changeset | manifest | filelogs |
3765 | | | |
3767 | | | |
3766 | | | |
3768 | | | |
3767 +---------------------------------+
3769 +---------------------------------+
3768 </pre>
3770 </pre>
3769 <p>
3771 <p>
3770 When exchanging treemanifests, there are 4 logical segments:
3772 When exchanging treemanifests, there are 4 logical segments:
3771 </p>
3773 </p>
3772 <pre>
3774 <pre>
3773 +-------------------------------------------------+
3775 +-------------------------------------------------+
3774 | | | | |
3776 | | | | |
3775 | changeset | root | treemanifests | filelogs |
3777 | changeset | root | treemanifests | filelogs |
3776 | | manifest | | |
3778 | | manifest | | |
3777 | | | | |
3779 | | | | |
3778 +-------------------------------------------------+
3780 +-------------------------------------------------+
3779 </pre>
3781 </pre>
3780 <p>
3782 <p>
3781 The principle building block of each segment is a *chunk*. A *chunk*
3783 The principle building block of each segment is a *chunk*. A *chunk*
3782 is a framed piece of data:
3784 is a framed piece of data:
3783 </p>
3785 </p>
3784 <pre>
3786 <pre>
3785 +---------------------------------------+
3787 +---------------------------------------+
3786 | | |
3788 | | |
3787 | length | data |
3789 | length | data |
3788 | (4 bytes) | (&lt;length - 4&gt; bytes) |
3790 | (4 bytes) | (&lt;length - 4&gt; bytes) |
3789 | | |
3791 | | |
3790 +---------------------------------------+
3792 +---------------------------------------+
3791 </pre>
3793 </pre>
3792 <p>
3794 <p>
3793 All integers are big-endian signed integers. Each chunk starts with a 32-bit
3795 All integers are big-endian signed integers. Each chunk starts with a 32-bit
3794 integer indicating the length of the entire chunk (including the length field
3796 integer indicating the length of the entire chunk (including the length field
3795 itself).
3797 itself).
3796 </p>
3798 </p>
3797 <p>
3799 <p>
3798 There is a special case chunk that has a value of 0 for the length
3800 There is a special case chunk that has a value of 0 for the length
3799 (&quot;0x00000000&quot;). We call this an *empty chunk*.
3801 (&quot;0x00000000&quot;). We call this an *empty chunk*.
3800 </p>
3802 </p>
3801 <h2>Delta Groups</h2>
3803 <h2>Delta Groups</h2>
3802 <p>
3804 <p>
3803 A *delta group* expresses the content of a revlog as a series of deltas,
3805 A *delta group* expresses the content of a revlog as a series of deltas,
3804 or patches against previous revisions.
3806 or patches against previous revisions.
3805 </p>
3807 </p>
3806 <p>
3808 <p>
3807 Delta groups consist of 0 or more *chunks* followed by the *empty chunk*
3809 Delta groups consist of 0 or more *chunks* followed by the *empty chunk*
3808 to signal the end of the delta group:
3810 to signal the end of the delta group:
3809 </p>
3811 </p>
3810 <pre>
3812 <pre>
3811 +------------------------------------------------------------------------+
3813 +------------------------------------------------------------------------+
3812 | | | | | |
3814 | | | | | |
3813 | chunk0 length | chunk0 data | chunk1 length | chunk1 data | 0x0 |
3815 | chunk0 length | chunk0 data | chunk1 length | chunk1 data | 0x0 |
3814 | (4 bytes) | (various) | (4 bytes) | (various) | (4 bytes) |
3816 | (4 bytes) | (various) | (4 bytes) | (various) | (4 bytes) |
3815 | | | | | |
3817 | | | | | |
3816 +------------------------------------------------------------------------+
3818 +------------------------------------------------------------------------+
3817 </pre>
3819 </pre>
3818 <p>
3820 <p>
3819 Each *chunk*'s data consists of the following:
3821 Each *chunk*'s data consists of the following:
3820 </p>
3822 </p>
3821 <pre>
3823 <pre>
3822 +---------------------------------------+
3824 +---------------------------------------+
3823 | | |
3825 | | |
3824 | delta header | delta data |
3826 | delta header | delta data |
3825 | (various by version) | (various) |
3827 | (various by version) | (various) |
3826 | | |
3828 | | |
3827 +---------------------------------------+
3829 +---------------------------------------+
3828 </pre>
3830 </pre>
3829 <p>
3831 <p>
3830 The *delta data* is a series of *delta*s that describe a diff from an existing
3832 The *delta data* is a series of *delta*s that describe a diff from an existing
3831 entry (either that the recipient already has, or previously specified in the
3833 entry (either that the recipient already has, or previously specified in the
3832 bundle/changegroup).
3834 bundle/changegroup).
3833 </p>
3835 </p>
3834 <p>
3836 <p>
3835 The *delta header* is different between versions &quot;1&quot;, &quot;2&quot;, &quot;3&quot; and &quot;4&quot;
3837 The *delta header* is different between versions &quot;1&quot;, &quot;2&quot;, &quot;3&quot; and &quot;4&quot;
3836 of the changegroup format.
3838 of the changegroup format.
3837 </p>
3839 </p>
3838 <p>
3840 <p>
3839 Version 1 (headerlen=80):
3841 Version 1 (headerlen=80):
3840 </p>
3842 </p>
3841 <pre>
3843 <pre>
3842 +------------------------------------------------------+
3844 +------------------------------------------------------+
3843 | | | | |
3845 | | | | |
3844 | node | p1 node | p2 node | link node |
3846 | node | p1 node | p2 node | link node |
3845 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
3847 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
3846 | | | | |
3848 | | | | |
3847 +------------------------------------------------------+
3849 +------------------------------------------------------+
3848 </pre>
3850 </pre>
3849 <p>
3851 <p>
3850 Version 2 (headerlen=100):
3852 Version 2 (headerlen=100):
3851 </p>
3853 </p>
3852 <pre>
3854 <pre>
3853 +------------------------------------------------------------------+
3855 +------------------------------------------------------------------+
3854 | | | | | |
3856 | | | | | |
3855 | node | p1 node | p2 node | base node | link node |
3857 | node | p1 node | p2 node | base node | link node |
3856 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
3858 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) |
3857 | | | | | |
3859 | | | | | |
3858 +------------------------------------------------------------------+
3860 +------------------------------------------------------------------+
3859 </pre>
3861 </pre>
3860 <p>
3862 <p>
3861 Version 3 (headerlen=102):
3863 Version 3 (headerlen=102):
3862 </p>
3864 </p>
3863 <pre>
3865 <pre>
3864 +------------------------------------------------------------------------------+
3866 +------------------------------------------------------------------------------+
3865 | | | | | | |
3867 | | | | | | |
3866 | node | p1 node | p2 node | base node | link node | flags |
3868 | node | p1 node | p2 node | base node | link node | flags |
3867 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (2 bytes) |
3869 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (2 bytes) |
3868 | | | | | | |
3870 | | | | | | |
3869 +------------------------------------------------------------------------------+
3871 +------------------------------------------------------------------------------+
3870 </pre>
3872 </pre>
3871 <p>
3873 <p>
3872 Version 4 (headerlen=103):
3874 Version 4 (headerlen=103):
3873 </p>
3875 </p>
3874 <pre>
3876 <pre>
3875 +------------------------------------------------------------------------------+----------+
3877 +------------------------------------------------------------------------------+----------+
3876 | | | | | | | |
3878 | | | | | | | |
3877 | node | p1 node | p2 node | base node | link node | flags | pflags |
3879 | node | p1 node | p2 node | base node | link node | flags | pflags |
3878 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (2 bytes) | (1 byte) |
3880 | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (20 bytes) | (2 bytes) | (1 byte) |
3879 | | | | | | | |
3881 | | | | | | | |
3880 +------------------------------------------------------------------------------+----------+
3882 +------------------------------------------------------------------------------+----------+
3881 </pre>
3883 </pre>
3882 <p>
3884 <p>
3883 The *delta data* consists of &quot;chunklen - 4 - headerlen&quot; bytes, which contain a
3885 The *delta data* consists of &quot;chunklen - 4 - headerlen&quot; bytes, which contain a
3884 series of *delta*s, densely packed (no separators). These deltas describe a diff
3886 series of *delta*s, densely packed (no separators). These deltas describe a diff
3885 from an existing entry (either that the recipient already has, or previously
3887 from an existing entry (either that the recipient already has, or previously
3886 specified in the bundle/changegroup). The format is described more fully in
3888 specified in the bundle/changegroup). The format is described more fully in
3887 &quot;hg help internals.bdiff&quot;, but briefly:
3889 &quot;hg help internals.bdiff&quot;, but briefly:
3888 </p>
3890 </p>
3889 <pre>
3891 <pre>
3890 +---------------------------------------------------------------+
3892 +---------------------------------------------------------------+
3891 | | | | |
3893 | | | | |
3892 | start offset | end offset | new length | content |
3894 | start offset | end offset | new length | content |
3893 | (4 bytes) | (4 bytes) | (4 bytes) | (&lt;new length&gt; bytes) |
3895 | (4 bytes) | (4 bytes) | (4 bytes) | (&lt;new length&gt; bytes) |
3894 | | | | |
3896 | | | | |
3895 +---------------------------------------------------------------+
3897 +---------------------------------------------------------------+
3896 </pre>
3898 </pre>
3897 <p>
3899 <p>
3898 Please note that the length field in the delta data does *not* include itself.
3900 Please note that the length field in the delta data does *not* include itself.
3899 </p>
3901 </p>
3900 <p>
3902 <p>
3901 In version 1, the delta is always applied against the previous node from
3903 In version 1, the delta is always applied against the previous node from
3902 the changegroup or the first parent if this is the first entry in the
3904 the changegroup or the first parent if this is the first entry in the
3903 changegroup.
3905 changegroup.
3904 </p>
3906 </p>
3905 <p>
3907 <p>
3906 In version 2 and up, the delta base node is encoded in the entry in the
3908 In version 2 and up, the delta base node is encoded in the entry in the
3907 changegroup. This allows the delta to be expressed against any parent,
3909 changegroup. This allows the delta to be expressed against any parent,
3908 which can result in smaller deltas and more efficient encoding of data.
3910 which can result in smaller deltas and more efficient encoding of data.
3909 </p>
3911 </p>
3910 <p>
3912 <p>
3911 The *flags* field holds bitwise flags affecting the processing of revision
3913 The *flags* field holds bitwise flags affecting the processing of revision
3912 data. The following flags are defined:
3914 data. The following flags are defined:
3913 </p>
3915 </p>
3914 <dl>
3916 <dl>
3915 <dt>32768
3917 <dt>32768
3916 <dd>Censored revision. The revision's fulltext has been replaced by censor metadata. May only occur on file revisions.
3918 <dd>Censored revision. The revision's fulltext has been replaced by censor metadata. May only occur on file revisions.
3917 <dt>16384
3919 <dt>16384
3918 <dd>Ellipsis revision. Revision hash does not match data (likely due to rewritten parents).
3920 <dd>Ellipsis revision. Revision hash does not match data (likely due to rewritten parents).
3919 <dt>8192
3921 <dt>8192
3920 <dd>Externally stored. The revision fulltext contains &quot;key:value&quot; &quot;\n&quot; delimited metadata defining an object stored elsewhere. Used by the LFS extension.
3922 <dd>Externally stored. The revision fulltext contains &quot;key:value&quot; &quot;\n&quot; delimited metadata defining an object stored elsewhere. Used by the LFS extension.
3921 <dt>4096
3923 <dt>4096
3922 <dd>Contains copy information. This revision changes files in a way that could affect copy tracing. This does *not* affect changegroup handling, but is relevant for other parts of Mercurial.
3924 <dd>Contains copy information. This revision changes files in a way that could affect copy tracing. This does *not* affect changegroup handling, but is relevant for other parts of Mercurial.
3923 </dl>
3925 </dl>
3924 <p>
3926 <p>
3925 For historical reasons, the integer values are identical to revlog version 1
3927 For historical reasons, the integer values are identical to revlog version 1
3926 per-revision storage flags and correspond to bits being set in this 2-byte
3928 per-revision storage flags and correspond to bits being set in this 2-byte
3927 field. Bits were allocated starting from the most-significant bit, hence the
3929 field. Bits were allocated starting from the most-significant bit, hence the
3928 reverse ordering and allocation of these flags.
3930 reverse ordering and allocation of these flags.
3929 </p>
3931 </p>
3930 <p>
3932 <p>
3931 The *pflags* (protocol flags) field holds bitwise flags affecting the protocol
3933 The *pflags* (protocol flags) field holds bitwise flags affecting the protocol
3932 itself. They are first in the header since they may affect the handling of the
3934 itself. They are first in the header since they may affect the handling of the
3933 rest of the fields in a future version. They are defined as such:
3935 rest of the fields in a future version. They are defined as such:
3934 </p>
3936 </p>
3935 <dl>
3937 <dl>
3936 <dt>1 indicates whether to read a chunk of sidedata (of variable length) right
3938 <dt>1 indicates whether to read a chunk of sidedata (of variable length) right
3937 <dd>after the revision flags.
3939 <dd>after the revision flags.
3938 </dl>
3940 </dl>
3939 <h2>Changeset Segment</h2>
3941 <h2>Changeset Segment</h2>
3940 <p>
3942 <p>
3941 The *changeset segment* consists of a single *delta group* holding
3943 The *changeset segment* consists of a single *delta group* holding
3942 changelog data. The *empty chunk* at the end of the *delta group* denotes
3944 changelog data. The *empty chunk* at the end of the *delta group* denotes
3943 the boundary to the *manifest segment*.
3945 the boundary to the *manifest segment*.
3944 </p>
3946 </p>
3945 <h2>Manifest Segment</h2>
3947 <h2>Manifest Segment</h2>
3946 <p>
3948 <p>
3947 The *manifest segment* consists of a single *delta group* holding manifest
3949 The *manifest segment* consists of a single *delta group* holding manifest
3948 data. If treemanifests are in use, it contains only the manifest for the
3950 data. If treemanifests are in use, it contains only the manifest for the
3949 root directory of the repository. Otherwise, it contains the entire
3951 root directory of the repository. Otherwise, it contains the entire
3950 manifest data. The *empty chunk* at the end of the *delta group* denotes
3952 manifest data. The *empty chunk* at the end of the *delta group* denotes
3951 the boundary to the next segment (either the *treemanifests segment* or the
3953 the boundary to the next segment (either the *treemanifests segment* or the
3952 *filelogs segment*, depending on version and the request options).
3954 *filelogs segment*, depending on version and the request options).
3953 </p>
3955 </p>
3954 <h3>Treemanifests Segment</h3>
3956 <h3>Treemanifests Segment</h3>
3955 <p>
3957 <p>
3956 The *treemanifests segment* only exists in changegroup version &quot;3&quot; and &quot;4&quot;,
3958 The *treemanifests segment* only exists in changegroup version &quot;3&quot; and &quot;4&quot;,
3957 and only if the 'treemanifest' param is part of the bundle2 changegroup part
3959 and only if the 'treemanifest' param is part of the bundle2 changegroup part
3958 (it is not possible to use changegroup version 3 or 4 outside of bundle2).
3960 (it is not possible to use changegroup version 3 or 4 outside of bundle2).
3959 Aside from the filenames in the *treemanifests segment* containing a
3961 Aside from the filenames in the *treemanifests segment* containing a
3960 trailing &quot;/&quot; character, it behaves identically to the *filelogs segment*
3962 trailing &quot;/&quot; character, it behaves identically to the *filelogs segment*
3961 (see below). The final sub-segment is followed by an *empty chunk* (logically,
3963 (see below). The final sub-segment is followed by an *empty chunk* (logically,
3962 a sub-segment with filename size 0). This denotes the boundary to the
3964 a sub-segment with filename size 0). This denotes the boundary to the
3963 *filelogs segment*.
3965 *filelogs segment*.
3964 </p>
3966 </p>
3965 <h2>Filelogs Segment</h2>
3967 <h2>Filelogs Segment</h2>
3966 <p>
3968 <p>
3967 The *filelogs segment* consists of multiple sub-segments, each
3969 The *filelogs segment* consists of multiple sub-segments, each
3968 corresponding to an individual file whose data is being described:
3970 corresponding to an individual file whose data is being described:
3969 </p>
3971 </p>
3970 <pre>
3972 <pre>
3971 +--------------------------------------------------+
3973 +--------------------------------------------------+
3972 | | | | | |
3974 | | | | | |
3973 | filelog0 | filelog1 | filelog2 | ... | 0x0 |
3975 | filelog0 | filelog1 | filelog2 | ... | 0x0 |
3974 | | | | | (4 bytes) |
3976 | | | | | (4 bytes) |
3975 | | | | | |
3977 | | | | | |
3976 +--------------------------------------------------+
3978 +--------------------------------------------------+
3977 </pre>
3979 </pre>
3978 <p>
3980 <p>
3979 The final filelog sub-segment is followed by an *empty chunk* (logically,
3981 The final filelog sub-segment is followed by an *empty chunk* (logically,
3980 a sub-segment with filename size 0). This denotes the end of the segment
3982 a sub-segment with filename size 0). This denotes the end of the segment
3981 and of the overall changegroup.
3983 and of the overall changegroup.
3982 </p>
3984 </p>
3983 <p>
3985 <p>
3984 Each filelog sub-segment consists of the following:
3986 Each filelog sub-segment consists of the following:
3985 </p>
3987 </p>
3986 <pre>
3988 <pre>
3987 +------------------------------------------------------+
3989 +------------------------------------------------------+
3988 | | | |
3990 | | | |
3989 | filename length | filename | delta group |
3991 | filename length | filename | delta group |
3990 | (4 bytes) | (&lt;length - 4&gt; bytes) | (various) |
3992 | (4 bytes) | (&lt;length - 4&gt; bytes) | (various) |
3991 | | | |
3993 | | | |
3992 +------------------------------------------------------+
3994 +------------------------------------------------------+
3993 </pre>
3995 </pre>
3994 <p>
3996 <p>
3995 That is, a *chunk* consisting of the filename (not terminated or padded)
3997 That is, a *chunk* consisting of the filename (not terminated or padded)
3996 followed by N chunks constituting the *delta group* for this file. The
3998 followed by N chunks constituting the *delta group* for this file. The
3997 *empty chunk* at the end of each *delta group* denotes the boundary to the
3999 *empty chunk* at the end of each *delta group* denotes the boundary to the
3998 next filelog sub-segment.
4000 next filelog sub-segment.
3999 </p>
4001 </p>
4000
4002
4001 </div>
4003 </div>
4002 </div>
4004 </div>
4003 </div>
4005 </div>
4004
4006
4005
4007
4006
4008
4007 </body>
4009 </body>
4008 </html>
4010 </html>
4009
4011
4010
4012
4011 $ get-with-headers.py 127.0.0.1:$HGPORT "help/unknowntopic"
4013 $ get-with-headers.py 127.0.0.1:$HGPORT "help/unknowntopic"
4012 404 Not Found
4014 404 Not Found
4013
4015
4014 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4016 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4015 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
4017 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
4016 <head>
4018 <head>
4017 <link rel="icon" href="/static/hgicon.png" type="image/png" />
4019 <link rel="icon" href="/static/hgicon.png" type="image/png" />
4018 <meta name="robots" content="index, nofollow" />
4020 <meta name="robots" content="index, nofollow" />
4019 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
4021 <link rel="stylesheet" href="/static/style-paper.css" type="text/css" />
4020 <script type="text/javascript" src="/static/mercurial.js"></script>
4022 <script type="text/javascript" src="/static/mercurial.js"></script>
4021
4023
4022 <title>test: error</title>
4024 <title>test: error</title>
4023 </head>
4025 </head>
4024 <body>
4026 <body>
4025
4027
4026 <div class="container">
4028 <div class="container">
4027 <div class="menu">
4029 <div class="menu">
4028 <div class="logo">
4030 <div class="logo">
4029 <a href="https://mercurial-scm.org/">
4031 <a href="https://mercurial-scm.org/">
4030 <img src="/static/hglogo.png" width=75 height=90 border=0 alt="mercurial" /></a>
4032 <img src="/static/hglogo.png" width=75 height=90 border=0 alt="mercurial" /></a>
4031 </div>
4033 </div>
4032 <ul>
4034 <ul>
4033 <li><a href="/shortlog">log</a></li>
4035 <li><a href="/shortlog">log</a></li>
4034 <li><a href="/graph">graph</a></li>
4036 <li><a href="/graph">graph</a></li>
4035 <li><a href="/tags">tags</a></li>
4037 <li><a href="/tags">tags</a></li>
4036 <li><a href="/bookmarks">bookmarks</a></li>
4038 <li><a href="/bookmarks">bookmarks</a></li>
4037 <li><a href="/branches">branches</a></li>
4039 <li><a href="/branches">branches</a></li>
4038 </ul>
4040 </ul>
4039 <ul>
4041 <ul>
4040 <li><a href="/help">help</a></li>
4042 <li><a href="/help">help</a></li>
4041 </ul>
4043 </ul>
4042 </div>
4044 </div>
4043
4045
4044 <div class="main">
4046 <div class="main">
4045
4047
4046 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
4048 <h2 class="breadcrumb"><a href="/">Mercurial</a> </h2>
4047 <h3>error</h3>
4049 <h3>error</h3>
4048
4050
4049
4051
4050 <form class="search" action="/log">
4052 <form class="search" action="/log">
4051
4053
4052 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
4054 <p><input name="rev" id="search1" type="text" size="30" value="" /></p>
4053 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
4055 <div id="hint">Find changesets by keywords (author, files, the commit message), revision
4054 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
4056 number or hash, or <a href="/help/revsets">revset expression</a>.</div>
4055 </form>
4057 </form>
4056
4058
4057 <div class="description">
4059 <div class="description">
4058 <p>
4060 <p>
4059 An error occurred while processing your request:
4061 An error occurred while processing your request:
4060 </p>
4062 </p>
4061 <p>
4063 <p>
4062 Not Found
4064 Not Found
4063 </p>
4065 </p>
4064 </div>
4066 </div>
4065 </div>
4067 </div>
4066 </div>
4068 </div>
4067
4069
4068
4070
4069
4071
4070 </body>
4072 </body>
4071 </html>
4073 </html>
4072
4074
4073 [1]
4075 [1]
4074
4076
4075 $ killdaemons.py
4077 $ killdaemons.py
4076
4078
4077 #endif
4079 #endif
General Comments 0
You need to be logged in to leave comments. Login now