##// END OF EJS Templates
merge with stable
Matt Mackall -
r16373:329887a7 merge default
parent child Browse files
Show More
@@ -1,433 +1,435 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 #
2 #
3 # check-code - a style and portability checker for Mercurial
3 # check-code - a style and portability checker for Mercurial
4 #
4 #
5 # Copyright 2010 Matt Mackall <mpm@selenic.com>
5 # Copyright 2010 Matt Mackall <mpm@selenic.com>
6 #
6 #
7 # This software may be used and distributed according to the terms of the
7 # This software may be used and distributed according to the terms of the
8 # GNU General Public License version 2 or any later version.
8 # GNU General Public License version 2 or any later version.
9
9
10 import re, glob, os, sys
10 import re, glob, os, sys
11 import keyword
11 import keyword
12 import optparse
12 import optparse
13
13
14 def repquote(m):
14 def repquote(m):
15 t = re.sub(r"\w", "x", m.group('text'))
15 t = re.sub(r"\w", "x", m.group('text'))
16 t = re.sub(r"[^\s\nx]", "o", t)
16 t = re.sub(r"[^\s\nx]", "o", t)
17 return m.group('quote') + t + m.group('quote')
17 return m.group('quote') + t + m.group('quote')
18
18
19 def reppython(m):
19 def reppython(m):
20 comment = m.group('comment')
20 comment = m.group('comment')
21 if comment:
21 if comment:
22 return "#" * len(comment)
22 return "#" * len(comment)
23 return repquote(m)
23 return repquote(m)
24
24
25 def repcomment(m):
25 def repcomment(m):
26 return m.group(1) + "#" * len(m.group(2))
26 return m.group(1) + "#" * len(m.group(2))
27
27
28 def repccomment(m):
28 def repccomment(m):
29 t = re.sub(r"((?<=\n) )|\S", "x", m.group(2))
29 t = re.sub(r"((?<=\n) )|\S", "x", m.group(2))
30 return m.group(1) + t + "*/"
30 return m.group(1) + t + "*/"
31
31
32 def repcallspaces(m):
32 def repcallspaces(m):
33 t = re.sub(r"\n\s+", "\n", m.group(2))
33 t = re.sub(r"\n\s+", "\n", m.group(2))
34 return m.group(1) + t
34 return m.group(1) + t
35
35
36 def repinclude(m):
36 def repinclude(m):
37 return m.group(1) + "<foo>"
37 return m.group(1) + "<foo>"
38
38
39 def rephere(m):
39 def rephere(m):
40 t = re.sub(r"\S", "x", m.group(2))
40 t = re.sub(r"\S", "x", m.group(2))
41 return m.group(1) + t
41 return m.group(1) + t
42
42
43
43
44 testpats = [
44 testpats = [
45 [
45 [
46 (r'(pushd|popd)', "don't use 'pushd' or 'popd', use 'cd'"),
46 (r'(pushd|popd)', "don't use 'pushd' or 'popd', use 'cd'"),
47 (r'\W\$?\(\([^\)\n]*\)\)', "don't use (()) or $(()), use 'expr'"),
47 (r'\W\$?\(\([^\)\n]*\)\)', "don't use (()) or $(()), use 'expr'"),
48 (r'^function', "don't use 'function', use old style"),
48 (r'^function', "don't use 'function', use old style"),
49 (r'grep.*-q', "don't use 'grep -q', redirect to /dev/null"),
49 (r'grep.*-q', "don't use 'grep -q', redirect to /dev/null"),
50 (r'sed.*-i', "don't use 'sed -i', use a temporary file"),
50 (r'sed.*-i', "don't use 'sed -i', use a temporary file"),
51 (r'echo.*\\n', "don't use 'echo \\n', use printf"),
51 (r'echo.*\\n', "don't use 'echo \\n', use printf"),
52 (r'echo -n', "don't use 'echo -n', use printf"),
52 (r'echo -n', "don't use 'echo -n', use printf"),
53 (r'^diff.*-\w*N', "don't use 'diff -N'"),
53 (r'^diff.*-\w*N', "don't use 'diff -N'"),
54 (r'(^| )wc[^|]*$\n(?!.*\(re\))', "filter wc output"),
54 (r'(^| )wc[^|]*$\n(?!.*\(re\))', "filter wc output"),
55 (r'head -c', "don't use 'head -c', use 'dd'"),
55 (r'head -c', "don't use 'head -c', use 'dd'"),
56 (r'sha1sum', "don't use sha1sum, use $TESTDIR/md5sum.py"),
56 (r'sha1sum', "don't use sha1sum, use $TESTDIR/md5sum.py"),
57 (r'ls.*-\w*R', "don't use 'ls -R', use 'find'"),
57 (r'ls.*-\w*R', "don't use 'ls -R', use 'find'"),
58 (r'printf.*\\\d{1,3}', "don't use 'printf \NNN', use Python"),
58 (r'printf.*\\\d{1,3}', "don't use 'printf \NNN', use Python"),
59 (r'printf.*\\x', "don't use printf \\x, use Python"),
59 (r'printf.*\\x', "don't use printf \\x, use Python"),
60 (r'\$\(.*\)', "don't use $(expr), use `expr`"),
60 (r'\$\(.*\)', "don't use $(expr), use `expr`"),
61 (r'rm -rf \*', "don't use naked rm -rf, target a directory"),
61 (r'rm -rf \*', "don't use naked rm -rf, target a directory"),
62 (r'(^|\|\s*)grep (-\w\s+)*[^|]*[(|]\w',
62 (r'(^|\|\s*)grep (-\w\s+)*[^|]*[(|]\w',
63 "use egrep for extended grep syntax"),
63 "use egrep for extended grep syntax"),
64 (r'/bin/', "don't use explicit paths for tools"),
64 (r'/bin/', "don't use explicit paths for tools"),
65 (r'\$PWD', "don't use $PWD, use `pwd`"),
65 (r'\$PWD', "don't use $PWD, use `pwd`"),
66 (r'[^\n]\Z', "no trailing newline"),
66 (r'[^\n]\Z', "no trailing newline"),
67 (r'export.*=', "don't export and assign at once"),
67 (r'export.*=', "don't export and assign at once"),
68 (r'^([^"\'\n]|("[^"\n]*")|(\'[^\'\n]*\'))*\\^', "^ must be quoted"),
68 (r'^([^"\'\n]|("[^"\n]*")|(\'[^\'\n]*\'))*\\^', "^ must be quoted"),
69 (r'^source\b', "don't use 'source', use '.'"),
69 (r'^source\b', "don't use 'source', use '.'"),
70 (r'touch -d', "don't use 'touch -d', use 'touch -t' instead"),
70 (r'touch -d', "don't use 'touch -d', use 'touch -t' instead"),
71 (r'ls +[^|\n-]+ +-', "options to 'ls' must come before filenames"),
71 (r'ls +[^|\n-]+ +-', "options to 'ls' must come before filenames"),
72 (r'[^>\n]>\s*\$HGRCPATH', "don't overwrite $HGRCPATH, append to it"),
72 (r'[^>\n]>\s*\$HGRCPATH', "don't overwrite $HGRCPATH, append to it"),
73 (r'^stop\(\)', "don't use 'stop' as a shell function name"),
73 (r'^stop\(\)', "don't use 'stop' as a shell function name"),
74 (r'(\[|\btest\b).*-e ', "don't use 'test -e', use 'test -f'"),
74 (r'(\[|\btest\b).*-e ', "don't use 'test -e', use 'test -f'"),
75 (r'^alias\b.*=', "don't use alias, use a function"),
75 (r'^alias\b.*=', "don't use alias, use a function"),
76 ],
76 ],
77 # warnings
77 # warnings
78 []
78 []
79 ]
79 ]
80
80
81 testfilters = [
81 testfilters = [
82 (r"( *)(#([^\n]*\S)?)", repcomment),
82 (r"( *)(#([^\n]*\S)?)", repcomment),
83 (r"<<(\S+)((.|\n)*?\n\1)", rephere),
83 (r"<<(\S+)((.|\n)*?\n\1)", rephere),
84 ]
84 ]
85
85
86 uprefix = r"^ \$ "
86 uprefix = r"^ \$ "
87 uprefixc = r"^ > "
87 uprefixc = r"^ > "
88 utestpats = [
88 utestpats = [
89 [
89 [
90 (r'^(\S| $ ).*(\S[ \t]+|^[ \t]+)\n', "trailing whitespace on non-output"),
90 (r'^(\S| $ ).*(\S[ \t]+|^[ \t]+)\n', "trailing whitespace on non-output"),
91 (uprefix + r'.*\|\s*sed', "use regex test output patterns instead of sed"),
91 (uprefix + r'.*\|\s*sed', "use regex test output patterns instead of sed"),
92 (uprefix + r'(true|exit 0)', "explicit zero exit unnecessary"),
92 (uprefix + r'(true|exit 0)', "explicit zero exit unnecessary"),
93 (uprefix + r'.*(?<!\[)\$\?', "explicit exit code checks unnecessary"),
93 (uprefix + r'.*(?<!\[)\$\?', "explicit exit code checks unnecessary"),
94 (uprefix + r'.*\|\| echo.*(fail|error)',
94 (uprefix + r'.*\|\| echo.*(fail|error)',
95 "explicit exit code checks unnecessary"),
95 "explicit exit code checks unnecessary"),
96 (uprefix + r'set -e', "don't use set -e"),
96 (uprefix + r'set -e', "don't use set -e"),
97 (uprefixc + r'( *)\t', "don't use tabs to indent"),
97 (uprefixc + r'( *)\t', "don't use tabs to indent"),
98 (uprefixc + r'.*do\s*true;\s*done',
99 "don't use true as loop body, use sleep 0"),
98 ],
100 ],
99 # warnings
101 # warnings
100 []
102 []
101 ]
103 ]
102
104
103 for i in [0, 1]:
105 for i in [0, 1]:
104 for p, m in testpats[i]:
106 for p, m in testpats[i]:
105 if p.startswith(r'^'):
107 if p.startswith(r'^'):
106 p = uprefix + p[1:]
108 p = uprefix + p[1:]
107 else:
109 else:
108 p = uprefix + ".*" + p
110 p = uprefix + ".*" + p
109 utestpats[i].append((p, m))
111 utestpats[i].append((p, m))
110
112
111 utestfilters = [
113 utestfilters = [
112 (r"( *)(#([^\n]*\S)?)", repcomment),
114 (r"( *)(#([^\n]*\S)?)", repcomment),
113 ]
115 ]
114
116
115 pypats = [
117 pypats = [
116 [
118 [
117 (r'^\s*def\s*\w+\s*\(.*,\s*\(',
119 (r'^\s*def\s*\w+\s*\(.*,\s*\(',
118 "tuple parameter unpacking not available in Python 3+"),
120 "tuple parameter unpacking not available in Python 3+"),
119 (r'lambda\s*\(.*,.*\)',
121 (r'lambda\s*\(.*,.*\)',
120 "tuple parameter unpacking not available in Python 3+"),
122 "tuple parameter unpacking not available in Python 3+"),
121 (r'(?<!def)\s+(cmp)\(', "cmp is not available in Python 3+"),
123 (r'(?<!def)\s+(cmp)\(', "cmp is not available in Python 3+"),
122 (r'\breduce\s*\(.*', "reduce is not available in Python 3+"),
124 (r'\breduce\s*\(.*', "reduce is not available in Python 3+"),
123 (r'\.has_key\b', "dict.has_key is not available in Python 3+"),
125 (r'\.has_key\b', "dict.has_key is not available in Python 3+"),
124 (r'^\s*\t', "don't use tabs"),
126 (r'^\s*\t', "don't use tabs"),
125 (r'\S;\s*\n', "semicolon"),
127 (r'\S;\s*\n', "semicolon"),
126 (r'[^_]_\("[^"]+"\s*%', "don't use % inside _()"),
128 (r'[^_]_\("[^"]+"\s*%', "don't use % inside _()"),
127 (r"[^_]_\('[^']+'\s*%", "don't use % inside _()"),
129 (r"[^_]_\('[^']+'\s*%", "don't use % inside _()"),
128 (r'\w,\w', "missing whitespace after ,"),
130 (r'\w,\w', "missing whitespace after ,"),
129 (r'\w[+/*\-<>]\w', "missing whitespace in expression"),
131 (r'\w[+/*\-<>]\w', "missing whitespace in expression"),
130 (r'^\s+\w+=\w+[^,)\n]$', "missing whitespace in assignment"),
132 (r'^\s+\w+=\w+[^,)\n]$', "missing whitespace in assignment"),
131 (r'(\s+)try:\n((?:\n|\1\s.*\n)+?)\1except.*?:\n'
133 (r'(\s+)try:\n((?:\n|\1\s.*\n)+?)\1except.*?:\n'
132 r'((?:\n|\1\s.*\n)+?)\1finally:', 'no try/except/finally in Py2.4'),
134 r'((?:\n|\1\s.*\n)+?)\1finally:', 'no try/except/finally in Py2.4'),
133 (r'.{85}', "line too long"),
135 (r'.{85}', "line too long"),
134 (r' x+[xo][\'"]\n\s+[\'"]x', 'string join across lines with no space'),
136 (r' x+[xo][\'"]\n\s+[\'"]x', 'string join across lines with no space'),
135 (r'[^\n]\Z', "no trailing newline"),
137 (r'[^\n]\Z', "no trailing newline"),
136 (r'(\S[ \t]+|^[ \t]+)\n', "trailing whitespace"),
138 (r'(\S[ \t]+|^[ \t]+)\n', "trailing whitespace"),
137 # (r'^\s+[^_ \n][^_. \n]+_[^_\n]+\s*=', "don't use underbars in identifiers"),
139 # (r'^\s+[^_ \n][^_. \n]+_[^_\n]+\s*=', "don't use underbars in identifiers"),
138 (r'^\s+(self\.)?[A-za-z][a-z0-9]+[A-Z]\w* = ',
140 (r'^\s+(self\.)?[A-za-z][a-z0-9]+[A-Z]\w* = ',
139 "don't use camelcase in identifiers"),
141 "don't use camelcase in identifiers"),
140 (r'^\s*(if|while|def|class|except|try)\s[^[\n]*:\s*[^\\n]#\s]+',
142 (r'^\s*(if|while|def|class|except|try)\s[^[\n]*:\s*[^\\n]#\s]+',
141 "linebreak after :"),
143 "linebreak after :"),
142 (r'class\s[^( \n]+:', "old-style class, use class foo(object)"),
144 (r'class\s[^( \n]+:', "old-style class, use class foo(object)"),
143 (r'class\s[^( \n]+\(\):',
145 (r'class\s[^( \n]+\(\):',
144 "class foo() not available in Python 2.4, use class foo(object)"),
146 "class foo() not available in Python 2.4, use class foo(object)"),
145 (r'\b(%s)\(' % '|'.join(keyword.kwlist),
147 (r'\b(%s)\(' % '|'.join(keyword.kwlist),
146 "Python keyword is not a function"),
148 "Python keyword is not a function"),
147 (r',]', "unneeded trailing ',' in list"),
149 (r',]', "unneeded trailing ',' in list"),
148 # (r'class\s[A-Z][^\(]*\((?!Exception)',
150 # (r'class\s[A-Z][^\(]*\((?!Exception)',
149 # "don't capitalize non-exception classes"),
151 # "don't capitalize non-exception classes"),
150 # (r'in range\(', "use xrange"),
152 # (r'in range\(', "use xrange"),
151 # (r'^\s*print\s+', "avoid using print in core and extensions"),
153 # (r'^\s*print\s+', "avoid using print in core and extensions"),
152 (r'[\x80-\xff]', "non-ASCII character literal"),
154 (r'[\x80-\xff]', "non-ASCII character literal"),
153 (r'("\')\.format\(', "str.format() not available in Python 2.4"),
155 (r'("\')\.format\(', "str.format() not available in Python 2.4"),
154 (r'^\s*with\s+', "with not available in Python 2.4"),
156 (r'^\s*with\s+', "with not available in Python 2.4"),
155 (r'\.isdisjoint\(', "set.isdisjoint not available in Python 2.4"),
157 (r'\.isdisjoint\(', "set.isdisjoint not available in Python 2.4"),
156 (r'^\s*except.* as .*:', "except as not available in Python 2.4"),
158 (r'^\s*except.* as .*:', "except as not available in Python 2.4"),
157 (r'^\s*os\.path\.relpath', "relpath not available in Python 2.4"),
159 (r'^\s*os\.path\.relpath', "relpath not available in Python 2.4"),
158 (r'(?<!def)\s+(any|all|format)\(',
160 (r'(?<!def)\s+(any|all|format)\(',
159 "any/all/format not available in Python 2.4"),
161 "any/all/format not available in Python 2.4"),
160 (r'(?<!def)\s+(callable)\(',
162 (r'(?<!def)\s+(callable)\(',
161 "callable not available in Python 3, use getattr(f, '__call__', None)"),
163 "callable not available in Python 3, use getattr(f, '__call__', None)"),
162 (r'if\s.*\selse', "if ... else form not available in Python 2.4"),
164 (r'if\s.*\selse', "if ... else form not available in Python 2.4"),
163 (r'^\s*(%s)\s\s' % '|'.join(keyword.kwlist),
165 (r'^\s*(%s)\s\s' % '|'.join(keyword.kwlist),
164 "gratuitous whitespace after Python keyword"),
166 "gratuitous whitespace after Python keyword"),
165 (r'([\(\[][ \t]\S)|(\S[ \t][\)\]])', "gratuitous whitespace in () or []"),
167 (r'([\(\[][ \t]\S)|(\S[ \t][\)\]])', "gratuitous whitespace in () or []"),
166 # (r'\s\s=', "gratuitous whitespace before ="),
168 # (r'\s\s=', "gratuitous whitespace before ="),
167 (r'[^>< ](\+=|-=|!=|<>|<=|>=|<<=|>>=)\S',
169 (r'[^>< ](\+=|-=|!=|<>|<=|>=|<<=|>>=)\S',
168 "missing whitespace around operator"),
170 "missing whitespace around operator"),
169 (r'[^>< ](\+=|-=|!=|<>|<=|>=|<<=|>>=)\s',
171 (r'[^>< ](\+=|-=|!=|<>|<=|>=|<<=|>>=)\s',
170 "missing whitespace around operator"),
172 "missing whitespace around operator"),
171 (r'\s(\+=|-=|!=|<>|<=|>=|<<=|>>=)\S',
173 (r'\s(\+=|-=|!=|<>|<=|>=|<<=|>>=)\S',
172 "missing whitespace around operator"),
174 "missing whitespace around operator"),
173 (r'[^^+=*/!<>&| -](\s=|=\s)[^= ]',
175 (r'[^^+=*/!<>&| -](\s=|=\s)[^= ]',
174 "wrong whitespace around ="),
176 "wrong whitespace around ="),
175 (r'raise Exception', "don't raise generic exceptions"),
177 (r'raise Exception', "don't raise generic exceptions"),
176 (r' is\s+(not\s+)?["\'0-9-]', "object comparison with literal"),
178 (r' is\s+(not\s+)?["\'0-9-]', "object comparison with literal"),
177 (r' [=!]=\s+(True|False|None)',
179 (r' [=!]=\s+(True|False|None)',
178 "comparison with singleton, use 'is' or 'is not' instead"),
180 "comparison with singleton, use 'is' or 'is not' instead"),
179 (r'^\s*(while|if) [01]:',
181 (r'^\s*(while|if) [01]:',
180 "use True/False for constant Boolean expression"),
182 "use True/False for constant Boolean expression"),
181 (r'(?<!def)\s+hasattr',
183 (r'(?<!def)\s+hasattr',
182 'hasattr(foo, bar) is broken, use util.safehasattr(foo, bar) instead'),
184 'hasattr(foo, bar) is broken, use util.safehasattr(foo, bar) instead'),
183 (r'opener\([^)]*\).read\(',
185 (r'opener\([^)]*\).read\(',
184 "use opener.read() instead"),
186 "use opener.read() instead"),
185 (r'BaseException', 'not in Py2.4, use Exception'),
187 (r'BaseException', 'not in Py2.4, use Exception'),
186 (r'os\.path\.relpath', 'os.path.relpath is not in Py2.5'),
188 (r'os\.path\.relpath', 'os.path.relpath is not in Py2.5'),
187 (r'opener\([^)]*\).write\(',
189 (r'opener\([^)]*\).write\(',
188 "use opener.write() instead"),
190 "use opener.write() instead"),
189 (r'[\s\(](open|file)\([^)]*\)\.read\(',
191 (r'[\s\(](open|file)\([^)]*\)\.read\(',
190 "use util.readfile() instead"),
192 "use util.readfile() instead"),
191 (r'[\s\(](open|file)\([^)]*\)\.write\(',
193 (r'[\s\(](open|file)\([^)]*\)\.write\(',
192 "use util.readfile() instead"),
194 "use util.readfile() instead"),
193 (r'^[\s\(]*(open(er)?|file)\([^)]*\)',
195 (r'^[\s\(]*(open(er)?|file)\([^)]*\)',
194 "always assign an opened file to a variable, and close it afterwards"),
196 "always assign an opened file to a variable, and close it afterwards"),
195 (r'[\s\(](open|file)\([^)]*\)\.',
197 (r'[\s\(](open|file)\([^)]*\)\.',
196 "always assign an opened file to a variable, and close it afterwards"),
198 "always assign an opened file to a variable, and close it afterwards"),
197 (r'(?i)descendent', "the proper spelling is descendAnt"),
199 (r'(?i)descendent', "the proper spelling is descendAnt"),
198 (r'\.debug\(\_', "don't mark debug messages for translation"),
200 (r'\.debug\(\_', "don't mark debug messages for translation"),
199 ],
201 ],
200 # warnings
202 # warnings
201 [
203 [
202 (r'.{81}', "warning: line over 80 characters"),
204 (r'.{81}', "warning: line over 80 characters"),
203 (r'^\s*except:$', "warning: naked except clause"),
205 (r'^\s*except:$', "warning: naked except clause"),
204 (r'ui\.(status|progress|write|note|warn)\([\'\"]x',
206 (r'ui\.(status|progress|write|note|warn)\([\'\"]x',
205 "warning: unwrapped ui message"),
207 "warning: unwrapped ui message"),
206 ]
208 ]
207 ]
209 ]
208
210
209 pyfilters = [
211 pyfilters = [
210 (r"""(?msx)(?P<comment>\#.*?$)|
212 (r"""(?msx)(?P<comment>\#.*?$)|
211 ((?P<quote>('''|\"\"\"|(?<!')'(?!')|(?<!")"(?!")))
213 ((?P<quote>('''|\"\"\"|(?<!')'(?!')|(?<!")"(?!")))
212 (?P<text>(([^\\]|\\.)*?))
214 (?P<text>(([^\\]|\\.)*?))
213 (?P=quote))""", reppython),
215 (?P=quote))""", reppython),
214 ]
216 ]
215
217
216 cpats = [
218 cpats = [
217 [
219 [
218 (r'//', "don't use //-style comments"),
220 (r'//', "don't use //-style comments"),
219 (r'^ ', "don't use spaces to indent"),
221 (r'^ ', "don't use spaces to indent"),
220 (r'\S\t', "don't use tabs except for indent"),
222 (r'\S\t', "don't use tabs except for indent"),
221 (r'(\S[ \t]+|^[ \t]+)\n', "trailing whitespace"),
223 (r'(\S[ \t]+|^[ \t]+)\n', "trailing whitespace"),
222 (r'.{85}', "line too long"),
224 (r'.{85}', "line too long"),
223 (r'(while|if|do|for)\(', "use space after while/if/do/for"),
225 (r'(while|if|do|for)\(', "use space after while/if/do/for"),
224 (r'return\(', "return is not a function"),
226 (r'return\(', "return is not a function"),
225 (r' ;', "no space before ;"),
227 (r' ;', "no space before ;"),
226 (r'\w+\* \w+', "use int *foo, not int* foo"),
228 (r'\w+\* \w+', "use int *foo, not int* foo"),
227 (r'\([^\)]+\) \w+', "use (int)foo, not (int) foo"),
229 (r'\([^\)]+\) \w+', "use (int)foo, not (int) foo"),
228 (r'\S+ (\+\+|--)', "use foo++, not foo ++"),
230 (r'\S+ (\+\+|--)', "use foo++, not foo ++"),
229 (r'\w,\w', "missing whitespace after ,"),
231 (r'\w,\w', "missing whitespace after ,"),
230 (r'^[^#]\w[+/*]\w', "missing whitespace in expression"),
232 (r'^[^#]\w[+/*]\w', "missing whitespace in expression"),
231 (r'^#\s+\w', "use #foo, not # foo"),
233 (r'^#\s+\w', "use #foo, not # foo"),
232 (r'[^\n]\Z', "no trailing newline"),
234 (r'[^\n]\Z', "no trailing newline"),
233 (r'^\s*#import\b', "use only #include in standard C code"),
235 (r'^\s*#import\b', "use only #include in standard C code"),
234 ],
236 ],
235 # warnings
237 # warnings
236 []
238 []
237 ]
239 ]
238
240
239 cfilters = [
241 cfilters = [
240 (r'(/\*)(((\*(?!/))|[^*])*)\*/', repccomment),
242 (r'(/\*)(((\*(?!/))|[^*])*)\*/', repccomment),
241 (r'''(?P<quote>(?<!")")(?P<text>([^"]|\\")+)"(?!")''', repquote),
243 (r'''(?P<quote>(?<!")")(?P<text>([^"]|\\")+)"(?!")''', repquote),
242 (r'''(#\s*include\s+<)([^>]+)>''', repinclude),
244 (r'''(#\s*include\s+<)([^>]+)>''', repinclude),
243 (r'(\()([^)]+\))', repcallspaces),
245 (r'(\()([^)]+\))', repcallspaces),
244 ]
246 ]
245
247
246 inutilpats = [
248 inutilpats = [
247 [
249 [
248 (r'\bui\.', "don't use ui in util"),
250 (r'\bui\.', "don't use ui in util"),
249 ],
251 ],
250 # warnings
252 # warnings
251 []
253 []
252 ]
254 ]
253
255
254 inrevlogpats = [
256 inrevlogpats = [
255 [
257 [
256 (r'\brepo\.', "don't use repo in revlog"),
258 (r'\brepo\.', "don't use repo in revlog"),
257 ],
259 ],
258 # warnings
260 # warnings
259 []
261 []
260 ]
262 ]
261
263
262 checks = [
264 checks = [
263 ('python', r'.*\.(py|cgi)$', pyfilters, pypats),
265 ('python', r'.*\.(py|cgi)$', pyfilters, pypats),
264 ('test script', r'(.*/)?test-[^.~]*$', testfilters, testpats),
266 ('test script', r'(.*/)?test-[^.~]*$', testfilters, testpats),
265 ('c', r'.*\.c$', cfilters, cpats),
267 ('c', r'.*\.c$', cfilters, cpats),
266 ('unified test', r'.*\.t$', utestfilters, utestpats),
268 ('unified test', r'.*\.t$', utestfilters, utestpats),
267 ('layering violation repo in revlog', r'mercurial/revlog\.py', pyfilters,
269 ('layering violation repo in revlog', r'mercurial/revlog\.py', pyfilters,
268 inrevlogpats),
270 inrevlogpats),
269 ('layering violation ui in util', r'mercurial/util\.py', pyfilters,
271 ('layering violation ui in util', r'mercurial/util\.py', pyfilters,
270 inutilpats),
272 inutilpats),
271 ]
273 ]
272
274
273 class norepeatlogger(object):
275 class norepeatlogger(object):
274 def __init__(self):
276 def __init__(self):
275 self._lastseen = None
277 self._lastseen = None
276
278
277 def log(self, fname, lineno, line, msg, blame):
279 def log(self, fname, lineno, line, msg, blame):
278 """print error related a to given line of a given file.
280 """print error related a to given line of a given file.
279
281
280 The faulty line will also be printed but only once in the case
282 The faulty line will also be printed but only once in the case
281 of multiple errors.
283 of multiple errors.
282
284
283 :fname: filename
285 :fname: filename
284 :lineno: line number
286 :lineno: line number
285 :line: actual content of the line
287 :line: actual content of the line
286 :msg: error message
288 :msg: error message
287 """
289 """
288 msgid = fname, lineno, line
290 msgid = fname, lineno, line
289 if msgid != self._lastseen:
291 if msgid != self._lastseen:
290 if blame:
292 if blame:
291 print "%s:%d (%s):" % (fname, lineno, blame)
293 print "%s:%d (%s):" % (fname, lineno, blame)
292 else:
294 else:
293 print "%s:%d:" % (fname, lineno)
295 print "%s:%d:" % (fname, lineno)
294 print " > %s" % line
296 print " > %s" % line
295 self._lastseen = msgid
297 self._lastseen = msgid
296 print " " + msg
298 print " " + msg
297
299
298 _defaultlogger = norepeatlogger()
300 _defaultlogger = norepeatlogger()
299
301
300 def getblame(f):
302 def getblame(f):
301 lines = []
303 lines = []
302 for l in os.popen('hg annotate -un %s' % f):
304 for l in os.popen('hg annotate -un %s' % f):
303 start, line = l.split(':', 1)
305 start, line = l.split(':', 1)
304 user, rev = start.split()
306 user, rev = start.split()
305 lines.append((line[1:-1], user, rev))
307 lines.append((line[1:-1], user, rev))
306 return lines
308 return lines
307
309
308 def checkfile(f, logfunc=_defaultlogger.log, maxerr=None, warnings=False,
310 def checkfile(f, logfunc=_defaultlogger.log, maxerr=None, warnings=False,
309 blame=False, debug=False, lineno=True):
311 blame=False, debug=False, lineno=True):
310 """checks style and portability of a given file
312 """checks style and portability of a given file
311
313
312 :f: filepath
314 :f: filepath
313 :logfunc: function used to report error
315 :logfunc: function used to report error
314 logfunc(filename, linenumber, linecontent, errormessage)
316 logfunc(filename, linenumber, linecontent, errormessage)
315 :maxerr: number of error to display before arborting.
317 :maxerr: number of error to display before arborting.
316 Set to false (default) to report all errors
318 Set to false (default) to report all errors
317
319
318 return True if no error is found, False otherwise.
320 return True if no error is found, False otherwise.
319 """
321 """
320 blamecache = None
322 blamecache = None
321 result = True
323 result = True
322 for name, match, filters, pats in checks:
324 for name, match, filters, pats in checks:
323 if debug:
325 if debug:
324 print name, f
326 print name, f
325 fc = 0
327 fc = 0
326 if not re.match(match, f):
328 if not re.match(match, f):
327 if debug:
329 if debug:
328 print "Skipping %s for %s it doesn't match %s" % (
330 print "Skipping %s for %s it doesn't match %s" % (
329 name, match, f)
331 name, match, f)
330 continue
332 continue
331 fp = open(f)
333 fp = open(f)
332 pre = post = fp.read()
334 pre = post = fp.read()
333 fp.close()
335 fp.close()
334 if "no-" + "check-code" in pre:
336 if "no-" + "check-code" in pre:
335 if debug:
337 if debug:
336 print "Skipping %s for %s it has no- and check-code" % (
338 print "Skipping %s for %s it has no- and check-code" % (
337 name, f)
339 name, f)
338 break
340 break
339 for p, r in filters:
341 for p, r in filters:
340 post = re.sub(p, r, post)
342 post = re.sub(p, r, post)
341 if warnings:
343 if warnings:
342 pats = pats[0] + pats[1]
344 pats = pats[0] + pats[1]
343 else:
345 else:
344 pats = pats[0]
346 pats = pats[0]
345 # print post # uncomment to show filtered version
347 # print post # uncomment to show filtered version
346
348
347 if debug:
349 if debug:
348 print "Checking %s for %s" % (name, f)
350 print "Checking %s for %s" % (name, f)
349
351
350 prelines = None
352 prelines = None
351 errors = []
353 errors = []
352 for p, msg in pats:
354 for p, msg in pats:
353 # fix-up regexes for multiline searches
355 # fix-up regexes for multiline searches
354 po = p
356 po = p
355 # \s doesn't match \n
357 # \s doesn't match \n
356 p = re.sub(r'(?<!\\)\\s', r'[ \\t]', p)
358 p = re.sub(r'(?<!\\)\\s', r'[ \\t]', p)
357 # [^...] doesn't match newline
359 # [^...] doesn't match newline
358 p = re.sub(r'(?<!\\)\[\^', r'[^\\n', p)
360 p = re.sub(r'(?<!\\)\[\^', r'[^\\n', p)
359
361
360 #print po, '=>', p
362 #print po, '=>', p
361
363
362 pos = 0
364 pos = 0
363 n = 0
365 n = 0
364 for m in re.finditer(p, post, re.MULTILINE):
366 for m in re.finditer(p, post, re.MULTILINE):
365 if prelines is None:
367 if prelines is None:
366 prelines = pre.splitlines()
368 prelines = pre.splitlines()
367 postlines = post.splitlines(True)
369 postlines = post.splitlines(True)
368
370
369 start = m.start()
371 start = m.start()
370 while n < len(postlines):
372 while n < len(postlines):
371 step = len(postlines[n])
373 step = len(postlines[n])
372 if pos + step > start:
374 if pos + step > start:
373 break
375 break
374 pos += step
376 pos += step
375 n += 1
377 n += 1
376 l = prelines[n]
378 l = prelines[n]
377
379
378 if "check-code" + "-ignore" in l:
380 if "check-code" + "-ignore" in l:
379 if debug:
381 if debug:
380 print "Skipping %s for %s:%s (check-code -ignore)" % (
382 print "Skipping %s for %s:%s (check-code -ignore)" % (
381 name, f, n)
383 name, f, n)
382 continue
384 continue
383 bd = ""
385 bd = ""
384 if blame:
386 if blame:
385 bd = 'working directory'
387 bd = 'working directory'
386 if not blamecache:
388 if not blamecache:
387 blamecache = getblame(f)
389 blamecache = getblame(f)
388 if n < len(blamecache):
390 if n < len(blamecache):
389 bl, bu, br = blamecache[n]
391 bl, bu, br = blamecache[n]
390 if bl == l:
392 if bl == l:
391 bd = '%s@%s' % (bu, br)
393 bd = '%s@%s' % (bu, br)
392 errors.append((f, lineno and n + 1, l, msg, bd))
394 errors.append((f, lineno and n + 1, l, msg, bd))
393 result = False
395 result = False
394
396
395 errors.sort()
397 errors.sort()
396 for e in errors:
398 for e in errors:
397 logfunc(*e)
399 logfunc(*e)
398 fc += 1
400 fc += 1
399 if maxerr and fc >= maxerr:
401 if maxerr and fc >= maxerr:
400 print " (too many errors, giving up)"
402 print " (too many errors, giving up)"
401 break
403 break
402
404
403 return result
405 return result
404
406
405 if __name__ == "__main__":
407 if __name__ == "__main__":
406 parser = optparse.OptionParser("%prog [options] [files]")
408 parser = optparse.OptionParser("%prog [options] [files]")
407 parser.add_option("-w", "--warnings", action="store_true",
409 parser.add_option("-w", "--warnings", action="store_true",
408 help="include warning-level checks")
410 help="include warning-level checks")
409 parser.add_option("-p", "--per-file", type="int",
411 parser.add_option("-p", "--per-file", type="int",
410 help="max warnings per file")
412 help="max warnings per file")
411 parser.add_option("-b", "--blame", action="store_true",
413 parser.add_option("-b", "--blame", action="store_true",
412 help="use annotate to generate blame info")
414 help="use annotate to generate blame info")
413 parser.add_option("", "--debug", action="store_true",
415 parser.add_option("", "--debug", action="store_true",
414 help="show debug information")
416 help="show debug information")
415 parser.add_option("", "--nolineno", action="store_false",
417 parser.add_option("", "--nolineno", action="store_false",
416 dest='lineno', help="don't show line numbers")
418 dest='lineno', help="don't show line numbers")
417
419
418 parser.set_defaults(per_file=15, warnings=False, blame=False, debug=False,
420 parser.set_defaults(per_file=15, warnings=False, blame=False, debug=False,
419 lineno=True)
421 lineno=True)
420 (options, args) = parser.parse_args()
422 (options, args) = parser.parse_args()
421
423
422 if len(args) == 0:
424 if len(args) == 0:
423 check = glob.glob("*")
425 check = glob.glob("*")
424 else:
426 else:
425 check = args
427 check = args
426
428
427 ret = 0
429 ret = 0
428 for f in check:
430 for f in check:
429 if not checkfile(f, maxerr=options.per_file, warnings=options.warnings,
431 if not checkfile(f, maxerr=options.per_file, warnings=options.warnings,
430 blame=options.blame, debug=options.debug,
432 blame=options.blame, debug=options.debug,
431 lineno=options.lineno):
433 lineno=options.lineno):
432 ret = 1
434 ret = 1
433 sys.exit(ret)
435 sys.exit(ret)
@@ -1,5647 +1,5647 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@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 from node import hex, bin, nullid, nullrev, short
8 from node import hex, bin, nullid, nullrev, short
9 from lock import release
9 from lock import release
10 from i18n import _, gettext
10 from i18n import _, gettext
11 import os, re, difflib, time, tempfile, errno
11 import os, re, difflib, time, tempfile, errno
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
13 import patch, help, url, encoding, templatekw, discovery
13 import patch, help, url, encoding, templatekw, discovery
14 import archival, changegroup, cmdutil, hbisect
14 import archival, changegroup, cmdutil, hbisect
15 import sshserver, hgweb, hgweb.server, commandserver
15 import sshserver, hgweb, hgweb.server, commandserver
16 import merge as mergemod
16 import merge as mergemod
17 import minirst, revset, fileset
17 import minirst, revset, fileset
18 import dagparser, context, simplemerge
18 import dagparser, context, simplemerge
19 import random, setdiscovery, treediscovery, dagutil, pvec
19 import random, setdiscovery, treediscovery, dagutil, pvec
20 import phases
20 import phases
21
21
22 table = {}
22 table = {}
23
23
24 command = cmdutil.command(table)
24 command = cmdutil.command(table)
25
25
26 # common command options
26 # common command options
27
27
28 globalopts = [
28 globalopts = [
29 ('R', 'repository', '',
29 ('R', 'repository', '',
30 _('repository root directory or name of overlay bundle file'),
30 _('repository root directory or name of overlay bundle file'),
31 _('REPO')),
31 _('REPO')),
32 ('', 'cwd', '',
32 ('', 'cwd', '',
33 _('change working directory'), _('DIR')),
33 _('change working directory'), _('DIR')),
34 ('y', 'noninteractive', None,
34 ('y', 'noninteractive', None,
35 _('do not prompt, automatically pick the first choice for all prompts')),
35 _('do not prompt, automatically pick the first choice for all prompts')),
36 ('q', 'quiet', None, _('suppress output')),
36 ('q', 'quiet', None, _('suppress output')),
37 ('v', 'verbose', None, _('enable additional output')),
37 ('v', 'verbose', None, _('enable additional output')),
38 ('', 'config', [],
38 ('', 'config', [],
39 _('set/override config option (use \'section.name=value\')'),
39 _('set/override config option (use \'section.name=value\')'),
40 _('CONFIG')),
40 _('CONFIG')),
41 ('', 'debug', None, _('enable debugging output')),
41 ('', 'debug', None, _('enable debugging output')),
42 ('', 'debugger', None, _('start debugger')),
42 ('', 'debugger', None, _('start debugger')),
43 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
43 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
44 _('ENCODE')),
44 _('ENCODE')),
45 ('', 'encodingmode', encoding.encodingmode,
45 ('', 'encodingmode', encoding.encodingmode,
46 _('set the charset encoding mode'), _('MODE')),
46 _('set the charset encoding mode'), _('MODE')),
47 ('', 'traceback', None, _('always print a traceback on exception')),
47 ('', 'traceback', None, _('always print a traceback on exception')),
48 ('', 'time', None, _('time how long the command takes')),
48 ('', 'time', None, _('time how long the command takes')),
49 ('', 'profile', None, _('print command execution profile')),
49 ('', 'profile', None, _('print command execution profile')),
50 ('', 'version', None, _('output version information and exit')),
50 ('', 'version', None, _('output version information and exit')),
51 ('h', 'help', None, _('display help and exit')),
51 ('h', 'help', None, _('display help and exit')),
52 ]
52 ]
53
53
54 dryrunopts = [('n', 'dry-run', None,
54 dryrunopts = [('n', 'dry-run', None,
55 _('do not perform actions, just print output'))]
55 _('do not perform actions, just print output'))]
56
56
57 remoteopts = [
57 remoteopts = [
58 ('e', 'ssh', '',
58 ('e', 'ssh', '',
59 _('specify ssh command to use'), _('CMD')),
59 _('specify ssh command to use'), _('CMD')),
60 ('', 'remotecmd', '',
60 ('', 'remotecmd', '',
61 _('specify hg command to run on the remote side'), _('CMD')),
61 _('specify hg command to run on the remote side'), _('CMD')),
62 ('', 'insecure', None,
62 ('', 'insecure', None,
63 _('do not verify server certificate (ignoring web.cacerts config)')),
63 _('do not verify server certificate (ignoring web.cacerts config)')),
64 ]
64 ]
65
65
66 walkopts = [
66 walkopts = [
67 ('I', 'include', [],
67 ('I', 'include', [],
68 _('include names matching the given patterns'), _('PATTERN')),
68 _('include names matching the given patterns'), _('PATTERN')),
69 ('X', 'exclude', [],
69 ('X', 'exclude', [],
70 _('exclude names matching the given patterns'), _('PATTERN')),
70 _('exclude names matching the given patterns'), _('PATTERN')),
71 ]
71 ]
72
72
73 commitopts = [
73 commitopts = [
74 ('m', 'message', '',
74 ('m', 'message', '',
75 _('use text as commit message'), _('TEXT')),
75 _('use text as commit message'), _('TEXT')),
76 ('l', 'logfile', '',
76 ('l', 'logfile', '',
77 _('read commit message from file'), _('FILE')),
77 _('read commit message from file'), _('FILE')),
78 ]
78 ]
79
79
80 commitopts2 = [
80 commitopts2 = [
81 ('d', 'date', '',
81 ('d', 'date', '',
82 _('record the specified date as commit date'), _('DATE')),
82 _('record the specified date as commit date'), _('DATE')),
83 ('u', 'user', '',
83 ('u', 'user', '',
84 _('record the specified user as committer'), _('USER')),
84 _('record the specified user as committer'), _('USER')),
85 ]
85 ]
86
86
87 templateopts = [
87 templateopts = [
88 ('', 'style', '',
88 ('', 'style', '',
89 _('display using template map file'), _('STYLE')),
89 _('display using template map file'), _('STYLE')),
90 ('', 'template', '',
90 ('', 'template', '',
91 _('display with template'), _('TEMPLATE')),
91 _('display with template'), _('TEMPLATE')),
92 ]
92 ]
93
93
94 logopts = [
94 logopts = [
95 ('p', 'patch', None, _('show patch')),
95 ('p', 'patch', None, _('show patch')),
96 ('g', 'git', None, _('use git extended diff format')),
96 ('g', 'git', None, _('use git extended diff format')),
97 ('l', 'limit', '',
97 ('l', 'limit', '',
98 _('limit number of changes displayed'), _('NUM')),
98 _('limit number of changes displayed'), _('NUM')),
99 ('M', 'no-merges', None, _('do not show merges')),
99 ('M', 'no-merges', None, _('do not show merges')),
100 ('', 'stat', None, _('output diffstat-style summary of changes')),
100 ('', 'stat', None, _('output diffstat-style summary of changes')),
101 ] + templateopts
101 ] + templateopts
102
102
103 diffopts = [
103 diffopts = [
104 ('a', 'text', None, _('treat all files as text')),
104 ('a', 'text', None, _('treat all files as text')),
105 ('g', 'git', None, _('use git extended diff format')),
105 ('g', 'git', None, _('use git extended diff format')),
106 ('', 'nodates', None, _('omit dates from diff headers'))
106 ('', 'nodates', None, _('omit dates from diff headers'))
107 ]
107 ]
108
108
109 diffwsopts = [
109 diffwsopts = [
110 ('w', 'ignore-all-space', None,
110 ('w', 'ignore-all-space', None,
111 _('ignore white space when comparing lines')),
111 _('ignore white space when comparing lines')),
112 ('b', 'ignore-space-change', None,
112 ('b', 'ignore-space-change', None,
113 _('ignore changes in the amount of white space')),
113 _('ignore changes in the amount of white space')),
114 ('B', 'ignore-blank-lines', None,
114 ('B', 'ignore-blank-lines', None,
115 _('ignore changes whose lines are all blank')),
115 _('ignore changes whose lines are all blank')),
116 ]
116 ]
117
117
118 diffopts2 = [
118 diffopts2 = [
119 ('p', 'show-function', None, _('show which function each change is in')),
119 ('p', 'show-function', None, _('show which function each change is in')),
120 ('', 'reverse', None, _('produce a diff that undoes the changes')),
120 ('', 'reverse', None, _('produce a diff that undoes the changes')),
121 ] + diffwsopts + [
121 ] + diffwsopts + [
122 ('U', 'unified', '',
122 ('U', 'unified', '',
123 _('number of lines of context to show'), _('NUM')),
123 _('number of lines of context to show'), _('NUM')),
124 ('', 'stat', None, _('output diffstat-style summary of changes')),
124 ('', 'stat', None, _('output diffstat-style summary of changes')),
125 ]
125 ]
126
126
127 mergetoolopts = [
127 mergetoolopts = [
128 ('t', 'tool', '', _('specify merge tool')),
128 ('t', 'tool', '', _('specify merge tool')),
129 ]
129 ]
130
130
131 similarityopts = [
131 similarityopts = [
132 ('s', 'similarity', '',
132 ('s', 'similarity', '',
133 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
133 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
134 ]
134 ]
135
135
136 subrepoopts = [
136 subrepoopts = [
137 ('S', 'subrepos', None,
137 ('S', 'subrepos', None,
138 _('recurse into subrepositories'))
138 _('recurse into subrepositories'))
139 ]
139 ]
140
140
141 # Commands start here, listed alphabetically
141 # Commands start here, listed alphabetically
142
142
143 @command('^add',
143 @command('^add',
144 walkopts + subrepoopts + dryrunopts,
144 walkopts + subrepoopts + dryrunopts,
145 _('[OPTION]... [FILE]...'))
145 _('[OPTION]... [FILE]...'))
146 def add(ui, repo, *pats, **opts):
146 def add(ui, repo, *pats, **opts):
147 """add the specified files on the next commit
147 """add the specified files on the next commit
148
148
149 Schedule files to be version controlled and added to the
149 Schedule files to be version controlled and added to the
150 repository.
150 repository.
151
151
152 The files will be added to the repository at the next commit. To
152 The files will be added to the repository at the next commit. To
153 undo an add before that, see :hg:`forget`.
153 undo an add before that, see :hg:`forget`.
154
154
155 If no names are given, add all files to the repository.
155 If no names are given, add all files to the repository.
156
156
157 .. container:: verbose
157 .. container:: verbose
158
158
159 An example showing how new (unknown) files are added
159 An example showing how new (unknown) files are added
160 automatically by :hg:`add`::
160 automatically by :hg:`add`::
161
161
162 $ ls
162 $ ls
163 foo.c
163 foo.c
164 $ hg status
164 $ hg status
165 ? foo.c
165 ? foo.c
166 $ hg add
166 $ hg add
167 adding foo.c
167 adding foo.c
168 $ hg status
168 $ hg status
169 A foo.c
169 A foo.c
170
170
171 Returns 0 if all files are successfully added.
171 Returns 0 if all files are successfully added.
172 """
172 """
173
173
174 m = scmutil.match(repo[None], pats, opts)
174 m = scmutil.match(repo[None], pats, opts)
175 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
175 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
176 opts.get('subrepos'), prefix="", explicitonly=False)
176 opts.get('subrepos'), prefix="", explicitonly=False)
177 return rejected and 1 or 0
177 return rejected and 1 or 0
178
178
179 @command('addremove',
179 @command('addremove',
180 similarityopts + walkopts + dryrunopts,
180 similarityopts + walkopts + dryrunopts,
181 _('[OPTION]... [FILE]...'))
181 _('[OPTION]... [FILE]...'))
182 def addremove(ui, repo, *pats, **opts):
182 def addremove(ui, repo, *pats, **opts):
183 """add all new files, delete all missing files
183 """add all new files, delete all missing files
184
184
185 Add all new files and remove all missing files from the
185 Add all new files and remove all missing files from the
186 repository.
186 repository.
187
187
188 New files are ignored if they match any of the patterns in
188 New files are ignored if they match any of the patterns in
189 ``.hgignore``. As with add, these changes take effect at the next
189 ``.hgignore``. As with add, these changes take effect at the next
190 commit.
190 commit.
191
191
192 Use the -s/--similarity option to detect renamed files. With a
192 Use the -s/--similarity option to detect renamed files. With a
193 parameter greater than 0, this compares every removed file with
193 parameter greater than 0, this compares every removed file with
194 every added file and records those similar enough as renames. This
194 every added file and records those similar enough as renames. This
195 option takes a percentage between 0 (disabled) and 100 (files must
195 option takes a percentage between 0 (disabled) and 100 (files must
196 be identical) as its parameter. Detecting renamed files this way
196 be identical) as its parameter. Detecting renamed files this way
197 can be expensive. After using this option, :hg:`status -C` can be
197 can be expensive. After using this option, :hg:`status -C` can be
198 used to check which files were identified as moved or renamed.
198 used to check which files were identified as moved or renamed.
199
199
200 Returns 0 if all files are successfully added.
200 Returns 0 if all files are successfully added.
201 """
201 """
202 try:
202 try:
203 sim = float(opts.get('similarity') or 100)
203 sim = float(opts.get('similarity') or 100)
204 except ValueError:
204 except ValueError:
205 raise util.Abort(_('similarity must be a number'))
205 raise util.Abort(_('similarity must be a number'))
206 if sim < 0 or sim > 100:
206 if sim < 0 or sim > 100:
207 raise util.Abort(_('similarity must be between 0 and 100'))
207 raise util.Abort(_('similarity must be between 0 and 100'))
208 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
208 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
209
209
210 @command('^annotate|blame',
210 @command('^annotate|blame',
211 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
211 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
212 ('', 'follow', None,
212 ('', 'follow', None,
213 _('follow copies/renames and list the filename (DEPRECATED)')),
213 _('follow copies/renames and list the filename (DEPRECATED)')),
214 ('', 'no-follow', None, _("don't follow copies and renames")),
214 ('', 'no-follow', None, _("don't follow copies and renames")),
215 ('a', 'text', None, _('treat all files as text')),
215 ('a', 'text', None, _('treat all files as text')),
216 ('u', 'user', None, _('list the author (long with -v)')),
216 ('u', 'user', None, _('list the author (long with -v)')),
217 ('f', 'file', None, _('list the filename')),
217 ('f', 'file', None, _('list the filename')),
218 ('d', 'date', None, _('list the date (short with -q)')),
218 ('d', 'date', None, _('list the date (short with -q)')),
219 ('n', 'number', None, _('list the revision number (default)')),
219 ('n', 'number', None, _('list the revision number (default)')),
220 ('c', 'changeset', None, _('list the changeset')),
220 ('c', 'changeset', None, _('list the changeset')),
221 ('l', 'line-number', None, _('show line number at the first appearance'))
221 ('l', 'line-number', None, _('show line number at the first appearance'))
222 ] + diffwsopts + walkopts,
222 ] + diffwsopts + walkopts,
223 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
223 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
224 def annotate(ui, repo, *pats, **opts):
224 def annotate(ui, repo, *pats, **opts):
225 """show changeset information by line for each file
225 """show changeset information by line for each file
226
226
227 List changes in files, showing the revision id responsible for
227 List changes in files, showing the revision id responsible for
228 each line
228 each line
229
229
230 This command is useful for discovering when a change was made and
230 This command is useful for discovering when a change was made and
231 by whom.
231 by whom.
232
232
233 Without the -a/--text option, annotate will avoid processing files
233 Without the -a/--text option, annotate will avoid processing files
234 it detects as binary. With -a, annotate will annotate the file
234 it detects as binary. With -a, annotate will annotate the file
235 anyway, although the results will probably be neither useful
235 anyway, although the results will probably be neither useful
236 nor desirable.
236 nor desirable.
237
237
238 Returns 0 on success.
238 Returns 0 on success.
239 """
239 """
240 if opts.get('follow'):
240 if opts.get('follow'):
241 # --follow is deprecated and now just an alias for -f/--file
241 # --follow is deprecated and now just an alias for -f/--file
242 # to mimic the behavior of Mercurial before version 1.5
242 # to mimic the behavior of Mercurial before version 1.5
243 opts['file'] = True
243 opts['file'] = True
244
244
245 datefunc = ui.quiet and util.shortdate or util.datestr
245 datefunc = ui.quiet and util.shortdate or util.datestr
246 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
246 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
247
247
248 if not pats:
248 if not pats:
249 raise util.Abort(_('at least one filename or pattern is required'))
249 raise util.Abort(_('at least one filename or pattern is required'))
250
250
251 hexfn = ui.debugflag and hex or short
251 hexfn = ui.debugflag and hex or short
252
252
253 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
253 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
254 ('number', ' ', lambda x: str(x[0].rev())),
254 ('number', ' ', lambda x: str(x[0].rev())),
255 ('changeset', ' ', lambda x: hexfn(x[0].node())),
255 ('changeset', ' ', lambda x: hexfn(x[0].node())),
256 ('date', ' ', getdate),
256 ('date', ' ', getdate),
257 ('file', ' ', lambda x: x[0].path()),
257 ('file', ' ', lambda x: x[0].path()),
258 ('line_number', ':', lambda x: str(x[1])),
258 ('line_number', ':', lambda x: str(x[1])),
259 ]
259 ]
260
260
261 if (not opts.get('user') and not opts.get('changeset')
261 if (not opts.get('user') and not opts.get('changeset')
262 and not opts.get('date') and not opts.get('file')):
262 and not opts.get('date') and not opts.get('file')):
263 opts['number'] = True
263 opts['number'] = True
264
264
265 linenumber = opts.get('line_number') is not None
265 linenumber = opts.get('line_number') is not None
266 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
266 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
267 raise util.Abort(_('at least one of -n/-c is required for -l'))
267 raise util.Abort(_('at least one of -n/-c is required for -l'))
268
268
269 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
269 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
270 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
270 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
271
271
272 def bad(x, y):
272 def bad(x, y):
273 raise util.Abort("%s: %s" % (x, y))
273 raise util.Abort("%s: %s" % (x, y))
274
274
275 ctx = scmutil.revsingle(repo, opts.get('rev'))
275 ctx = scmutil.revsingle(repo, opts.get('rev'))
276 m = scmutil.match(ctx, pats, opts)
276 m = scmutil.match(ctx, pats, opts)
277 m.bad = bad
277 m.bad = bad
278 follow = not opts.get('no_follow')
278 follow = not opts.get('no_follow')
279 diffopts = patch.diffopts(ui, opts, section='annotate')
279 diffopts = patch.diffopts(ui, opts, section='annotate')
280 for abs in ctx.walk(m):
280 for abs in ctx.walk(m):
281 fctx = ctx[abs]
281 fctx = ctx[abs]
282 if not opts.get('text') and util.binary(fctx.data()):
282 if not opts.get('text') and util.binary(fctx.data()):
283 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
283 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
284 continue
284 continue
285
285
286 lines = fctx.annotate(follow=follow, linenumber=linenumber,
286 lines = fctx.annotate(follow=follow, linenumber=linenumber,
287 diffopts=diffopts)
287 diffopts=diffopts)
288 pieces = []
288 pieces = []
289
289
290 for f, sep in funcmap:
290 for f, sep in funcmap:
291 l = [f(n) for n, dummy in lines]
291 l = [f(n) for n, dummy in lines]
292 if l:
292 if l:
293 sized = [(x, encoding.colwidth(x)) for x in l]
293 sized = [(x, encoding.colwidth(x)) for x in l]
294 ml = max([w for x, w in sized])
294 ml = max([w for x, w in sized])
295 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
295 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
296 for x, w in sized])
296 for x, w in sized])
297
297
298 if pieces:
298 if pieces:
299 for p, l in zip(zip(*pieces), lines):
299 for p, l in zip(zip(*pieces), lines):
300 ui.write("%s: %s" % ("".join(p), l[1]))
300 ui.write("%s: %s" % ("".join(p), l[1]))
301
301
302 if lines and not lines[-1][1].endswith('\n'):
302 if lines and not lines[-1][1].endswith('\n'):
303 ui.write('\n')
303 ui.write('\n')
304
304
305 @command('archive',
305 @command('archive',
306 [('', 'no-decode', None, _('do not pass files through decoders')),
306 [('', 'no-decode', None, _('do not pass files through decoders')),
307 ('p', 'prefix', '', _('directory prefix for files in archive'),
307 ('p', 'prefix', '', _('directory prefix for files in archive'),
308 _('PREFIX')),
308 _('PREFIX')),
309 ('r', 'rev', '', _('revision to distribute'), _('REV')),
309 ('r', 'rev', '', _('revision to distribute'), _('REV')),
310 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
310 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
311 ] + subrepoopts + walkopts,
311 ] + subrepoopts + walkopts,
312 _('[OPTION]... DEST'))
312 _('[OPTION]... DEST'))
313 def archive(ui, repo, dest, **opts):
313 def archive(ui, repo, dest, **opts):
314 '''create an unversioned archive of a repository revision
314 '''create an unversioned archive of a repository revision
315
315
316 By default, the revision used is the parent of the working
316 By default, the revision used is the parent of the working
317 directory; use -r/--rev to specify a different revision.
317 directory; use -r/--rev to specify a different revision.
318
318
319 The archive type is automatically detected based on file
319 The archive type is automatically detected based on file
320 extension (or override using -t/--type).
320 extension (or override using -t/--type).
321
321
322 .. container:: verbose
322 .. container:: verbose
323
323
324 Examples:
324 Examples:
325
325
326 - create a zip file containing the 1.0 release::
326 - create a zip file containing the 1.0 release::
327
327
328 hg archive -r 1.0 project-1.0.zip
328 hg archive -r 1.0 project-1.0.zip
329
329
330 - create a tarball excluding .hg files::
330 - create a tarball excluding .hg files::
331
331
332 hg archive project.tar.gz -X ".hg*"
332 hg archive project.tar.gz -X ".hg*"
333
333
334 Valid types are:
334 Valid types are:
335
335
336 :``files``: a directory full of files (default)
336 :``files``: a directory full of files (default)
337 :``tar``: tar archive, uncompressed
337 :``tar``: tar archive, uncompressed
338 :``tbz2``: tar archive, compressed using bzip2
338 :``tbz2``: tar archive, compressed using bzip2
339 :``tgz``: tar archive, compressed using gzip
339 :``tgz``: tar archive, compressed using gzip
340 :``uzip``: zip archive, uncompressed
340 :``uzip``: zip archive, uncompressed
341 :``zip``: zip archive, compressed using deflate
341 :``zip``: zip archive, compressed using deflate
342
342
343 The exact name of the destination archive or directory is given
343 The exact name of the destination archive or directory is given
344 using a format string; see :hg:`help export` for details.
344 using a format string; see :hg:`help export` for details.
345
345
346 Each member added to an archive file has a directory prefix
346 Each member added to an archive file has a directory prefix
347 prepended. Use -p/--prefix to specify a format string for the
347 prepended. Use -p/--prefix to specify a format string for the
348 prefix. The default is the basename of the archive, with suffixes
348 prefix. The default is the basename of the archive, with suffixes
349 removed.
349 removed.
350
350
351 Returns 0 on success.
351 Returns 0 on success.
352 '''
352 '''
353
353
354 ctx = scmutil.revsingle(repo, opts.get('rev'))
354 ctx = scmutil.revsingle(repo, opts.get('rev'))
355 if not ctx:
355 if not ctx:
356 raise util.Abort(_('no working directory: please specify a revision'))
356 raise util.Abort(_('no working directory: please specify a revision'))
357 node = ctx.node()
357 node = ctx.node()
358 dest = cmdutil.makefilename(repo, dest, node)
358 dest = cmdutil.makefilename(repo, dest, node)
359 if os.path.realpath(dest) == repo.root:
359 if os.path.realpath(dest) == repo.root:
360 raise util.Abort(_('repository root cannot be destination'))
360 raise util.Abort(_('repository root cannot be destination'))
361
361
362 kind = opts.get('type') or archival.guesskind(dest) or 'files'
362 kind = opts.get('type') or archival.guesskind(dest) or 'files'
363 prefix = opts.get('prefix')
363 prefix = opts.get('prefix')
364
364
365 if dest == '-':
365 if dest == '-':
366 if kind == 'files':
366 if kind == 'files':
367 raise util.Abort(_('cannot archive plain files to stdout'))
367 raise util.Abort(_('cannot archive plain files to stdout'))
368 dest = cmdutil.makefileobj(repo, dest)
368 dest = cmdutil.makefileobj(repo, dest)
369 if not prefix:
369 if not prefix:
370 prefix = os.path.basename(repo.root) + '-%h'
370 prefix = os.path.basename(repo.root) + '-%h'
371
371
372 prefix = cmdutil.makefilename(repo, prefix, node)
372 prefix = cmdutil.makefilename(repo, prefix, node)
373 matchfn = scmutil.match(ctx, [], opts)
373 matchfn = scmutil.match(ctx, [], opts)
374 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
374 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
375 matchfn, prefix, subrepos=opts.get('subrepos'))
375 matchfn, prefix, subrepos=opts.get('subrepos'))
376
376
377 @command('backout',
377 @command('backout',
378 [('', 'merge', None, _('merge with old dirstate parent after backout')),
378 [('', 'merge', None, _('merge with old dirstate parent after backout')),
379 ('', 'parent', '',
379 ('', 'parent', '',
380 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
380 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
381 ('r', 'rev', '', _('revision to backout'), _('REV')),
381 ('r', 'rev', '', _('revision to backout'), _('REV')),
382 ] + mergetoolopts + walkopts + commitopts + commitopts2,
382 ] + mergetoolopts + walkopts + commitopts + commitopts2,
383 _('[OPTION]... [-r] REV'))
383 _('[OPTION]... [-r] REV'))
384 def backout(ui, repo, node=None, rev=None, **opts):
384 def backout(ui, repo, node=None, rev=None, **opts):
385 '''reverse effect of earlier changeset
385 '''reverse effect of earlier changeset
386
386
387 Prepare a new changeset with the effect of REV undone in the
387 Prepare a new changeset with the effect of REV undone in the
388 current working directory.
388 current working directory.
389
389
390 If REV is the parent of the working directory, then this new changeset
390 If REV is the parent of the working directory, then this new changeset
391 is committed automatically. Otherwise, hg needs to merge the
391 is committed automatically. Otherwise, hg needs to merge the
392 changes and the merged result is left uncommitted.
392 changes and the merged result is left uncommitted.
393
393
394 .. note::
394 .. note::
395 backout cannot be used to fix either an unwanted or
395 backout cannot be used to fix either an unwanted or
396 incorrect merge.
396 incorrect merge.
397
397
398 .. container:: verbose
398 .. container:: verbose
399
399
400 By default, the pending changeset will have one parent,
400 By default, the pending changeset will have one parent,
401 maintaining a linear history. With --merge, the pending
401 maintaining a linear history. With --merge, the pending
402 changeset will instead have two parents: the old parent of the
402 changeset will instead have two parents: the old parent of the
403 working directory and a new child of REV that simply undoes REV.
403 working directory and a new child of REV that simply undoes REV.
404
404
405 Before version 1.7, the behavior without --merge was equivalent
405 Before version 1.7, the behavior without --merge was equivalent
406 to specifying --merge followed by :hg:`update --clean .` to
406 to specifying --merge followed by :hg:`update --clean .` to
407 cancel the merge and leave the child of REV as a head to be
407 cancel the merge and leave the child of REV as a head to be
408 merged separately.
408 merged separately.
409
409
410 See :hg:`help dates` for a list of formats valid for -d/--date.
410 See :hg:`help dates` for a list of formats valid for -d/--date.
411
411
412 Returns 0 on success.
412 Returns 0 on success.
413 '''
413 '''
414 if rev and node:
414 if rev and node:
415 raise util.Abort(_("please specify just one revision"))
415 raise util.Abort(_("please specify just one revision"))
416
416
417 if not rev:
417 if not rev:
418 rev = node
418 rev = node
419
419
420 if not rev:
420 if not rev:
421 raise util.Abort(_("please specify a revision to backout"))
421 raise util.Abort(_("please specify a revision to backout"))
422
422
423 date = opts.get('date')
423 date = opts.get('date')
424 if date:
424 if date:
425 opts['date'] = util.parsedate(date)
425 opts['date'] = util.parsedate(date)
426
426
427 cmdutil.bailifchanged(repo)
427 cmdutil.bailifchanged(repo)
428 node = scmutil.revsingle(repo, rev).node()
428 node = scmutil.revsingle(repo, rev).node()
429
429
430 op1, op2 = repo.dirstate.parents()
430 op1, op2 = repo.dirstate.parents()
431 a = repo.changelog.ancestor(op1, node)
431 a = repo.changelog.ancestor(op1, node)
432 if a != node:
432 if a != node:
433 raise util.Abort(_('cannot backout change on a different branch'))
433 raise util.Abort(_('cannot backout change on a different branch'))
434
434
435 p1, p2 = repo.changelog.parents(node)
435 p1, p2 = repo.changelog.parents(node)
436 if p1 == nullid:
436 if p1 == nullid:
437 raise util.Abort(_('cannot backout a change with no parents'))
437 raise util.Abort(_('cannot backout a change with no parents'))
438 if p2 != nullid:
438 if p2 != nullid:
439 if not opts.get('parent'):
439 if not opts.get('parent'):
440 raise util.Abort(_('cannot backout a merge changeset'))
440 raise util.Abort(_('cannot backout a merge changeset'))
441 p = repo.lookup(opts['parent'])
441 p = repo.lookup(opts['parent'])
442 if p not in (p1, p2):
442 if p not in (p1, p2):
443 raise util.Abort(_('%s is not a parent of %s') %
443 raise util.Abort(_('%s is not a parent of %s') %
444 (short(p), short(node)))
444 (short(p), short(node)))
445 parent = p
445 parent = p
446 else:
446 else:
447 if opts.get('parent'):
447 if opts.get('parent'):
448 raise util.Abort(_('cannot use --parent on non-merge changeset'))
448 raise util.Abort(_('cannot use --parent on non-merge changeset'))
449 parent = p1
449 parent = p1
450
450
451 # the backout should appear on the same branch
451 # the backout should appear on the same branch
452 branch = repo.dirstate.branch()
452 branch = repo.dirstate.branch()
453 hg.clean(repo, node, show_stats=False)
453 hg.clean(repo, node, show_stats=False)
454 repo.dirstate.setbranch(branch)
454 repo.dirstate.setbranch(branch)
455 revert_opts = opts.copy()
455 revert_opts = opts.copy()
456 revert_opts['date'] = None
456 revert_opts['date'] = None
457 revert_opts['all'] = True
457 revert_opts['all'] = True
458 revert_opts['rev'] = hex(parent)
458 revert_opts['rev'] = hex(parent)
459 revert_opts['no_backup'] = None
459 revert_opts['no_backup'] = None
460 revert(ui, repo, **revert_opts)
460 revert(ui, repo, **revert_opts)
461 if not opts.get('merge') and op1 != node:
461 if not opts.get('merge') and op1 != node:
462 try:
462 try:
463 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
463 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
464 return hg.update(repo, op1)
464 return hg.update(repo, op1)
465 finally:
465 finally:
466 ui.setconfig('ui', 'forcemerge', '')
466 ui.setconfig('ui', 'forcemerge', '')
467
467
468 commit_opts = opts.copy()
468 commit_opts = opts.copy()
469 commit_opts['addremove'] = False
469 commit_opts['addremove'] = False
470 if not commit_opts['message'] and not commit_opts['logfile']:
470 if not commit_opts['message'] and not commit_opts['logfile']:
471 # we don't translate commit messages
471 # we don't translate commit messages
472 commit_opts['message'] = "Backed out changeset %s" % short(node)
472 commit_opts['message'] = "Backed out changeset %s" % short(node)
473 commit_opts['force_editor'] = True
473 commit_opts['force_editor'] = True
474 commit(ui, repo, **commit_opts)
474 commit(ui, repo, **commit_opts)
475 def nice(node):
475 def nice(node):
476 return '%d:%s' % (repo.changelog.rev(node), short(node))
476 return '%d:%s' % (repo.changelog.rev(node), short(node))
477 ui.status(_('changeset %s backs out changeset %s\n') %
477 ui.status(_('changeset %s backs out changeset %s\n') %
478 (nice(repo.changelog.tip()), nice(node)))
478 (nice(repo.changelog.tip()), nice(node)))
479 if opts.get('merge') and op1 != node:
479 if opts.get('merge') and op1 != node:
480 hg.clean(repo, op1, show_stats=False)
480 hg.clean(repo, op1, show_stats=False)
481 ui.status(_('merging with changeset %s\n')
481 ui.status(_('merging with changeset %s\n')
482 % nice(repo.changelog.tip()))
482 % nice(repo.changelog.tip()))
483 try:
483 try:
484 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
484 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
485 return hg.merge(repo, hex(repo.changelog.tip()))
485 return hg.merge(repo, hex(repo.changelog.tip()))
486 finally:
486 finally:
487 ui.setconfig('ui', 'forcemerge', '')
487 ui.setconfig('ui', 'forcemerge', '')
488 return 0
488 return 0
489
489
490 @command('bisect',
490 @command('bisect',
491 [('r', 'reset', False, _('reset bisect state')),
491 [('r', 'reset', False, _('reset bisect state')),
492 ('g', 'good', False, _('mark changeset good')),
492 ('g', 'good', False, _('mark changeset good')),
493 ('b', 'bad', False, _('mark changeset bad')),
493 ('b', 'bad', False, _('mark changeset bad')),
494 ('s', 'skip', False, _('skip testing changeset')),
494 ('s', 'skip', False, _('skip testing changeset')),
495 ('e', 'extend', False, _('extend the bisect range')),
495 ('e', 'extend', False, _('extend the bisect range')),
496 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
496 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
497 ('U', 'noupdate', False, _('do not update to target'))],
497 ('U', 'noupdate', False, _('do not update to target'))],
498 _("[-gbsr] [-U] [-c CMD] [REV]"))
498 _("[-gbsr] [-U] [-c CMD] [REV]"))
499 def bisect(ui, repo, rev=None, extra=None, command=None,
499 def bisect(ui, repo, rev=None, extra=None, command=None,
500 reset=None, good=None, bad=None, skip=None, extend=None,
500 reset=None, good=None, bad=None, skip=None, extend=None,
501 noupdate=None):
501 noupdate=None):
502 """subdivision search of changesets
502 """subdivision search of changesets
503
503
504 This command helps to find changesets which introduce problems. To
504 This command helps to find changesets which introduce problems. To
505 use, mark the earliest changeset you know exhibits the problem as
505 use, mark the earliest changeset you know exhibits the problem as
506 bad, then mark the latest changeset which is free from the problem
506 bad, then mark the latest changeset which is free from the problem
507 as good. Bisect will update your working directory to a revision
507 as good. Bisect will update your working directory to a revision
508 for testing (unless the -U/--noupdate option is specified). Once
508 for testing (unless the -U/--noupdate option is specified). Once
509 you have performed tests, mark the working directory as good or
509 you have performed tests, mark the working directory as good or
510 bad, and bisect will either update to another candidate changeset
510 bad, and bisect will either update to another candidate changeset
511 or announce that it has found the bad revision.
511 or announce that it has found the bad revision.
512
512
513 As a shortcut, you can also use the revision argument to mark a
513 As a shortcut, you can also use the revision argument to mark a
514 revision as good or bad without checking it out first.
514 revision as good or bad without checking it out first.
515
515
516 If you supply a command, it will be used for automatic bisection.
516 If you supply a command, it will be used for automatic bisection.
517 Its exit status will be used to mark revisions as good or bad:
517 Its exit status will be used to mark revisions as good or bad:
518 status 0 means good, 125 means to skip the revision, 127
518 status 0 means good, 125 means to skip the revision, 127
519 (command not found) will abort the bisection, and any other
519 (command not found) will abort the bisection, and any other
520 non-zero exit status means the revision is bad.
520 non-zero exit status means the revision is bad.
521
521
522 .. container:: verbose
522 .. container:: verbose
523
523
524 Some examples:
524 Some examples:
525
525
526 - start a bisection with known bad revision 12, and good revision 34::
526 - start a bisection with known bad revision 12, and good revision 34::
527
527
528 hg bisect --bad 34
528 hg bisect --bad 34
529 hg bisect --good 12
529 hg bisect --good 12
530
530
531 - advance the current bisection by marking current revision as good or
531 - advance the current bisection by marking current revision as good or
532 bad::
532 bad::
533
533
534 hg bisect --good
534 hg bisect --good
535 hg bisect --bad
535 hg bisect --bad
536
536
537 - mark the current revision, or a known revision, to be skipped (eg. if
537 - mark the current revision, or a known revision, to be skipped (eg. if
538 that revision is not usable because of another issue)::
538 that revision is not usable because of another issue)::
539
539
540 hg bisect --skip
540 hg bisect --skip
541 hg bisect --skip 23
541 hg bisect --skip 23
542
542
543 - forget the current bisection::
543 - forget the current bisection::
544
544
545 hg bisect --reset
545 hg bisect --reset
546
546
547 - use 'make && make tests' to automatically find the first broken
547 - use 'make && make tests' to automatically find the first broken
548 revision::
548 revision::
549
549
550 hg bisect --reset
550 hg bisect --reset
551 hg bisect --bad 34
551 hg bisect --bad 34
552 hg bisect --good 12
552 hg bisect --good 12
553 hg bisect --command 'make && make tests'
553 hg bisect --command 'make && make tests'
554
554
555 - see all changesets whose states are already known in the current
555 - see all changesets whose states are already known in the current
556 bisection::
556 bisection::
557
557
558 hg log -r "bisect(pruned)"
558 hg log -r "bisect(pruned)"
559
559
560 - see all changesets that took part in the current bisection::
560 - see all changesets that took part in the current bisection::
561
561
562 hg log -r "bisect(range)"
562 hg log -r "bisect(range)"
563
563
564 - with the graphlog extension, you can even get a nice graph::
564 - with the graphlog extension, you can even get a nice graph::
565
565
566 hg log --graph -r "bisect(range)"
566 hg log --graph -r "bisect(range)"
567
567
568 See :hg:`help revsets` for more about the `bisect()` keyword.
568 See :hg:`help revsets` for more about the `bisect()` keyword.
569
569
570 Returns 0 on success.
570 Returns 0 on success.
571 """
571 """
572 def extendbisectrange(nodes, good):
572 def extendbisectrange(nodes, good):
573 # bisect is incomplete when it ends on a merge node and
573 # bisect is incomplete when it ends on a merge node and
574 # one of the parent was not checked.
574 # one of the parent was not checked.
575 parents = repo[nodes[0]].parents()
575 parents = repo[nodes[0]].parents()
576 if len(parents) > 1:
576 if len(parents) > 1:
577 side = good and state['bad'] or state['good']
577 side = good and state['bad'] or state['good']
578 num = len(set(i.node() for i in parents) & set(side))
578 num = len(set(i.node() for i in parents) & set(side))
579 if num == 1:
579 if num == 1:
580 return parents[0].ancestor(parents[1])
580 return parents[0].ancestor(parents[1])
581 return None
581 return None
582
582
583 def print_result(nodes, good):
583 def print_result(nodes, good):
584 displayer = cmdutil.show_changeset(ui, repo, {})
584 displayer = cmdutil.show_changeset(ui, repo, {})
585 if len(nodes) == 1:
585 if len(nodes) == 1:
586 # narrowed it down to a single revision
586 # narrowed it down to a single revision
587 if good:
587 if good:
588 ui.write(_("The first good revision is:\n"))
588 ui.write(_("The first good revision is:\n"))
589 else:
589 else:
590 ui.write(_("The first bad revision is:\n"))
590 ui.write(_("The first bad revision is:\n"))
591 displayer.show(repo[nodes[0]])
591 displayer.show(repo[nodes[0]])
592 extendnode = extendbisectrange(nodes, good)
592 extendnode = extendbisectrange(nodes, good)
593 if extendnode is not None:
593 if extendnode is not None:
594 ui.write(_('Not all ancestors of this changeset have been'
594 ui.write(_('Not all ancestors of this changeset have been'
595 ' checked.\nUse bisect --extend to continue the '
595 ' checked.\nUse bisect --extend to continue the '
596 'bisection from\nthe common ancestor, %s.\n')
596 'bisection from\nthe common ancestor, %s.\n')
597 % extendnode)
597 % extendnode)
598 else:
598 else:
599 # multiple possible revisions
599 # multiple possible revisions
600 if good:
600 if good:
601 ui.write(_("Due to skipped revisions, the first "
601 ui.write(_("Due to skipped revisions, the first "
602 "good revision could be any of:\n"))
602 "good revision could be any of:\n"))
603 else:
603 else:
604 ui.write(_("Due to skipped revisions, the first "
604 ui.write(_("Due to skipped revisions, the first "
605 "bad revision could be any of:\n"))
605 "bad revision could be any of:\n"))
606 for n in nodes:
606 for n in nodes:
607 displayer.show(repo[n])
607 displayer.show(repo[n])
608 displayer.close()
608 displayer.close()
609
609
610 def check_state(state, interactive=True):
610 def check_state(state, interactive=True):
611 if not state['good'] or not state['bad']:
611 if not state['good'] or not state['bad']:
612 if (good or bad or skip or reset) and interactive:
612 if (good or bad or skip or reset) and interactive:
613 return
613 return
614 if not state['good']:
614 if not state['good']:
615 raise util.Abort(_('cannot bisect (no known good revisions)'))
615 raise util.Abort(_('cannot bisect (no known good revisions)'))
616 else:
616 else:
617 raise util.Abort(_('cannot bisect (no known bad revisions)'))
617 raise util.Abort(_('cannot bisect (no known bad revisions)'))
618 return True
618 return True
619
619
620 # backward compatibility
620 # backward compatibility
621 if rev in "good bad reset init".split():
621 if rev in "good bad reset init".split():
622 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
622 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
623 cmd, rev, extra = rev, extra, None
623 cmd, rev, extra = rev, extra, None
624 if cmd == "good":
624 if cmd == "good":
625 good = True
625 good = True
626 elif cmd == "bad":
626 elif cmd == "bad":
627 bad = True
627 bad = True
628 else:
628 else:
629 reset = True
629 reset = True
630 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
630 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
631 raise util.Abort(_('incompatible arguments'))
631 raise util.Abort(_('incompatible arguments'))
632
632
633 if reset:
633 if reset:
634 p = repo.join("bisect.state")
634 p = repo.join("bisect.state")
635 if os.path.exists(p):
635 if os.path.exists(p):
636 os.unlink(p)
636 os.unlink(p)
637 return
637 return
638
638
639 state = hbisect.load_state(repo)
639 state = hbisect.load_state(repo)
640
640
641 if command:
641 if command:
642 changesets = 1
642 changesets = 1
643 try:
643 try:
644 while changesets:
644 while changesets:
645 # update state
645 # update state
646 status = util.system(command, out=ui.fout)
646 status = util.system(command, out=ui.fout)
647 if status == 125:
647 if status == 125:
648 transition = "skip"
648 transition = "skip"
649 elif status == 0:
649 elif status == 0:
650 transition = "good"
650 transition = "good"
651 # status < 0 means process was killed
651 # status < 0 means process was killed
652 elif status == 127:
652 elif status == 127:
653 raise util.Abort(_("failed to execute %s") % command)
653 raise util.Abort(_("failed to execute %s") % command)
654 elif status < 0:
654 elif status < 0:
655 raise util.Abort(_("%s killed") % command)
655 raise util.Abort(_("%s killed") % command)
656 else:
656 else:
657 transition = "bad"
657 transition = "bad"
658 ctx = scmutil.revsingle(repo, rev)
658 ctx = scmutil.revsingle(repo, rev)
659 rev = None # clear for future iterations
659 rev = None # clear for future iterations
660 state[transition].append(ctx.node())
660 state[transition].append(ctx.node())
661 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
661 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
662 check_state(state, interactive=False)
662 check_state(state, interactive=False)
663 # bisect
663 # bisect
664 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
664 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
665 # update to next check
665 # update to next check
666 cmdutil.bailifchanged(repo)
666 cmdutil.bailifchanged(repo)
667 hg.clean(repo, nodes[0], show_stats=False)
667 hg.clean(repo, nodes[0], show_stats=False)
668 finally:
668 finally:
669 hbisect.save_state(repo, state)
669 hbisect.save_state(repo, state)
670 print_result(nodes, good)
670 print_result(nodes, good)
671 return
671 return
672
672
673 # update state
673 # update state
674
674
675 if rev:
675 if rev:
676 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
676 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
677 else:
677 else:
678 nodes = [repo.lookup('.')]
678 nodes = [repo.lookup('.')]
679
679
680 if good or bad or skip:
680 if good or bad or skip:
681 if good:
681 if good:
682 state['good'] += nodes
682 state['good'] += nodes
683 elif bad:
683 elif bad:
684 state['bad'] += nodes
684 state['bad'] += nodes
685 elif skip:
685 elif skip:
686 state['skip'] += nodes
686 state['skip'] += nodes
687 hbisect.save_state(repo, state)
687 hbisect.save_state(repo, state)
688
688
689 if not check_state(state):
689 if not check_state(state):
690 return
690 return
691
691
692 # actually bisect
692 # actually bisect
693 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
693 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
694 if extend:
694 if extend:
695 if not changesets:
695 if not changesets:
696 extendnode = extendbisectrange(nodes, good)
696 extendnode = extendbisectrange(nodes, good)
697 if extendnode is not None:
697 if extendnode is not None:
698 ui.write(_("Extending search to changeset %d:%s\n"
698 ui.write(_("Extending search to changeset %d:%s\n"
699 % (extendnode.rev(), extendnode)))
699 % (extendnode.rev(), extendnode)))
700 if noupdate:
700 if noupdate:
701 return
701 return
702 cmdutil.bailifchanged(repo)
702 cmdutil.bailifchanged(repo)
703 return hg.clean(repo, extendnode.node())
703 return hg.clean(repo, extendnode.node())
704 raise util.Abort(_("nothing to extend"))
704 raise util.Abort(_("nothing to extend"))
705
705
706 if changesets == 0:
706 if changesets == 0:
707 print_result(nodes, good)
707 print_result(nodes, good)
708 else:
708 else:
709 assert len(nodes) == 1 # only a single node can be tested next
709 assert len(nodes) == 1 # only a single node can be tested next
710 node = nodes[0]
710 node = nodes[0]
711 # compute the approximate number of remaining tests
711 # compute the approximate number of remaining tests
712 tests, size = 0, 2
712 tests, size = 0, 2
713 while size <= changesets:
713 while size <= changesets:
714 tests, size = tests + 1, size * 2
714 tests, size = tests + 1, size * 2
715 rev = repo.changelog.rev(node)
715 rev = repo.changelog.rev(node)
716 ui.write(_("Testing changeset %d:%s "
716 ui.write(_("Testing changeset %d:%s "
717 "(%d changesets remaining, ~%d tests)\n")
717 "(%d changesets remaining, ~%d tests)\n")
718 % (rev, short(node), changesets, tests))
718 % (rev, short(node), changesets, tests))
719 if not noupdate:
719 if not noupdate:
720 cmdutil.bailifchanged(repo)
720 cmdutil.bailifchanged(repo)
721 return hg.clean(repo, node)
721 return hg.clean(repo, node)
722
722
723 @command('bookmarks',
723 @command('bookmarks',
724 [('f', 'force', False, _('force')),
724 [('f', 'force', False, _('force')),
725 ('r', 'rev', '', _('revision'), _('REV')),
725 ('r', 'rev', '', _('revision'), _('REV')),
726 ('d', 'delete', False, _('delete a given bookmark')),
726 ('d', 'delete', False, _('delete a given bookmark')),
727 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
727 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
728 ('i', 'inactive', False, _('mark a bookmark inactive'))],
728 ('i', 'inactive', False, _('mark a bookmark inactive'))],
729 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
729 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
730 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
730 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
731 rename=None, inactive=False):
731 rename=None, inactive=False):
732 '''track a line of development with movable markers
732 '''track a line of development with movable markers
733
733
734 Bookmarks are pointers to certain commits that move when committing.
734 Bookmarks are pointers to certain commits that move when committing.
735 Bookmarks are local. They can be renamed, copied and deleted. It is
735 Bookmarks are local. They can be renamed, copied and deleted. It is
736 possible to use :hg:`merge NAME` to merge from a given bookmark, and
736 possible to use :hg:`merge NAME` to merge from a given bookmark, and
737 :hg:`update NAME` to update to a given bookmark.
737 :hg:`update NAME` to update to a given bookmark.
738
738
739 You can use :hg:`bookmark NAME` to set a bookmark on the working
739 You can use :hg:`bookmark NAME` to set a bookmark on the working
740 directory's parent revision with the given name. If you specify
740 directory's parent revision with the given name. If you specify
741 a revision using -r REV (where REV may be an existing bookmark),
741 a revision using -r REV (where REV may be an existing bookmark),
742 the bookmark is assigned to that revision.
742 the bookmark is assigned to that revision.
743
743
744 Bookmarks can be pushed and pulled between repositories (see :hg:`help
744 Bookmarks can be pushed and pulled between repositories (see :hg:`help
745 push` and :hg:`help pull`). This requires both the local and remote
745 push` and :hg:`help pull`). This requires both the local and remote
746 repositories to support bookmarks. For versions prior to 1.8, this means
746 repositories to support bookmarks. For versions prior to 1.8, this means
747 the bookmarks extension must be enabled.
747 the bookmarks extension must be enabled.
748
748
749 With -i/--inactive, the new bookmark will not be made the active
749 With -i/--inactive, the new bookmark will not be made the active
750 bookmark. If -r/--rev is given, the new bookmark will not be made
750 bookmark. If -r/--rev is given, the new bookmark will not be made
751 active even if -i/--inactive is not given. If no NAME is given, the
751 active even if -i/--inactive is not given. If no NAME is given, the
752 current active bookmark will be marked inactive.
752 current active bookmark will be marked inactive.
753 '''
753 '''
754 hexfn = ui.debugflag and hex or short
754 hexfn = ui.debugflag and hex or short
755 marks = repo._bookmarks
755 marks = repo._bookmarks
756 cur = repo.changectx('.').node()
756 cur = repo.changectx('.').node()
757
757
758 if delete:
758 if delete:
759 if mark is None:
759 if mark is None:
760 raise util.Abort(_("bookmark name required"))
760 raise util.Abort(_("bookmark name required"))
761 if mark not in marks:
761 if mark not in marks:
762 raise util.Abort(_("bookmark '%s' does not exist") % mark)
762 raise util.Abort(_("bookmark '%s' does not exist") % mark)
763 if mark == repo._bookmarkcurrent:
763 if mark == repo._bookmarkcurrent:
764 bookmarks.setcurrent(repo, None)
764 bookmarks.setcurrent(repo, None)
765 del marks[mark]
765 del marks[mark]
766 bookmarks.write(repo)
766 bookmarks.write(repo)
767 return
767 return
768
768
769 if rename:
769 if rename:
770 if rename not in marks:
770 if rename not in marks:
771 raise util.Abort(_("bookmark '%s' does not exist") % rename)
771 raise util.Abort(_("bookmark '%s' does not exist") % rename)
772 if mark in marks and not force:
772 if mark in marks and not force:
773 raise util.Abort(_("bookmark '%s' already exists "
773 raise util.Abort(_("bookmark '%s' already exists "
774 "(use -f to force)") % mark)
774 "(use -f to force)") % mark)
775 if mark is None:
775 if mark is None:
776 raise util.Abort(_("new bookmark name required"))
776 raise util.Abort(_("new bookmark name required"))
777 marks[mark] = marks[rename]
777 marks[mark] = marks[rename]
778 if repo._bookmarkcurrent == rename and not inactive:
778 if repo._bookmarkcurrent == rename and not inactive:
779 bookmarks.setcurrent(repo, mark)
779 bookmarks.setcurrent(repo, mark)
780 del marks[rename]
780 del marks[rename]
781 bookmarks.write(repo)
781 bookmarks.write(repo)
782 return
782 return
783
783
784 if mark is not None:
784 if mark is not None:
785 if "\n" in mark:
785 if "\n" in mark:
786 raise util.Abort(_("bookmark name cannot contain newlines"))
786 raise util.Abort(_("bookmark name cannot contain newlines"))
787 mark = mark.strip()
787 mark = mark.strip()
788 if not mark:
788 if not mark:
789 raise util.Abort(_("bookmark names cannot consist entirely of "
789 raise util.Abort(_("bookmark names cannot consist entirely of "
790 "whitespace"))
790 "whitespace"))
791 if inactive and mark == repo._bookmarkcurrent:
791 if inactive and mark == repo._bookmarkcurrent:
792 bookmarks.setcurrent(repo, None)
792 bookmarks.setcurrent(repo, None)
793 return
793 return
794 if mark in marks and not force:
794 if mark in marks and not force:
795 raise util.Abort(_("bookmark '%s' already exists "
795 raise util.Abort(_("bookmark '%s' already exists "
796 "(use -f to force)") % mark)
796 "(use -f to force)") % mark)
797 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
797 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
798 and not force):
798 and not force):
799 raise util.Abort(
799 raise util.Abort(
800 _("a bookmark cannot have the name of an existing branch"))
800 _("a bookmark cannot have the name of an existing branch"))
801 if rev:
801 if rev:
802 marks[mark] = repo.lookup(rev)
802 marks[mark] = repo.lookup(rev)
803 else:
803 else:
804 marks[mark] = cur
804 marks[mark] = cur
805 if not inactive and cur == marks[mark]:
805 if not inactive and cur == marks[mark]:
806 bookmarks.setcurrent(repo, mark)
806 bookmarks.setcurrent(repo, mark)
807 bookmarks.write(repo)
807 bookmarks.write(repo)
808 return
808 return
809
809
810 if mark is None:
810 if mark is None:
811 if rev:
811 if rev:
812 raise util.Abort(_("bookmark name required"))
812 raise util.Abort(_("bookmark name required"))
813 if len(marks) == 0:
813 if len(marks) == 0:
814 ui.status(_("no bookmarks set\n"))
814 ui.status(_("no bookmarks set\n"))
815 else:
815 else:
816 for bmark, n in sorted(marks.iteritems()):
816 for bmark, n in sorted(marks.iteritems()):
817 current = repo._bookmarkcurrent
817 current = repo._bookmarkcurrent
818 if bmark == current and n == cur:
818 if bmark == current and n == cur:
819 prefix, label = '*', 'bookmarks.current'
819 prefix, label = '*', 'bookmarks.current'
820 else:
820 else:
821 prefix, label = ' ', ''
821 prefix, label = ' ', ''
822
822
823 if ui.quiet:
823 if ui.quiet:
824 ui.write("%s\n" % bmark, label=label)
824 ui.write("%s\n" % bmark, label=label)
825 else:
825 else:
826 ui.write(" %s %-25s %d:%s\n" % (
826 ui.write(" %s %-25s %d:%s\n" % (
827 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
827 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
828 label=label)
828 label=label)
829 return
829 return
830
830
831 @command('branch',
831 @command('branch',
832 [('f', 'force', None,
832 [('f', 'force', None,
833 _('set branch name even if it shadows an existing branch')),
833 _('set branch name even if it shadows an existing branch')),
834 ('C', 'clean', None, _('reset branch name to parent branch name'))],
834 ('C', 'clean', None, _('reset branch name to parent branch name'))],
835 _('[-fC] [NAME]'))
835 _('[-fC] [NAME]'))
836 def branch(ui, repo, label=None, **opts):
836 def branch(ui, repo, label=None, **opts):
837 """set or show the current branch name
837 """set or show the current branch name
838
838
839 .. note::
839 .. note::
840 Branch names are permanent and global. Use :hg:`bookmark` to create a
840 Branch names are permanent and global. Use :hg:`bookmark` to create a
841 light-weight bookmark instead. See :hg:`help glossary` for more
841 light-weight bookmark instead. See :hg:`help glossary` for more
842 information about named branches and bookmarks.
842 information about named branches and bookmarks.
843
843
844 With no argument, show the current branch name. With one argument,
844 With no argument, show the current branch name. With one argument,
845 set the working directory branch name (the branch will not exist
845 set the working directory branch name (the branch will not exist
846 in the repository until the next commit). Standard practice
846 in the repository until the next commit). Standard practice
847 recommends that primary development take place on the 'default'
847 recommends that primary development take place on the 'default'
848 branch.
848 branch.
849
849
850 Unless -f/--force is specified, branch will not let you set a
850 Unless -f/--force is specified, branch will not let you set a
851 branch name that already exists, even if it's inactive.
851 branch name that already exists, even if it's inactive.
852
852
853 Use -C/--clean to reset the working directory branch to that of
853 Use -C/--clean to reset the working directory branch to that of
854 the parent of the working directory, negating a previous branch
854 the parent of the working directory, negating a previous branch
855 change.
855 change.
856
856
857 Use the command :hg:`update` to switch to an existing branch. Use
857 Use the command :hg:`update` to switch to an existing branch. Use
858 :hg:`commit --close-branch` to mark this branch as closed.
858 :hg:`commit --close-branch` to mark this branch as closed.
859
859
860 Returns 0 on success.
860 Returns 0 on success.
861 """
861 """
862
862
863 if opts.get('clean'):
863 if opts.get('clean'):
864 label = repo[None].p1().branch()
864 label = repo[None].p1().branch()
865 repo.dirstate.setbranch(label)
865 repo.dirstate.setbranch(label)
866 ui.status(_('reset working directory to branch %s\n') % label)
866 ui.status(_('reset working directory to branch %s\n') % label)
867 elif label:
867 elif label:
868 if not opts.get('force') and label in repo.branchtags():
868 if not opts.get('force') and label in repo.branchtags():
869 if label not in [p.branch() for p in repo.parents()]:
869 if label not in [p.branch() for p in repo.parents()]:
870 raise util.Abort(_('a branch of the same name already exists'),
870 raise util.Abort(_('a branch of the same name already exists'),
871 # i18n: "it" refers to an existing branch
871 # i18n: "it" refers to an existing branch
872 hint=_("use 'hg update' to switch to it"))
872 hint=_("use 'hg update' to switch to it"))
873 repo.dirstate.setbranch(label)
873 repo.dirstate.setbranch(label)
874 ui.status(_('marked working directory as branch %s\n') % label)
874 ui.status(_('marked working directory as branch %s\n') % label)
875 ui.status(_('(branches are permanent and global, '
875 ui.status(_('(branches are permanent and global, '
876 'did you want a bookmark?)\n'))
876 'did you want a bookmark?)\n'))
877 else:
877 else:
878 ui.write("%s\n" % repo.dirstate.branch())
878 ui.write("%s\n" % repo.dirstate.branch())
879
879
880 @command('branches',
880 @command('branches',
881 [('a', 'active', False, _('show only branches that have unmerged heads')),
881 [('a', 'active', False, _('show only branches that have unmerged heads')),
882 ('c', 'closed', False, _('show normal and closed branches'))],
882 ('c', 'closed', False, _('show normal and closed branches'))],
883 _('[-ac]'))
883 _('[-ac]'))
884 def branches(ui, repo, active=False, closed=False):
884 def branches(ui, repo, active=False, closed=False):
885 """list repository named branches
885 """list repository named branches
886
886
887 List the repository's named branches, indicating which ones are
887 List the repository's named branches, indicating which ones are
888 inactive. If -c/--closed is specified, also list branches which have
888 inactive. If -c/--closed is specified, also list branches which have
889 been marked closed (see :hg:`commit --close-branch`).
889 been marked closed (see :hg:`commit --close-branch`).
890
890
891 If -a/--active is specified, only show active branches. A branch
891 If -a/--active is specified, only show active branches. A branch
892 is considered active if it contains repository heads.
892 is considered active if it contains repository heads.
893
893
894 Use the command :hg:`update` to switch to an existing branch.
894 Use the command :hg:`update` to switch to an existing branch.
895
895
896 Returns 0.
896 Returns 0.
897 """
897 """
898
898
899 hexfunc = ui.debugflag and hex or short
899 hexfunc = ui.debugflag and hex or short
900 activebranches = [repo[n].branch() for n in repo.heads()]
900 activebranches = [repo[n].branch() for n in repo.heads()]
901 def testactive(tag, node):
901 def testactive(tag, node):
902 realhead = tag in activebranches
902 realhead = tag in activebranches
903 open = node in repo.branchheads(tag, closed=False)
903 open = node in repo.branchheads(tag, closed=False)
904 return realhead and open
904 return realhead and open
905 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
905 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
906 for tag, node in repo.branchtags().items()],
906 for tag, node in repo.branchtags().items()],
907 reverse=True)
907 reverse=True)
908
908
909 for isactive, node, tag in branches:
909 for isactive, node, tag in branches:
910 if (not active) or isactive:
910 if (not active) or isactive:
911 if ui.quiet:
911 if ui.quiet:
912 ui.write("%s\n" % tag)
912 ui.write("%s\n" % tag)
913 else:
913 else:
914 hn = repo.lookup(node)
914 hn = repo.lookup(node)
915 if isactive:
915 if isactive:
916 label = 'branches.active'
916 label = 'branches.active'
917 notice = ''
917 notice = ''
918 elif hn not in repo.branchheads(tag, closed=False):
918 elif hn not in repo.branchheads(tag, closed=False):
919 if not closed:
919 if not closed:
920 continue
920 continue
921 label = 'branches.closed'
921 label = 'branches.closed'
922 notice = _(' (closed)')
922 notice = _(' (closed)')
923 else:
923 else:
924 label = 'branches.inactive'
924 label = 'branches.inactive'
925 notice = _(' (inactive)')
925 notice = _(' (inactive)')
926 if tag == repo.dirstate.branch():
926 if tag == repo.dirstate.branch():
927 label = 'branches.current'
927 label = 'branches.current'
928 rev = str(node).rjust(31 - encoding.colwidth(tag))
928 rev = str(node).rjust(31 - encoding.colwidth(tag))
929 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
929 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
930 tag = ui.label(tag, label)
930 tag = ui.label(tag, label)
931 ui.write("%s %s%s\n" % (tag, rev, notice))
931 ui.write("%s %s%s\n" % (tag, rev, notice))
932
932
933 @command('bundle',
933 @command('bundle',
934 [('f', 'force', None, _('run even when the destination is unrelated')),
934 [('f', 'force', None, _('run even when the destination is unrelated')),
935 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
935 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
936 _('REV')),
936 _('REV')),
937 ('b', 'branch', [], _('a specific branch you would like to bundle'),
937 ('b', 'branch', [], _('a specific branch you would like to bundle'),
938 _('BRANCH')),
938 _('BRANCH')),
939 ('', 'base', [],
939 ('', 'base', [],
940 _('a base changeset assumed to be available at the destination'),
940 _('a base changeset assumed to be available at the destination'),
941 _('REV')),
941 _('REV')),
942 ('a', 'all', None, _('bundle all changesets in the repository')),
942 ('a', 'all', None, _('bundle all changesets in the repository')),
943 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
943 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
944 ] + remoteopts,
944 ] + remoteopts,
945 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
945 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
946 def bundle(ui, repo, fname, dest=None, **opts):
946 def bundle(ui, repo, fname, dest=None, **opts):
947 """create a changegroup file
947 """create a changegroup file
948
948
949 Generate a compressed changegroup file collecting changesets not
949 Generate a compressed changegroup file collecting changesets not
950 known to be in another repository.
950 known to be in another repository.
951
951
952 If you omit the destination repository, then hg assumes the
952 If you omit the destination repository, then hg assumes the
953 destination will have all the nodes you specify with --base
953 destination will have all the nodes you specify with --base
954 parameters. To create a bundle containing all changesets, use
954 parameters. To create a bundle containing all changesets, use
955 -a/--all (or --base null).
955 -a/--all (or --base null).
956
956
957 You can change compression method with the -t/--type option.
957 You can change compression method with the -t/--type option.
958 The available compression methods are: none, bzip2, and
958 The available compression methods are: none, bzip2, and
959 gzip (by default, bundles are compressed using bzip2).
959 gzip (by default, bundles are compressed using bzip2).
960
960
961 The bundle file can then be transferred using conventional means
961 The bundle file can then be transferred using conventional means
962 and applied to another repository with the unbundle or pull
962 and applied to another repository with the unbundle or pull
963 command. This is useful when direct push and pull are not
963 command. This is useful when direct push and pull are not
964 available or when exporting an entire repository is undesirable.
964 available or when exporting an entire repository is undesirable.
965
965
966 Applying bundles preserves all changeset contents including
966 Applying bundles preserves all changeset contents including
967 permissions, copy/rename information, and revision history.
967 permissions, copy/rename information, and revision history.
968
968
969 Returns 0 on success, 1 if no changes found.
969 Returns 0 on success, 1 if no changes found.
970 """
970 """
971 revs = None
971 revs = None
972 if 'rev' in opts:
972 if 'rev' in opts:
973 revs = scmutil.revrange(repo, opts['rev'])
973 revs = scmutil.revrange(repo, opts['rev'])
974
974
975 if opts.get('all'):
975 if opts.get('all'):
976 base = ['null']
976 base = ['null']
977 else:
977 else:
978 base = scmutil.revrange(repo, opts.get('base'))
978 base = scmutil.revrange(repo, opts.get('base'))
979 if base:
979 if base:
980 if dest:
980 if dest:
981 raise util.Abort(_("--base is incompatible with specifying "
981 raise util.Abort(_("--base is incompatible with specifying "
982 "a destination"))
982 "a destination"))
983 common = [repo.lookup(rev) for rev in base]
983 common = [repo.lookup(rev) for rev in base]
984 heads = revs and map(repo.lookup, revs) or revs
984 heads = revs and map(repo.lookup, revs) or revs
985 cg = repo.getbundle('bundle', heads=heads, common=common)
985 cg = repo.getbundle('bundle', heads=heads, common=common)
986 outgoing = None
986 outgoing = None
987 else:
987 else:
988 dest = ui.expandpath(dest or 'default-push', dest or 'default')
988 dest = ui.expandpath(dest or 'default-push', dest or 'default')
989 dest, branches = hg.parseurl(dest, opts.get('branch'))
989 dest, branches = hg.parseurl(dest, opts.get('branch'))
990 other = hg.peer(repo, opts, dest)
990 other = hg.peer(repo, opts, dest)
991 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
991 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
992 heads = revs and map(repo.lookup, revs) or revs
992 heads = revs and map(repo.lookup, revs) or revs
993 outgoing = discovery.findcommonoutgoing(repo, other,
993 outgoing = discovery.findcommonoutgoing(repo, other,
994 onlyheads=heads,
994 onlyheads=heads,
995 force=opts.get('force'))
995 force=opts.get('force'))
996 cg = repo.getlocalbundle('bundle', outgoing)
996 cg = repo.getlocalbundle('bundle', outgoing)
997 if not cg:
997 if not cg:
998 scmutil.nochangesfound(ui, outgoing and outgoing.excluded)
998 scmutil.nochangesfound(ui, outgoing and outgoing.excluded)
999 return 1
999 return 1
1000
1000
1001 bundletype = opts.get('type', 'bzip2').lower()
1001 bundletype = opts.get('type', 'bzip2').lower()
1002 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1002 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1003 bundletype = btypes.get(bundletype)
1003 bundletype = btypes.get(bundletype)
1004 if bundletype not in changegroup.bundletypes:
1004 if bundletype not in changegroup.bundletypes:
1005 raise util.Abort(_('unknown bundle type specified with --type'))
1005 raise util.Abort(_('unknown bundle type specified with --type'))
1006
1006
1007 changegroup.writebundle(cg, fname, bundletype)
1007 changegroup.writebundle(cg, fname, bundletype)
1008
1008
1009 @command('cat',
1009 @command('cat',
1010 [('o', 'output', '',
1010 [('o', 'output', '',
1011 _('print output to file with formatted name'), _('FORMAT')),
1011 _('print output to file with formatted name'), _('FORMAT')),
1012 ('r', 'rev', '', _('print the given revision'), _('REV')),
1012 ('r', 'rev', '', _('print the given revision'), _('REV')),
1013 ('', 'decode', None, _('apply any matching decode filter')),
1013 ('', 'decode', None, _('apply any matching decode filter')),
1014 ] + walkopts,
1014 ] + walkopts,
1015 _('[OPTION]... FILE...'))
1015 _('[OPTION]... FILE...'))
1016 def cat(ui, repo, file1, *pats, **opts):
1016 def cat(ui, repo, file1, *pats, **opts):
1017 """output the current or given revision of files
1017 """output the current or given revision of files
1018
1018
1019 Print the specified files as they were at the given revision. If
1019 Print the specified files as they were at the given revision. If
1020 no revision is given, the parent of the working directory is used,
1020 no revision is given, the parent of the working directory is used,
1021 or tip if no revision is checked out.
1021 or tip if no revision is checked out.
1022
1022
1023 Output may be to a file, in which case the name of the file is
1023 Output may be to a file, in which case the name of the file is
1024 given using a format string. The formatting rules are the same as
1024 given using a format string. The formatting rules are the same as
1025 for the export command, with the following additions:
1025 for the export command, with the following additions:
1026
1026
1027 :``%s``: basename of file being printed
1027 :``%s``: basename of file being printed
1028 :``%d``: dirname of file being printed, or '.' if in repository root
1028 :``%d``: dirname of file being printed, or '.' if in repository root
1029 :``%p``: root-relative path name of file being printed
1029 :``%p``: root-relative path name of file being printed
1030
1030
1031 Returns 0 on success.
1031 Returns 0 on success.
1032 """
1032 """
1033 ctx = scmutil.revsingle(repo, opts.get('rev'))
1033 ctx = scmutil.revsingle(repo, opts.get('rev'))
1034 err = 1
1034 err = 1
1035 m = scmutil.match(ctx, (file1,) + pats, opts)
1035 m = scmutil.match(ctx, (file1,) + pats, opts)
1036 for abs in ctx.walk(m):
1036 for abs in ctx.walk(m):
1037 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1037 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1038 pathname=abs)
1038 pathname=abs)
1039 data = ctx[abs].data()
1039 data = ctx[abs].data()
1040 if opts.get('decode'):
1040 if opts.get('decode'):
1041 data = repo.wwritedata(abs, data)
1041 data = repo.wwritedata(abs, data)
1042 fp.write(data)
1042 fp.write(data)
1043 fp.close()
1043 fp.close()
1044 err = 0
1044 err = 0
1045 return err
1045 return err
1046
1046
1047 @command('^clone',
1047 @command('^clone',
1048 [('U', 'noupdate', None,
1048 [('U', 'noupdate', None,
1049 _('the clone will include an empty working copy (only a repository)')),
1049 _('the clone will include an empty working copy (only a repository)')),
1050 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1050 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1051 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1051 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1052 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1052 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1053 ('', 'pull', None, _('use pull protocol to copy metadata')),
1053 ('', 'pull', None, _('use pull protocol to copy metadata')),
1054 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1054 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1055 ] + remoteopts,
1055 ] + remoteopts,
1056 _('[OPTION]... SOURCE [DEST]'))
1056 _('[OPTION]... SOURCE [DEST]'))
1057 def clone(ui, source, dest=None, **opts):
1057 def clone(ui, source, dest=None, **opts):
1058 """make a copy of an existing repository
1058 """make a copy of an existing repository
1059
1059
1060 Create a copy of an existing repository in a new directory.
1060 Create a copy of an existing repository in a new directory.
1061
1061
1062 If no destination directory name is specified, it defaults to the
1062 If no destination directory name is specified, it defaults to the
1063 basename of the source.
1063 basename of the source.
1064
1064
1065 The location of the source is added to the new repository's
1065 The location of the source is added to the new repository's
1066 ``.hg/hgrc`` file, as the default to be used for future pulls.
1066 ``.hg/hgrc`` file, as the default to be used for future pulls.
1067
1067
1068 Only local paths and ``ssh://`` URLs are supported as
1068 Only local paths and ``ssh://`` URLs are supported as
1069 destinations. For ``ssh://`` destinations, no working directory or
1069 destinations. For ``ssh://`` destinations, no working directory or
1070 ``.hg/hgrc`` will be created on the remote side.
1070 ``.hg/hgrc`` will be created on the remote side.
1071
1071
1072 To pull only a subset of changesets, specify one or more revisions
1072 To pull only a subset of changesets, specify one or more revisions
1073 identifiers with -r/--rev or branches with -b/--branch. The
1073 identifiers with -r/--rev or branches with -b/--branch. The
1074 resulting clone will contain only the specified changesets and
1074 resulting clone will contain only the specified changesets and
1075 their ancestors. These options (or 'clone src#rev dest') imply
1075 their ancestors. These options (or 'clone src#rev dest') imply
1076 --pull, even for local source repositories. Note that specifying a
1076 --pull, even for local source repositories. Note that specifying a
1077 tag will include the tagged changeset but not the changeset
1077 tag will include the tagged changeset but not the changeset
1078 containing the tag.
1078 containing the tag.
1079
1079
1080 To check out a particular version, use -u/--update, or
1080 To check out a particular version, use -u/--update, or
1081 -U/--noupdate to create a clone with no working directory.
1081 -U/--noupdate to create a clone with no working directory.
1082
1082
1083 .. container:: verbose
1083 .. container:: verbose
1084
1084
1085 For efficiency, hardlinks are used for cloning whenever the
1085 For efficiency, hardlinks are used for cloning whenever the
1086 source and destination are on the same filesystem (note this
1086 source and destination are on the same filesystem (note this
1087 applies only to the repository data, not to the working
1087 applies only to the repository data, not to the working
1088 directory). Some filesystems, such as AFS, implement hardlinking
1088 directory). Some filesystems, such as AFS, implement hardlinking
1089 incorrectly, but do not report errors. In these cases, use the
1089 incorrectly, but do not report errors. In these cases, use the
1090 --pull option to avoid hardlinking.
1090 --pull option to avoid hardlinking.
1091
1091
1092 In some cases, you can clone repositories and the working
1092 In some cases, you can clone repositories and the working
1093 directory using full hardlinks with ::
1093 directory using full hardlinks with ::
1094
1094
1095 $ cp -al REPO REPOCLONE
1095 $ cp -al REPO REPOCLONE
1096
1096
1097 This is the fastest way to clone, but it is not always safe. The
1097 This is the fastest way to clone, but it is not always safe. The
1098 operation is not atomic (making sure REPO is not modified during
1098 operation is not atomic (making sure REPO is not modified during
1099 the operation is up to you) and you have to make sure your
1099 the operation is up to you) and you have to make sure your
1100 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1100 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1101 so). Also, this is not compatible with certain extensions that
1101 so). Also, this is not compatible with certain extensions that
1102 place their metadata under the .hg directory, such as mq.
1102 place their metadata under the .hg directory, such as mq.
1103
1103
1104 Mercurial will update the working directory to the first applicable
1104 Mercurial will update the working directory to the first applicable
1105 revision from this list:
1105 revision from this list:
1106
1106
1107 a) null if -U or the source repository has no changesets
1107 a) null if -U or the source repository has no changesets
1108 b) if -u . and the source repository is local, the first parent of
1108 b) if -u . and the source repository is local, the first parent of
1109 the source repository's working directory
1109 the source repository's working directory
1110 c) the changeset specified with -u (if a branch name, this means the
1110 c) the changeset specified with -u (if a branch name, this means the
1111 latest head of that branch)
1111 latest head of that branch)
1112 d) the changeset specified with -r
1112 d) the changeset specified with -r
1113 e) the tipmost head specified with -b
1113 e) the tipmost head specified with -b
1114 f) the tipmost head specified with the url#branch source syntax
1114 f) the tipmost head specified with the url#branch source syntax
1115 g) the tipmost head of the default branch
1115 g) the tipmost head of the default branch
1116 h) tip
1116 h) tip
1117
1117
1118 Examples:
1118 Examples:
1119
1119
1120 - clone a remote repository to a new directory named hg/::
1120 - clone a remote repository to a new directory named hg/::
1121
1121
1122 hg clone http://selenic.com/hg
1122 hg clone http://selenic.com/hg
1123
1123
1124 - create a lightweight local clone::
1124 - create a lightweight local clone::
1125
1125
1126 hg clone project/ project-feature/
1126 hg clone project/ project-feature/
1127
1127
1128 - clone from an absolute path on an ssh server (note double-slash)::
1128 - clone from an absolute path on an ssh server (note double-slash)::
1129
1129
1130 hg clone ssh://user@server//home/projects/alpha/
1130 hg clone ssh://user@server//home/projects/alpha/
1131
1131
1132 - do a high-speed clone over a LAN while checking out a
1132 - do a high-speed clone over a LAN while checking out a
1133 specified version::
1133 specified version::
1134
1134
1135 hg clone --uncompressed http://server/repo -u 1.5
1135 hg clone --uncompressed http://server/repo -u 1.5
1136
1136
1137 - create a repository without changesets after a particular revision::
1137 - create a repository without changesets after a particular revision::
1138
1138
1139 hg clone -r 04e544 experimental/ good/
1139 hg clone -r 04e544 experimental/ good/
1140
1140
1141 - clone (and track) a particular named branch::
1141 - clone (and track) a particular named branch::
1142
1142
1143 hg clone http://selenic.com/hg#stable
1143 hg clone http://selenic.com/hg#stable
1144
1144
1145 See :hg:`help urls` for details on specifying URLs.
1145 See :hg:`help urls` for details on specifying URLs.
1146
1146
1147 Returns 0 on success.
1147 Returns 0 on success.
1148 """
1148 """
1149 if opts.get('noupdate') and opts.get('updaterev'):
1149 if opts.get('noupdate') and opts.get('updaterev'):
1150 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1150 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1151
1151
1152 r = hg.clone(ui, opts, source, dest,
1152 r = hg.clone(ui, opts, source, dest,
1153 pull=opts.get('pull'),
1153 pull=opts.get('pull'),
1154 stream=opts.get('uncompressed'),
1154 stream=opts.get('uncompressed'),
1155 rev=opts.get('rev'),
1155 rev=opts.get('rev'),
1156 update=opts.get('updaterev') or not opts.get('noupdate'),
1156 update=opts.get('updaterev') or not opts.get('noupdate'),
1157 branch=opts.get('branch'))
1157 branch=opts.get('branch'))
1158
1158
1159 return r is None
1159 return r is None
1160
1160
1161 @command('^commit|ci',
1161 @command('^commit|ci',
1162 [('A', 'addremove', None,
1162 [('A', 'addremove', None,
1163 _('mark new/missing files as added/removed before committing')),
1163 _('mark new/missing files as added/removed before committing')),
1164 ('', 'close-branch', None,
1164 ('', 'close-branch', None,
1165 _('mark a branch as closed, hiding it from the branch list')),
1165 _('mark a branch as closed, hiding it from the branch list')),
1166 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1166 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1167 _('[OPTION]... [FILE]...'))
1167 _('[OPTION]... [FILE]...'))
1168 def commit(ui, repo, *pats, **opts):
1168 def commit(ui, repo, *pats, **opts):
1169 """commit the specified files or all outstanding changes
1169 """commit the specified files or all outstanding changes
1170
1170
1171 Commit changes to the given files into the repository. Unlike a
1171 Commit changes to the given files into the repository. Unlike a
1172 centralized SCM, this operation is a local operation. See
1172 centralized SCM, this operation is a local operation. See
1173 :hg:`push` for a way to actively distribute your changes.
1173 :hg:`push` for a way to actively distribute your changes.
1174
1174
1175 If a list of files is omitted, all changes reported by :hg:`status`
1175 If a list of files is omitted, all changes reported by :hg:`status`
1176 will be committed.
1176 will be committed.
1177
1177
1178 If you are committing the result of a merge, do not provide any
1178 If you are committing the result of a merge, do not provide any
1179 filenames or -I/-X filters.
1179 filenames or -I/-X filters.
1180
1180
1181 If no commit message is specified, Mercurial starts your
1181 If no commit message is specified, Mercurial starts your
1182 configured editor where you can enter a message. In case your
1182 configured editor where you can enter a message. In case your
1183 commit fails, you will find a backup of your message in
1183 commit fails, you will find a backup of your message in
1184 ``.hg/last-message.txt``.
1184 ``.hg/last-message.txt``.
1185
1185
1186 See :hg:`help dates` for a list of formats valid for -d/--date.
1186 See :hg:`help dates` for a list of formats valid for -d/--date.
1187
1187
1188 Returns 0 on success, 1 if nothing changed.
1188 Returns 0 on success, 1 if nothing changed.
1189 """
1189 """
1190 if opts.get('subrepos'):
1190 if opts.get('subrepos'):
1191 # Let --subrepos on the command line overide config setting.
1191 # Let --subrepos on the command line overide config setting.
1192 ui.setconfig('ui', 'commitsubrepos', True)
1192 ui.setconfig('ui', 'commitsubrepos', True)
1193
1193
1194 extra = {}
1194 extra = {}
1195 if opts.get('close_branch'):
1195 if opts.get('close_branch'):
1196 if repo['.'].node() not in repo.branchheads():
1196 if repo['.'].node() not in repo.branchheads():
1197 # The topo heads set is included in the branch heads set of the
1197 # The topo heads set is included in the branch heads set of the
1198 # current branch, so it's sufficient to test branchheads
1198 # current branch, so it's sufficient to test branchheads
1199 raise util.Abort(_('can only close branch heads'))
1199 raise util.Abort(_('can only close branch heads'))
1200 extra['close'] = 1
1200 extra['close'] = 1
1201 e = cmdutil.commiteditor
1201 e = cmdutil.commiteditor
1202 if opts.get('force_editor'):
1202 if opts.get('force_editor'):
1203 e = cmdutil.commitforceeditor
1203 e = cmdutil.commitforceeditor
1204
1204
1205 def commitfunc(ui, repo, message, match, opts):
1205 def commitfunc(ui, repo, message, match, opts):
1206 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1206 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1207 editor=e, extra=extra)
1207 editor=e, extra=extra)
1208
1208
1209 branch = repo[None].branch()
1209 branch = repo[None].branch()
1210 bheads = repo.branchheads(branch)
1210 bheads = repo.branchheads(branch)
1211
1211
1212 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1212 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1213 if not node:
1213 if not node:
1214 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1214 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1215 if stat[3]:
1215 if stat[3]:
1216 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1216 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1217 % len(stat[3]))
1217 % len(stat[3]))
1218 else:
1218 else:
1219 ui.status(_("nothing changed\n"))
1219 ui.status(_("nothing changed\n"))
1220 return 1
1220 return 1
1221
1221
1222 ctx = repo[node]
1222 ctx = repo[node]
1223 parents = ctx.parents()
1223 parents = ctx.parents()
1224
1224
1225 if (bheads and node not in bheads and not
1225 if (bheads and node not in bheads and not
1226 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1226 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1227 ui.status(_('created new head\n'))
1227 ui.status(_('created new head\n'))
1228 # The message is not printed for initial roots. For the other
1228 # The message is not printed for initial roots. For the other
1229 # changesets, it is printed in the following situations:
1229 # changesets, it is printed in the following situations:
1230 #
1230 #
1231 # Par column: for the 2 parents with ...
1231 # Par column: for the 2 parents with ...
1232 # N: null or no parent
1232 # N: null or no parent
1233 # B: parent is on another named branch
1233 # B: parent is on another named branch
1234 # C: parent is a regular non head changeset
1234 # C: parent is a regular non head changeset
1235 # H: parent was a branch head of the current branch
1235 # H: parent was a branch head of the current branch
1236 # Msg column: whether we print "created new head" message
1236 # Msg column: whether we print "created new head" message
1237 # In the following, it is assumed that there already exists some
1237 # In the following, it is assumed that there already exists some
1238 # initial branch heads of the current branch, otherwise nothing is
1238 # initial branch heads of the current branch, otherwise nothing is
1239 # printed anyway.
1239 # printed anyway.
1240 #
1240 #
1241 # Par Msg Comment
1241 # Par Msg Comment
1242 # NN y additional topo root
1242 # NN y additional topo root
1243 #
1243 #
1244 # BN y additional branch root
1244 # BN y additional branch root
1245 # CN y additional topo head
1245 # CN y additional topo head
1246 # HN n usual case
1246 # HN n usual case
1247 #
1247 #
1248 # BB y weird additional branch root
1248 # BB y weird additional branch root
1249 # CB y branch merge
1249 # CB y branch merge
1250 # HB n merge with named branch
1250 # HB n merge with named branch
1251 #
1251 #
1252 # CC y additional head from merge
1252 # CC y additional head from merge
1253 # CH n merge with a head
1253 # CH n merge with a head
1254 #
1254 #
1255 # HH n head merge: head count decreases
1255 # HH n head merge: head count decreases
1256
1256
1257 if not opts.get('close_branch'):
1257 if not opts.get('close_branch'):
1258 for r in parents:
1258 for r in parents:
1259 if r.extra().get('close') and r.branch() == branch:
1259 if r.extra().get('close') and r.branch() == branch:
1260 ui.status(_('reopening closed branch head %d\n') % r)
1260 ui.status(_('reopening closed branch head %d\n') % r)
1261
1261
1262 if ui.debugflag:
1262 if ui.debugflag:
1263 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1263 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1264 elif ui.verbose:
1264 elif ui.verbose:
1265 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1265 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1266
1266
1267 @command('copy|cp',
1267 @command('copy|cp',
1268 [('A', 'after', None, _('record a copy that has already occurred')),
1268 [('A', 'after', None, _('record a copy that has already occurred')),
1269 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1269 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1270 ] + walkopts + dryrunopts,
1270 ] + walkopts + dryrunopts,
1271 _('[OPTION]... [SOURCE]... DEST'))
1271 _('[OPTION]... [SOURCE]... DEST'))
1272 def copy(ui, repo, *pats, **opts):
1272 def copy(ui, repo, *pats, **opts):
1273 """mark files as copied for the next commit
1273 """mark files as copied for the next commit
1274
1274
1275 Mark dest as having copies of source files. If dest is a
1275 Mark dest as having copies of source files. If dest is a
1276 directory, copies are put in that directory. If dest is a file,
1276 directory, copies are put in that directory. If dest is a file,
1277 the source must be a single file.
1277 the source must be a single file.
1278
1278
1279 By default, this command copies the contents of files as they
1279 By default, this command copies the contents of files as they
1280 exist in the working directory. If invoked with -A/--after, the
1280 exist in the working directory. If invoked with -A/--after, the
1281 operation is recorded, but no copying is performed.
1281 operation is recorded, but no copying is performed.
1282
1282
1283 This command takes effect with the next commit. To undo a copy
1283 This command takes effect with the next commit. To undo a copy
1284 before that, see :hg:`revert`.
1284 before that, see :hg:`revert`.
1285
1285
1286 Returns 0 on success, 1 if errors are encountered.
1286 Returns 0 on success, 1 if errors are encountered.
1287 """
1287 """
1288 wlock = repo.wlock(False)
1288 wlock = repo.wlock(False)
1289 try:
1289 try:
1290 return cmdutil.copy(ui, repo, pats, opts)
1290 return cmdutil.copy(ui, repo, pats, opts)
1291 finally:
1291 finally:
1292 wlock.release()
1292 wlock.release()
1293
1293
1294 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1294 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1295 def debugancestor(ui, repo, *args):
1295 def debugancestor(ui, repo, *args):
1296 """find the ancestor revision of two revisions in a given index"""
1296 """find the ancestor revision of two revisions in a given index"""
1297 if len(args) == 3:
1297 if len(args) == 3:
1298 index, rev1, rev2 = args
1298 index, rev1, rev2 = args
1299 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1299 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1300 lookup = r.lookup
1300 lookup = r.lookup
1301 elif len(args) == 2:
1301 elif len(args) == 2:
1302 if not repo:
1302 if not repo:
1303 raise util.Abort(_("there is no Mercurial repository here "
1303 raise util.Abort(_("there is no Mercurial repository here "
1304 "(.hg not found)"))
1304 "(.hg not found)"))
1305 rev1, rev2 = args
1305 rev1, rev2 = args
1306 r = repo.changelog
1306 r = repo.changelog
1307 lookup = repo.lookup
1307 lookup = repo.lookup
1308 else:
1308 else:
1309 raise util.Abort(_('either two or three arguments required'))
1309 raise util.Abort(_('either two or three arguments required'))
1310 a = r.ancestor(lookup(rev1), lookup(rev2))
1310 a = r.ancestor(lookup(rev1), lookup(rev2))
1311 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1311 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1312
1312
1313 @command('debugbuilddag',
1313 @command('debugbuilddag',
1314 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1314 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1315 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1315 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1316 ('n', 'new-file', None, _('add new file at each rev'))],
1316 ('n', 'new-file', None, _('add new file at each rev'))],
1317 _('[OPTION]... [TEXT]'))
1317 _('[OPTION]... [TEXT]'))
1318 def debugbuilddag(ui, repo, text=None,
1318 def debugbuilddag(ui, repo, text=None,
1319 mergeable_file=False,
1319 mergeable_file=False,
1320 overwritten_file=False,
1320 overwritten_file=False,
1321 new_file=False):
1321 new_file=False):
1322 """builds a repo with a given DAG from scratch in the current empty repo
1322 """builds a repo with a given DAG from scratch in the current empty repo
1323
1323
1324 The description of the DAG is read from stdin if not given on the
1324 The description of the DAG is read from stdin if not given on the
1325 command line.
1325 command line.
1326
1326
1327 Elements:
1327 Elements:
1328
1328
1329 - "+n" is a linear run of n nodes based on the current default parent
1329 - "+n" is a linear run of n nodes based on the current default parent
1330 - "." is a single node based on the current default parent
1330 - "." is a single node based on the current default parent
1331 - "$" resets the default parent to null (implied at the start);
1331 - "$" resets the default parent to null (implied at the start);
1332 otherwise the default parent is always the last node created
1332 otherwise the default parent is always the last node created
1333 - "<p" sets the default parent to the backref p
1333 - "<p" sets the default parent to the backref p
1334 - "*p" is a fork at parent p, which is a backref
1334 - "*p" is a fork at parent p, which is a backref
1335 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1335 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1336 - "/p2" is a merge of the preceding node and p2
1336 - "/p2" is a merge of the preceding node and p2
1337 - ":tag" defines a local tag for the preceding node
1337 - ":tag" defines a local tag for the preceding node
1338 - "@branch" sets the named branch for subsequent nodes
1338 - "@branch" sets the named branch for subsequent nodes
1339 - "#...\\n" is a comment up to the end of the line
1339 - "#...\\n" is a comment up to the end of the line
1340
1340
1341 Whitespace between the above elements is ignored.
1341 Whitespace between the above elements is ignored.
1342
1342
1343 A backref is either
1343 A backref is either
1344
1344
1345 - a number n, which references the node curr-n, where curr is the current
1345 - a number n, which references the node curr-n, where curr is the current
1346 node, or
1346 node, or
1347 - the name of a local tag you placed earlier using ":tag", or
1347 - the name of a local tag you placed earlier using ":tag", or
1348 - empty to denote the default parent.
1348 - empty to denote the default parent.
1349
1349
1350 All string valued-elements are either strictly alphanumeric, or must
1350 All string valued-elements are either strictly alphanumeric, or must
1351 be enclosed in double quotes ("..."), with "\\" as escape character.
1351 be enclosed in double quotes ("..."), with "\\" as escape character.
1352 """
1352 """
1353
1353
1354 if text is None:
1354 if text is None:
1355 ui.status(_("reading DAG from stdin\n"))
1355 ui.status(_("reading DAG from stdin\n"))
1356 text = ui.fin.read()
1356 text = ui.fin.read()
1357
1357
1358 cl = repo.changelog
1358 cl = repo.changelog
1359 if len(cl) > 0:
1359 if len(cl) > 0:
1360 raise util.Abort(_('repository is not empty'))
1360 raise util.Abort(_('repository is not empty'))
1361
1361
1362 # determine number of revs in DAG
1362 # determine number of revs in DAG
1363 total = 0
1363 total = 0
1364 for type, data in dagparser.parsedag(text):
1364 for type, data in dagparser.parsedag(text):
1365 if type == 'n':
1365 if type == 'n':
1366 total += 1
1366 total += 1
1367
1367
1368 if mergeable_file:
1368 if mergeable_file:
1369 linesperrev = 2
1369 linesperrev = 2
1370 # make a file with k lines per rev
1370 # make a file with k lines per rev
1371 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1371 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1372 initialmergedlines.append("")
1372 initialmergedlines.append("")
1373
1373
1374 tags = []
1374 tags = []
1375
1375
1376 lock = tr = None
1376 lock = tr = None
1377 try:
1377 try:
1378 lock = repo.lock()
1378 lock = repo.lock()
1379 tr = repo.transaction("builddag")
1379 tr = repo.transaction("builddag")
1380
1380
1381 at = -1
1381 at = -1
1382 atbranch = 'default'
1382 atbranch = 'default'
1383 nodeids = []
1383 nodeids = []
1384 id = 0
1384 id = 0
1385 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1385 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1386 for type, data in dagparser.parsedag(text):
1386 for type, data in dagparser.parsedag(text):
1387 if type == 'n':
1387 if type == 'n':
1388 ui.note('node %s\n' % str(data))
1388 ui.note('node %s\n' % str(data))
1389 id, ps = data
1389 id, ps = data
1390
1390
1391 files = []
1391 files = []
1392 fctxs = {}
1392 fctxs = {}
1393
1393
1394 p2 = None
1394 p2 = None
1395 if mergeable_file:
1395 if mergeable_file:
1396 fn = "mf"
1396 fn = "mf"
1397 p1 = repo[ps[0]]
1397 p1 = repo[ps[0]]
1398 if len(ps) > 1:
1398 if len(ps) > 1:
1399 p2 = repo[ps[1]]
1399 p2 = repo[ps[1]]
1400 pa = p1.ancestor(p2)
1400 pa = p1.ancestor(p2)
1401 base, local, other = [x[fn].data() for x in pa, p1, p2]
1401 base, local, other = [x[fn].data() for x in pa, p1, p2]
1402 m3 = simplemerge.Merge3Text(base, local, other)
1402 m3 = simplemerge.Merge3Text(base, local, other)
1403 ml = [l.strip() for l in m3.merge_lines()]
1403 ml = [l.strip() for l in m3.merge_lines()]
1404 ml.append("")
1404 ml.append("")
1405 elif at > 0:
1405 elif at > 0:
1406 ml = p1[fn].data().split("\n")
1406 ml = p1[fn].data().split("\n")
1407 else:
1407 else:
1408 ml = initialmergedlines
1408 ml = initialmergedlines
1409 ml[id * linesperrev] += " r%i" % id
1409 ml[id * linesperrev] += " r%i" % id
1410 mergedtext = "\n".join(ml)
1410 mergedtext = "\n".join(ml)
1411 files.append(fn)
1411 files.append(fn)
1412 fctxs[fn] = context.memfilectx(fn, mergedtext)
1412 fctxs[fn] = context.memfilectx(fn, mergedtext)
1413
1413
1414 if overwritten_file:
1414 if overwritten_file:
1415 fn = "of"
1415 fn = "of"
1416 files.append(fn)
1416 files.append(fn)
1417 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1417 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1418
1418
1419 if new_file:
1419 if new_file:
1420 fn = "nf%i" % id
1420 fn = "nf%i" % id
1421 files.append(fn)
1421 files.append(fn)
1422 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1422 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1423 if len(ps) > 1:
1423 if len(ps) > 1:
1424 if not p2:
1424 if not p2:
1425 p2 = repo[ps[1]]
1425 p2 = repo[ps[1]]
1426 for fn in p2:
1426 for fn in p2:
1427 if fn.startswith("nf"):
1427 if fn.startswith("nf"):
1428 files.append(fn)
1428 files.append(fn)
1429 fctxs[fn] = p2[fn]
1429 fctxs[fn] = p2[fn]
1430
1430
1431 def fctxfn(repo, cx, path):
1431 def fctxfn(repo, cx, path):
1432 return fctxs.get(path)
1432 return fctxs.get(path)
1433
1433
1434 if len(ps) == 0 or ps[0] < 0:
1434 if len(ps) == 0 or ps[0] < 0:
1435 pars = [None, None]
1435 pars = [None, None]
1436 elif len(ps) == 1:
1436 elif len(ps) == 1:
1437 pars = [nodeids[ps[0]], None]
1437 pars = [nodeids[ps[0]], None]
1438 else:
1438 else:
1439 pars = [nodeids[p] for p in ps]
1439 pars = [nodeids[p] for p in ps]
1440 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1440 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1441 date=(id, 0),
1441 date=(id, 0),
1442 user="debugbuilddag",
1442 user="debugbuilddag",
1443 extra={'branch': atbranch})
1443 extra={'branch': atbranch})
1444 nodeid = repo.commitctx(cx)
1444 nodeid = repo.commitctx(cx)
1445 nodeids.append(nodeid)
1445 nodeids.append(nodeid)
1446 at = id
1446 at = id
1447 elif type == 'l':
1447 elif type == 'l':
1448 id, name = data
1448 id, name = data
1449 ui.note('tag %s\n' % name)
1449 ui.note('tag %s\n' % name)
1450 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1450 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1451 elif type == 'a':
1451 elif type == 'a':
1452 ui.note('branch %s\n' % data)
1452 ui.note('branch %s\n' % data)
1453 atbranch = data
1453 atbranch = data
1454 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1454 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1455 tr.close()
1455 tr.close()
1456
1456
1457 if tags:
1457 if tags:
1458 repo.opener.write("localtags", "".join(tags))
1458 repo.opener.write("localtags", "".join(tags))
1459 finally:
1459 finally:
1460 ui.progress(_('building'), None)
1460 ui.progress(_('building'), None)
1461 release(tr, lock)
1461 release(tr, lock)
1462
1462
1463 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1463 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1464 def debugbundle(ui, bundlepath, all=None, **opts):
1464 def debugbundle(ui, bundlepath, all=None, **opts):
1465 """lists the contents of a bundle"""
1465 """lists the contents of a bundle"""
1466 f = url.open(ui, bundlepath)
1466 f = url.open(ui, bundlepath)
1467 try:
1467 try:
1468 gen = changegroup.readbundle(f, bundlepath)
1468 gen = changegroup.readbundle(f, bundlepath)
1469 if all:
1469 if all:
1470 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1470 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1471
1471
1472 def showchunks(named):
1472 def showchunks(named):
1473 ui.write("\n%s\n" % named)
1473 ui.write("\n%s\n" % named)
1474 chain = None
1474 chain = None
1475 while True:
1475 while True:
1476 chunkdata = gen.deltachunk(chain)
1476 chunkdata = gen.deltachunk(chain)
1477 if not chunkdata:
1477 if not chunkdata:
1478 break
1478 break
1479 node = chunkdata['node']
1479 node = chunkdata['node']
1480 p1 = chunkdata['p1']
1480 p1 = chunkdata['p1']
1481 p2 = chunkdata['p2']
1481 p2 = chunkdata['p2']
1482 cs = chunkdata['cs']
1482 cs = chunkdata['cs']
1483 deltabase = chunkdata['deltabase']
1483 deltabase = chunkdata['deltabase']
1484 delta = chunkdata['delta']
1484 delta = chunkdata['delta']
1485 ui.write("%s %s %s %s %s %s\n" %
1485 ui.write("%s %s %s %s %s %s\n" %
1486 (hex(node), hex(p1), hex(p2),
1486 (hex(node), hex(p1), hex(p2),
1487 hex(cs), hex(deltabase), len(delta)))
1487 hex(cs), hex(deltabase), len(delta)))
1488 chain = node
1488 chain = node
1489
1489
1490 chunkdata = gen.changelogheader()
1490 chunkdata = gen.changelogheader()
1491 showchunks("changelog")
1491 showchunks("changelog")
1492 chunkdata = gen.manifestheader()
1492 chunkdata = gen.manifestheader()
1493 showchunks("manifest")
1493 showchunks("manifest")
1494 while True:
1494 while True:
1495 chunkdata = gen.filelogheader()
1495 chunkdata = gen.filelogheader()
1496 if not chunkdata:
1496 if not chunkdata:
1497 break
1497 break
1498 fname = chunkdata['filename']
1498 fname = chunkdata['filename']
1499 showchunks(fname)
1499 showchunks(fname)
1500 else:
1500 else:
1501 chunkdata = gen.changelogheader()
1501 chunkdata = gen.changelogheader()
1502 chain = None
1502 chain = None
1503 while True:
1503 while True:
1504 chunkdata = gen.deltachunk(chain)
1504 chunkdata = gen.deltachunk(chain)
1505 if not chunkdata:
1505 if not chunkdata:
1506 break
1506 break
1507 node = chunkdata['node']
1507 node = chunkdata['node']
1508 ui.write("%s\n" % hex(node))
1508 ui.write("%s\n" % hex(node))
1509 chain = node
1509 chain = node
1510 finally:
1510 finally:
1511 f.close()
1511 f.close()
1512
1512
1513 @command('debugcheckstate', [], '')
1513 @command('debugcheckstate', [], '')
1514 def debugcheckstate(ui, repo):
1514 def debugcheckstate(ui, repo):
1515 """validate the correctness of the current dirstate"""
1515 """validate the correctness of the current dirstate"""
1516 parent1, parent2 = repo.dirstate.parents()
1516 parent1, parent2 = repo.dirstate.parents()
1517 m1 = repo[parent1].manifest()
1517 m1 = repo[parent1].manifest()
1518 m2 = repo[parent2].manifest()
1518 m2 = repo[parent2].manifest()
1519 errors = 0
1519 errors = 0
1520 for f in repo.dirstate:
1520 for f in repo.dirstate:
1521 state = repo.dirstate[f]
1521 state = repo.dirstate[f]
1522 if state in "nr" and f not in m1:
1522 if state in "nr" and f not in m1:
1523 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1523 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1524 errors += 1
1524 errors += 1
1525 if state in "a" and f in m1:
1525 if state in "a" and f in m1:
1526 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1526 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1527 errors += 1
1527 errors += 1
1528 if state in "m" and f not in m1 and f not in m2:
1528 if state in "m" and f not in m1 and f not in m2:
1529 ui.warn(_("%s in state %s, but not in either manifest\n") %
1529 ui.warn(_("%s in state %s, but not in either manifest\n") %
1530 (f, state))
1530 (f, state))
1531 errors += 1
1531 errors += 1
1532 for f in m1:
1532 for f in m1:
1533 state = repo.dirstate[f]
1533 state = repo.dirstate[f]
1534 if state not in "nrm":
1534 if state not in "nrm":
1535 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1535 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1536 errors += 1
1536 errors += 1
1537 if errors:
1537 if errors:
1538 error = _(".hg/dirstate inconsistent with current parent's manifest")
1538 error = _(".hg/dirstate inconsistent with current parent's manifest")
1539 raise util.Abort(error)
1539 raise util.Abort(error)
1540
1540
1541 @command('debugcommands', [], _('[COMMAND]'))
1541 @command('debugcommands', [], _('[COMMAND]'))
1542 def debugcommands(ui, cmd='', *args):
1542 def debugcommands(ui, cmd='', *args):
1543 """list all available commands and options"""
1543 """list all available commands and options"""
1544 for cmd, vals in sorted(table.iteritems()):
1544 for cmd, vals in sorted(table.iteritems()):
1545 cmd = cmd.split('|')[0].strip('^')
1545 cmd = cmd.split('|')[0].strip('^')
1546 opts = ', '.join([i[1] for i in vals[1]])
1546 opts = ', '.join([i[1] for i in vals[1]])
1547 ui.write('%s: %s\n' % (cmd, opts))
1547 ui.write('%s: %s\n' % (cmd, opts))
1548
1548
1549 @command('debugcomplete',
1549 @command('debugcomplete',
1550 [('o', 'options', None, _('show the command options'))],
1550 [('o', 'options', None, _('show the command options'))],
1551 _('[-o] CMD'))
1551 _('[-o] CMD'))
1552 def debugcomplete(ui, cmd='', **opts):
1552 def debugcomplete(ui, cmd='', **opts):
1553 """returns the completion list associated with the given command"""
1553 """returns the completion list associated with the given command"""
1554
1554
1555 if opts.get('options'):
1555 if opts.get('options'):
1556 options = []
1556 options = []
1557 otables = [globalopts]
1557 otables = [globalopts]
1558 if cmd:
1558 if cmd:
1559 aliases, entry = cmdutil.findcmd(cmd, table, False)
1559 aliases, entry = cmdutil.findcmd(cmd, table, False)
1560 otables.append(entry[1])
1560 otables.append(entry[1])
1561 for t in otables:
1561 for t in otables:
1562 for o in t:
1562 for o in t:
1563 if "(DEPRECATED)" in o[3]:
1563 if "(DEPRECATED)" in o[3]:
1564 continue
1564 continue
1565 if o[0]:
1565 if o[0]:
1566 options.append('-%s' % o[0])
1566 options.append('-%s' % o[0])
1567 options.append('--%s' % o[1])
1567 options.append('--%s' % o[1])
1568 ui.write("%s\n" % "\n".join(options))
1568 ui.write("%s\n" % "\n".join(options))
1569 return
1569 return
1570
1570
1571 cmdlist = cmdutil.findpossible(cmd, table)
1571 cmdlist = cmdutil.findpossible(cmd, table)
1572 if ui.verbose:
1572 if ui.verbose:
1573 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1573 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1574 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1574 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1575
1575
1576 @command('debugdag',
1576 @command('debugdag',
1577 [('t', 'tags', None, _('use tags as labels')),
1577 [('t', 'tags', None, _('use tags as labels')),
1578 ('b', 'branches', None, _('annotate with branch names')),
1578 ('b', 'branches', None, _('annotate with branch names')),
1579 ('', 'dots', None, _('use dots for runs')),
1579 ('', 'dots', None, _('use dots for runs')),
1580 ('s', 'spaces', None, _('separate elements by spaces'))],
1580 ('s', 'spaces', None, _('separate elements by spaces'))],
1581 _('[OPTION]... [FILE [REV]...]'))
1581 _('[OPTION]... [FILE [REV]...]'))
1582 def debugdag(ui, repo, file_=None, *revs, **opts):
1582 def debugdag(ui, repo, file_=None, *revs, **opts):
1583 """format the changelog or an index DAG as a concise textual description
1583 """format the changelog or an index DAG as a concise textual description
1584
1584
1585 If you pass a revlog index, the revlog's DAG is emitted. If you list
1585 If you pass a revlog index, the revlog's DAG is emitted. If you list
1586 revision numbers, they get labelled in the output as rN.
1586 revision numbers, they get labelled in the output as rN.
1587
1587
1588 Otherwise, the changelog DAG of the current repo is emitted.
1588 Otherwise, the changelog DAG of the current repo is emitted.
1589 """
1589 """
1590 spaces = opts.get('spaces')
1590 spaces = opts.get('spaces')
1591 dots = opts.get('dots')
1591 dots = opts.get('dots')
1592 if file_:
1592 if file_:
1593 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1593 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1594 revs = set((int(r) for r in revs))
1594 revs = set((int(r) for r in revs))
1595 def events():
1595 def events():
1596 for r in rlog:
1596 for r in rlog:
1597 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1597 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1598 if r in revs:
1598 if r in revs:
1599 yield 'l', (r, "r%i" % r)
1599 yield 'l', (r, "r%i" % r)
1600 elif repo:
1600 elif repo:
1601 cl = repo.changelog
1601 cl = repo.changelog
1602 tags = opts.get('tags')
1602 tags = opts.get('tags')
1603 branches = opts.get('branches')
1603 branches = opts.get('branches')
1604 if tags:
1604 if tags:
1605 labels = {}
1605 labels = {}
1606 for l, n in repo.tags().items():
1606 for l, n in repo.tags().items():
1607 labels.setdefault(cl.rev(n), []).append(l)
1607 labels.setdefault(cl.rev(n), []).append(l)
1608 def events():
1608 def events():
1609 b = "default"
1609 b = "default"
1610 for r in cl:
1610 for r in cl:
1611 if branches:
1611 if branches:
1612 newb = cl.read(cl.node(r))[5]['branch']
1612 newb = cl.read(cl.node(r))[5]['branch']
1613 if newb != b:
1613 if newb != b:
1614 yield 'a', newb
1614 yield 'a', newb
1615 b = newb
1615 b = newb
1616 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1616 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1617 if tags:
1617 if tags:
1618 ls = labels.get(r)
1618 ls = labels.get(r)
1619 if ls:
1619 if ls:
1620 for l in ls:
1620 for l in ls:
1621 yield 'l', (r, l)
1621 yield 'l', (r, l)
1622 else:
1622 else:
1623 raise util.Abort(_('need repo for changelog dag'))
1623 raise util.Abort(_('need repo for changelog dag'))
1624
1624
1625 for line in dagparser.dagtextlines(events(),
1625 for line in dagparser.dagtextlines(events(),
1626 addspaces=spaces,
1626 addspaces=spaces,
1627 wraplabels=True,
1627 wraplabels=True,
1628 wrapannotations=True,
1628 wrapannotations=True,
1629 wrapnonlinear=dots,
1629 wrapnonlinear=dots,
1630 usedots=dots,
1630 usedots=dots,
1631 maxlinewidth=70):
1631 maxlinewidth=70):
1632 ui.write(line)
1632 ui.write(line)
1633 ui.write("\n")
1633 ui.write("\n")
1634
1634
1635 @command('debugdata',
1635 @command('debugdata',
1636 [('c', 'changelog', False, _('open changelog')),
1636 [('c', 'changelog', False, _('open changelog')),
1637 ('m', 'manifest', False, _('open manifest'))],
1637 ('m', 'manifest', False, _('open manifest'))],
1638 _('-c|-m|FILE REV'))
1638 _('-c|-m|FILE REV'))
1639 def debugdata(ui, repo, file_, rev = None, **opts):
1639 def debugdata(ui, repo, file_, rev = None, **opts):
1640 """dump the contents of a data file revision"""
1640 """dump the contents of a data file revision"""
1641 if opts.get('changelog') or opts.get('manifest'):
1641 if opts.get('changelog') or opts.get('manifest'):
1642 file_, rev = None, file_
1642 file_, rev = None, file_
1643 elif rev is None:
1643 elif rev is None:
1644 raise error.CommandError('debugdata', _('invalid arguments'))
1644 raise error.CommandError('debugdata', _('invalid arguments'))
1645 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1645 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1646 try:
1646 try:
1647 ui.write(r.revision(r.lookup(rev)))
1647 ui.write(r.revision(r.lookup(rev)))
1648 except KeyError:
1648 except KeyError:
1649 raise util.Abort(_('invalid revision identifier %s') % rev)
1649 raise util.Abort(_('invalid revision identifier %s') % rev)
1650
1650
1651 @command('debugdate',
1651 @command('debugdate',
1652 [('e', 'extended', None, _('try extended date formats'))],
1652 [('e', 'extended', None, _('try extended date formats'))],
1653 _('[-e] DATE [RANGE]'))
1653 _('[-e] DATE [RANGE]'))
1654 def debugdate(ui, date, range=None, **opts):
1654 def debugdate(ui, date, range=None, **opts):
1655 """parse and display a date"""
1655 """parse and display a date"""
1656 if opts["extended"]:
1656 if opts["extended"]:
1657 d = util.parsedate(date, util.extendeddateformats)
1657 d = util.parsedate(date, util.extendeddateformats)
1658 else:
1658 else:
1659 d = util.parsedate(date)
1659 d = util.parsedate(date)
1660 ui.write("internal: %s %s\n" % d)
1660 ui.write("internal: %s %s\n" % d)
1661 ui.write("standard: %s\n" % util.datestr(d))
1661 ui.write("standard: %s\n" % util.datestr(d))
1662 if range:
1662 if range:
1663 m = util.matchdate(range)
1663 m = util.matchdate(range)
1664 ui.write("match: %s\n" % m(d[0]))
1664 ui.write("match: %s\n" % m(d[0]))
1665
1665
1666 @command('debugdiscovery',
1666 @command('debugdiscovery',
1667 [('', 'old', None, _('use old-style discovery')),
1667 [('', 'old', None, _('use old-style discovery')),
1668 ('', 'nonheads', None,
1668 ('', 'nonheads', None,
1669 _('use old-style discovery with non-heads included')),
1669 _('use old-style discovery with non-heads included')),
1670 ] + remoteopts,
1670 ] + remoteopts,
1671 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1671 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1672 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1672 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1673 """runs the changeset discovery protocol in isolation"""
1673 """runs the changeset discovery protocol in isolation"""
1674 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1674 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1675 remote = hg.peer(repo, opts, remoteurl)
1675 remote = hg.peer(repo, opts, remoteurl)
1676 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1676 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1677
1677
1678 # make sure tests are repeatable
1678 # make sure tests are repeatable
1679 random.seed(12323)
1679 random.seed(12323)
1680
1680
1681 def doit(localheads, remoteheads):
1681 def doit(localheads, remoteheads):
1682 if opts.get('old'):
1682 if opts.get('old'):
1683 if localheads:
1683 if localheads:
1684 raise util.Abort('cannot use localheads with old style discovery')
1684 raise util.Abort('cannot use localheads with old style discovery')
1685 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1685 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1686 force=True)
1686 force=True)
1687 common = set(common)
1687 common = set(common)
1688 if not opts.get('nonheads'):
1688 if not opts.get('nonheads'):
1689 ui.write("unpruned common: %s\n" % " ".join([short(n)
1689 ui.write("unpruned common: %s\n" % " ".join([short(n)
1690 for n in common]))
1690 for n in common]))
1691 dag = dagutil.revlogdag(repo.changelog)
1691 dag = dagutil.revlogdag(repo.changelog)
1692 all = dag.ancestorset(dag.internalizeall(common))
1692 all = dag.ancestorset(dag.internalizeall(common))
1693 common = dag.externalizeall(dag.headsetofconnecteds(all))
1693 common = dag.externalizeall(dag.headsetofconnecteds(all))
1694 else:
1694 else:
1695 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1695 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1696 common = set(common)
1696 common = set(common)
1697 rheads = set(hds)
1697 rheads = set(hds)
1698 lheads = set(repo.heads())
1698 lheads = set(repo.heads())
1699 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1699 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1700 if lheads <= common:
1700 if lheads <= common:
1701 ui.write("local is subset\n")
1701 ui.write("local is subset\n")
1702 elif rheads <= common:
1702 elif rheads <= common:
1703 ui.write("remote is subset\n")
1703 ui.write("remote is subset\n")
1704
1704
1705 serverlogs = opts.get('serverlog')
1705 serverlogs = opts.get('serverlog')
1706 if serverlogs:
1706 if serverlogs:
1707 for filename in serverlogs:
1707 for filename in serverlogs:
1708 logfile = open(filename, 'r')
1708 logfile = open(filename, 'r')
1709 try:
1709 try:
1710 line = logfile.readline()
1710 line = logfile.readline()
1711 while line:
1711 while line:
1712 parts = line.strip().split(';')
1712 parts = line.strip().split(';')
1713 op = parts[1]
1713 op = parts[1]
1714 if op == 'cg':
1714 if op == 'cg':
1715 pass
1715 pass
1716 elif op == 'cgss':
1716 elif op == 'cgss':
1717 doit(parts[2].split(' '), parts[3].split(' '))
1717 doit(parts[2].split(' '), parts[3].split(' '))
1718 elif op == 'unb':
1718 elif op == 'unb':
1719 doit(parts[3].split(' '), parts[2].split(' '))
1719 doit(parts[3].split(' '), parts[2].split(' '))
1720 line = logfile.readline()
1720 line = logfile.readline()
1721 finally:
1721 finally:
1722 logfile.close()
1722 logfile.close()
1723
1723
1724 else:
1724 else:
1725 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1725 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1726 opts.get('remote_head'))
1726 opts.get('remote_head'))
1727 localrevs = opts.get('local_head')
1727 localrevs = opts.get('local_head')
1728 doit(localrevs, remoterevs)
1728 doit(localrevs, remoterevs)
1729
1729
1730 @command('debugfileset', [], ('REVSPEC'))
1730 @command('debugfileset', [], ('REVSPEC'))
1731 def debugfileset(ui, repo, expr):
1731 def debugfileset(ui, repo, expr):
1732 '''parse and apply a fileset specification'''
1732 '''parse and apply a fileset specification'''
1733 if ui.verbose:
1733 if ui.verbose:
1734 tree = fileset.parse(expr)[0]
1734 tree = fileset.parse(expr)[0]
1735 ui.note(tree, "\n")
1735 ui.note(tree, "\n")
1736
1736
1737 for f in fileset.getfileset(repo[None], expr):
1737 for f in fileset.getfileset(repo[None], expr):
1738 ui.write("%s\n" % f)
1738 ui.write("%s\n" % f)
1739
1739
1740 @command('debugfsinfo', [], _('[PATH]'))
1740 @command('debugfsinfo', [], _('[PATH]'))
1741 def debugfsinfo(ui, path = "."):
1741 def debugfsinfo(ui, path = "."):
1742 """show information detected about current filesystem"""
1742 """show information detected about current filesystem"""
1743 util.writefile('.debugfsinfo', '')
1743 util.writefile('.debugfsinfo', '')
1744 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1744 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1745 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1745 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1746 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1746 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1747 and 'yes' or 'no'))
1747 and 'yes' or 'no'))
1748 os.unlink('.debugfsinfo')
1748 os.unlink('.debugfsinfo')
1749
1749
1750 @command('debuggetbundle',
1750 @command('debuggetbundle',
1751 [('H', 'head', [], _('id of head node'), _('ID')),
1751 [('H', 'head', [], _('id of head node'), _('ID')),
1752 ('C', 'common', [], _('id of common node'), _('ID')),
1752 ('C', 'common', [], _('id of common node'), _('ID')),
1753 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1753 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1754 _('REPO FILE [-H|-C ID]...'))
1754 _('REPO FILE [-H|-C ID]...'))
1755 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1755 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1756 """retrieves a bundle from a repo
1756 """retrieves a bundle from a repo
1757
1757
1758 Every ID must be a full-length hex node id string. Saves the bundle to the
1758 Every ID must be a full-length hex node id string. Saves the bundle to the
1759 given file.
1759 given file.
1760 """
1760 """
1761 repo = hg.peer(ui, opts, repopath)
1761 repo = hg.peer(ui, opts, repopath)
1762 if not repo.capable('getbundle'):
1762 if not repo.capable('getbundle'):
1763 raise util.Abort("getbundle() not supported by target repository")
1763 raise util.Abort("getbundle() not supported by target repository")
1764 args = {}
1764 args = {}
1765 if common:
1765 if common:
1766 args['common'] = [bin(s) for s in common]
1766 args['common'] = [bin(s) for s in common]
1767 if head:
1767 if head:
1768 args['heads'] = [bin(s) for s in head]
1768 args['heads'] = [bin(s) for s in head]
1769 bundle = repo.getbundle('debug', **args)
1769 bundle = repo.getbundle('debug', **args)
1770
1770
1771 bundletype = opts.get('type', 'bzip2').lower()
1771 bundletype = opts.get('type', 'bzip2').lower()
1772 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1772 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1773 bundletype = btypes.get(bundletype)
1773 bundletype = btypes.get(bundletype)
1774 if bundletype not in changegroup.bundletypes:
1774 if bundletype not in changegroup.bundletypes:
1775 raise util.Abort(_('unknown bundle type specified with --type'))
1775 raise util.Abort(_('unknown bundle type specified with --type'))
1776 changegroup.writebundle(bundle, bundlepath, bundletype)
1776 changegroup.writebundle(bundle, bundlepath, bundletype)
1777
1777
1778 @command('debugignore', [], '')
1778 @command('debugignore', [], '')
1779 def debugignore(ui, repo, *values, **opts):
1779 def debugignore(ui, repo, *values, **opts):
1780 """display the combined ignore pattern"""
1780 """display the combined ignore pattern"""
1781 ignore = repo.dirstate._ignore
1781 ignore = repo.dirstate._ignore
1782 includepat = getattr(ignore, 'includepat', None)
1782 includepat = getattr(ignore, 'includepat', None)
1783 if includepat is not None:
1783 if includepat is not None:
1784 ui.write("%s\n" % includepat)
1784 ui.write("%s\n" % includepat)
1785 else:
1785 else:
1786 raise util.Abort(_("no ignore patterns found"))
1786 raise util.Abort(_("no ignore patterns found"))
1787
1787
1788 @command('debugindex',
1788 @command('debugindex',
1789 [('c', 'changelog', False, _('open changelog')),
1789 [('c', 'changelog', False, _('open changelog')),
1790 ('m', 'manifest', False, _('open manifest')),
1790 ('m', 'manifest', False, _('open manifest')),
1791 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1791 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1792 _('[-f FORMAT] -c|-m|FILE'))
1792 _('[-f FORMAT] -c|-m|FILE'))
1793 def debugindex(ui, repo, file_ = None, **opts):
1793 def debugindex(ui, repo, file_ = None, **opts):
1794 """dump the contents of an index file"""
1794 """dump the contents of an index file"""
1795 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1795 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1796 format = opts.get('format', 0)
1796 format = opts.get('format', 0)
1797 if format not in (0, 1):
1797 if format not in (0, 1):
1798 raise util.Abort(_("unknown format %d") % format)
1798 raise util.Abort(_("unknown format %d") % format)
1799
1799
1800 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1800 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1801 if generaldelta:
1801 if generaldelta:
1802 basehdr = ' delta'
1802 basehdr = ' delta'
1803 else:
1803 else:
1804 basehdr = ' base'
1804 basehdr = ' base'
1805
1805
1806 if format == 0:
1806 if format == 0:
1807 ui.write(" rev offset length " + basehdr + " linkrev"
1807 ui.write(" rev offset length " + basehdr + " linkrev"
1808 " nodeid p1 p2\n")
1808 " nodeid p1 p2\n")
1809 elif format == 1:
1809 elif format == 1:
1810 ui.write(" rev flag offset length"
1810 ui.write(" rev flag offset length"
1811 " size " + basehdr + " link p1 p2 nodeid\n")
1811 " size " + basehdr + " link p1 p2 nodeid\n")
1812
1812
1813 for i in r:
1813 for i in r:
1814 node = r.node(i)
1814 node = r.node(i)
1815 if generaldelta:
1815 if generaldelta:
1816 base = r.deltaparent(i)
1816 base = r.deltaparent(i)
1817 else:
1817 else:
1818 base = r.chainbase(i)
1818 base = r.chainbase(i)
1819 if format == 0:
1819 if format == 0:
1820 try:
1820 try:
1821 pp = r.parents(node)
1821 pp = r.parents(node)
1822 except:
1822 except:
1823 pp = [nullid, nullid]
1823 pp = [nullid, nullid]
1824 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1824 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1825 i, r.start(i), r.length(i), base, r.linkrev(i),
1825 i, r.start(i), r.length(i), base, r.linkrev(i),
1826 short(node), short(pp[0]), short(pp[1])))
1826 short(node), short(pp[0]), short(pp[1])))
1827 elif format == 1:
1827 elif format == 1:
1828 pr = r.parentrevs(i)
1828 pr = r.parentrevs(i)
1829 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1829 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1830 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1830 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1831 base, r.linkrev(i), pr[0], pr[1], short(node)))
1831 base, r.linkrev(i), pr[0], pr[1], short(node)))
1832
1832
1833 @command('debugindexdot', [], _('FILE'))
1833 @command('debugindexdot', [], _('FILE'))
1834 def debugindexdot(ui, repo, file_):
1834 def debugindexdot(ui, repo, file_):
1835 """dump an index DAG as a graphviz dot file"""
1835 """dump an index DAG as a graphviz dot file"""
1836 r = None
1836 r = None
1837 if repo:
1837 if repo:
1838 filelog = repo.file(file_)
1838 filelog = repo.file(file_)
1839 if len(filelog):
1839 if len(filelog):
1840 r = filelog
1840 r = filelog
1841 if not r:
1841 if not r:
1842 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1842 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1843 ui.write("digraph G {\n")
1843 ui.write("digraph G {\n")
1844 for i in r:
1844 for i in r:
1845 node = r.node(i)
1845 node = r.node(i)
1846 pp = r.parents(node)
1846 pp = r.parents(node)
1847 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1847 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1848 if pp[1] != nullid:
1848 if pp[1] != nullid:
1849 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1849 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1850 ui.write("}\n")
1850 ui.write("}\n")
1851
1851
1852 @command('debuginstall', [], '')
1852 @command('debuginstall', [], '')
1853 def debuginstall(ui):
1853 def debuginstall(ui):
1854 '''test Mercurial installation
1854 '''test Mercurial installation
1855
1855
1856 Returns 0 on success.
1856 Returns 0 on success.
1857 '''
1857 '''
1858
1858
1859 def writetemp(contents):
1859 def writetemp(contents):
1860 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1860 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1861 f = os.fdopen(fd, "wb")
1861 f = os.fdopen(fd, "wb")
1862 f.write(contents)
1862 f.write(contents)
1863 f.close()
1863 f.close()
1864 return name
1864 return name
1865
1865
1866 problems = 0
1866 problems = 0
1867
1867
1868 # encoding
1868 # encoding
1869 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1869 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1870 try:
1870 try:
1871 encoding.fromlocal("test")
1871 encoding.fromlocal("test")
1872 except util.Abort, inst:
1872 except util.Abort, inst:
1873 ui.write(" %s\n" % inst)
1873 ui.write(" %s\n" % inst)
1874 ui.write(_(" (check that your locale is properly set)\n"))
1874 ui.write(_(" (check that your locale is properly set)\n"))
1875 problems += 1
1875 problems += 1
1876
1876
1877 # compiled modules
1877 # compiled modules
1878 ui.status(_("Checking installed modules (%s)...\n")
1878 ui.status(_("Checking installed modules (%s)...\n")
1879 % os.path.dirname(__file__))
1879 % os.path.dirname(__file__))
1880 try:
1880 try:
1881 import bdiff, mpatch, base85, osutil
1881 import bdiff, mpatch, base85, osutil
1882 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
1882 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
1883 except Exception, inst:
1883 except Exception, inst:
1884 ui.write(" %s\n" % inst)
1884 ui.write(" %s\n" % inst)
1885 ui.write(_(" One or more extensions could not be found"))
1885 ui.write(_(" One or more extensions could not be found"))
1886 ui.write(_(" (check that you compiled the extensions)\n"))
1886 ui.write(_(" (check that you compiled the extensions)\n"))
1887 problems += 1
1887 problems += 1
1888
1888
1889 # templates
1889 # templates
1890 import templater
1890 import templater
1891 p = templater.templatepath()
1891 p = templater.templatepath()
1892 ui.status(_("Checking templates (%s)...\n") % ' '.join(p))
1892 ui.status(_("Checking templates (%s)...\n") % ' '.join(p))
1893 try:
1893 try:
1894 templater.templater(templater.templatepath("map-cmdline.default"))
1894 templater.templater(templater.templatepath("map-cmdline.default"))
1895 except Exception, inst:
1895 except Exception, inst:
1896 ui.write(" %s\n" % inst)
1896 ui.write(" %s\n" % inst)
1897 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1897 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1898 problems += 1
1898 problems += 1
1899
1899
1900 # editor
1900 # editor
1901 ui.status(_("Checking commit editor...\n"))
1901 ui.status(_("Checking commit editor...\n"))
1902 editor = ui.geteditor()
1902 editor = ui.geteditor()
1903 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1903 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1904 if not cmdpath:
1904 if not cmdpath:
1905 if editor == 'vi':
1905 if editor == 'vi':
1906 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1906 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1907 ui.write(_(" (specify a commit editor in your configuration"
1907 ui.write(_(" (specify a commit editor in your configuration"
1908 " file)\n"))
1908 " file)\n"))
1909 else:
1909 else:
1910 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1910 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1911 ui.write(_(" (specify a commit editor in your configuration"
1911 ui.write(_(" (specify a commit editor in your configuration"
1912 " file)\n"))
1912 " file)\n"))
1913 problems += 1
1913 problems += 1
1914
1914
1915 # check username
1915 # check username
1916 ui.status(_("Checking username...\n"))
1916 ui.status(_("Checking username...\n"))
1917 try:
1917 try:
1918 ui.username()
1918 ui.username()
1919 except util.Abort, e:
1919 except util.Abort, e:
1920 ui.write(" %s\n" % e)
1920 ui.write(" %s\n" % e)
1921 ui.write(_(" (specify a username in your configuration file)\n"))
1921 ui.write(_(" (specify a username in your configuration file)\n"))
1922 problems += 1
1922 problems += 1
1923
1923
1924 if not problems:
1924 if not problems:
1925 ui.status(_("No problems detected\n"))
1925 ui.status(_("No problems detected\n"))
1926 else:
1926 else:
1927 ui.write(_("%s problems detected,"
1927 ui.write(_("%s problems detected,"
1928 " please check your install!\n") % problems)
1928 " please check your install!\n") % problems)
1929
1929
1930 return problems
1930 return problems
1931
1931
1932 @command('debugknown', [], _('REPO ID...'))
1932 @command('debugknown', [], _('REPO ID...'))
1933 def debugknown(ui, repopath, *ids, **opts):
1933 def debugknown(ui, repopath, *ids, **opts):
1934 """test whether node ids are known to a repo
1934 """test whether node ids are known to a repo
1935
1935
1936 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1936 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1937 indicating unknown/known.
1937 indicating unknown/known.
1938 """
1938 """
1939 repo = hg.peer(ui, opts, repopath)
1939 repo = hg.peer(ui, opts, repopath)
1940 if not repo.capable('known'):
1940 if not repo.capable('known'):
1941 raise util.Abort("known() not supported by target repository")
1941 raise util.Abort("known() not supported by target repository")
1942 flags = repo.known([bin(s) for s in ids])
1942 flags = repo.known([bin(s) for s in ids])
1943 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1943 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1944
1944
1945 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1945 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1946 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1946 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1947 '''access the pushkey key/value protocol
1947 '''access the pushkey key/value protocol
1948
1948
1949 With two args, list the keys in the given namespace.
1949 With two args, list the keys in the given namespace.
1950
1950
1951 With five args, set a key to new if it currently is set to old.
1951 With five args, set a key to new if it currently is set to old.
1952 Reports success or failure.
1952 Reports success or failure.
1953 '''
1953 '''
1954
1954
1955 target = hg.peer(ui, {}, repopath)
1955 target = hg.peer(ui, {}, repopath)
1956 if keyinfo:
1956 if keyinfo:
1957 key, old, new = keyinfo
1957 key, old, new = keyinfo
1958 r = target.pushkey(namespace, key, old, new)
1958 r = target.pushkey(namespace, key, old, new)
1959 ui.status(str(r) + '\n')
1959 ui.status(str(r) + '\n')
1960 return not r
1960 return not r
1961 else:
1961 else:
1962 for k, v in target.listkeys(namespace).iteritems():
1962 for k, v in target.listkeys(namespace).iteritems():
1963 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1963 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1964 v.encode('string-escape')))
1964 v.encode('string-escape')))
1965
1965
1966 @command('debugpvec', [], _('A B'))
1966 @command('debugpvec', [], _('A B'))
1967 def debugpvec(ui, repo, a, b=None):
1967 def debugpvec(ui, repo, a, b=None):
1968 ca = scmutil.revsingle(repo, a)
1968 ca = scmutil.revsingle(repo, a)
1969 cb = scmutil.revsingle(repo, b)
1969 cb = scmutil.revsingle(repo, b)
1970 pa = pvec.ctxpvec(ca)
1970 pa = pvec.ctxpvec(ca)
1971 pb = pvec.ctxpvec(cb)
1971 pb = pvec.ctxpvec(cb)
1972 if pa == pb:
1972 if pa == pb:
1973 rel = "="
1973 rel = "="
1974 elif pa > pb:
1974 elif pa > pb:
1975 rel = ">"
1975 rel = ">"
1976 elif pa < pb:
1976 elif pa < pb:
1977 rel = "<"
1977 rel = "<"
1978 elif pa | pb:
1978 elif pa | pb:
1979 rel = "|"
1979 rel = "|"
1980 ui.write(_("a: %s\n") % pa)
1980 ui.write(_("a: %s\n") % pa)
1981 ui.write(_("b: %s\n") % pb)
1981 ui.write(_("b: %s\n") % pb)
1982 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
1982 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
1983 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
1983 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
1984 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
1984 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
1985 pa.distance(pb), rel))
1985 pa.distance(pb), rel))
1986
1986
1987 @command('debugrebuildstate',
1987 @command('debugrebuildstate',
1988 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1988 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1989 _('[-r REV] [REV]'))
1989 _('[-r REV] [REV]'))
1990 def debugrebuildstate(ui, repo, rev="tip"):
1990 def debugrebuildstate(ui, repo, rev="tip"):
1991 """rebuild the dirstate as it would look like for the given revision"""
1991 """rebuild the dirstate as it would look like for the given revision"""
1992 ctx = scmutil.revsingle(repo, rev)
1992 ctx = scmutil.revsingle(repo, rev)
1993 wlock = repo.wlock()
1993 wlock = repo.wlock()
1994 try:
1994 try:
1995 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1995 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1996 finally:
1996 finally:
1997 wlock.release()
1997 wlock.release()
1998
1998
1999 @command('debugrename',
1999 @command('debugrename',
2000 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2000 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2001 _('[-r REV] FILE'))
2001 _('[-r REV] FILE'))
2002 def debugrename(ui, repo, file1, *pats, **opts):
2002 def debugrename(ui, repo, file1, *pats, **opts):
2003 """dump rename information"""
2003 """dump rename information"""
2004
2004
2005 ctx = scmutil.revsingle(repo, opts.get('rev'))
2005 ctx = scmutil.revsingle(repo, opts.get('rev'))
2006 m = scmutil.match(ctx, (file1,) + pats, opts)
2006 m = scmutil.match(ctx, (file1,) + pats, opts)
2007 for abs in ctx.walk(m):
2007 for abs in ctx.walk(m):
2008 fctx = ctx[abs]
2008 fctx = ctx[abs]
2009 o = fctx.filelog().renamed(fctx.filenode())
2009 o = fctx.filelog().renamed(fctx.filenode())
2010 rel = m.rel(abs)
2010 rel = m.rel(abs)
2011 if o:
2011 if o:
2012 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2012 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2013 else:
2013 else:
2014 ui.write(_("%s not renamed\n") % rel)
2014 ui.write(_("%s not renamed\n") % rel)
2015
2015
2016 @command('debugrevlog',
2016 @command('debugrevlog',
2017 [('c', 'changelog', False, _('open changelog')),
2017 [('c', 'changelog', False, _('open changelog')),
2018 ('m', 'manifest', False, _('open manifest')),
2018 ('m', 'manifest', False, _('open manifest')),
2019 ('d', 'dump', False, _('dump index data'))],
2019 ('d', 'dump', False, _('dump index data'))],
2020 _('-c|-m|FILE'))
2020 _('-c|-m|FILE'))
2021 def debugrevlog(ui, repo, file_ = None, **opts):
2021 def debugrevlog(ui, repo, file_ = None, **opts):
2022 """show data and statistics about a revlog"""
2022 """show data and statistics about a revlog"""
2023 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2023 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2024
2024
2025 if opts.get("dump"):
2025 if opts.get("dump"):
2026 numrevs = len(r)
2026 numrevs = len(r)
2027 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2027 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2028 " rawsize totalsize compression heads\n")
2028 " rawsize totalsize compression heads\n")
2029 ts = 0
2029 ts = 0
2030 heads = set()
2030 heads = set()
2031 for rev in xrange(numrevs):
2031 for rev in xrange(numrevs):
2032 dbase = r.deltaparent(rev)
2032 dbase = r.deltaparent(rev)
2033 if dbase == -1:
2033 if dbase == -1:
2034 dbase = rev
2034 dbase = rev
2035 cbase = r.chainbase(rev)
2035 cbase = r.chainbase(rev)
2036 p1, p2 = r.parentrevs(rev)
2036 p1, p2 = r.parentrevs(rev)
2037 rs = r.rawsize(rev)
2037 rs = r.rawsize(rev)
2038 ts = ts + rs
2038 ts = ts + rs
2039 heads -= set(r.parentrevs(rev))
2039 heads -= set(r.parentrevs(rev))
2040 heads.add(rev)
2040 heads.add(rev)
2041 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2041 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2042 (rev, p1, p2, r.start(rev), r.end(rev),
2042 (rev, p1, p2, r.start(rev), r.end(rev),
2043 r.start(dbase), r.start(cbase),
2043 r.start(dbase), r.start(cbase),
2044 r.start(p1), r.start(p2),
2044 r.start(p1), r.start(p2),
2045 rs, ts, ts / r.end(rev), len(heads)))
2045 rs, ts, ts / r.end(rev), len(heads)))
2046 return 0
2046 return 0
2047
2047
2048 v = r.version
2048 v = r.version
2049 format = v & 0xFFFF
2049 format = v & 0xFFFF
2050 flags = []
2050 flags = []
2051 gdelta = False
2051 gdelta = False
2052 if v & revlog.REVLOGNGINLINEDATA:
2052 if v & revlog.REVLOGNGINLINEDATA:
2053 flags.append('inline')
2053 flags.append('inline')
2054 if v & revlog.REVLOGGENERALDELTA:
2054 if v & revlog.REVLOGGENERALDELTA:
2055 gdelta = True
2055 gdelta = True
2056 flags.append('generaldelta')
2056 flags.append('generaldelta')
2057 if not flags:
2057 if not flags:
2058 flags = ['(none)']
2058 flags = ['(none)']
2059
2059
2060 nummerges = 0
2060 nummerges = 0
2061 numfull = 0
2061 numfull = 0
2062 numprev = 0
2062 numprev = 0
2063 nump1 = 0
2063 nump1 = 0
2064 nump2 = 0
2064 nump2 = 0
2065 numother = 0
2065 numother = 0
2066 nump1prev = 0
2066 nump1prev = 0
2067 nump2prev = 0
2067 nump2prev = 0
2068 chainlengths = []
2068 chainlengths = []
2069
2069
2070 datasize = [None, 0, 0L]
2070 datasize = [None, 0, 0L]
2071 fullsize = [None, 0, 0L]
2071 fullsize = [None, 0, 0L]
2072 deltasize = [None, 0, 0L]
2072 deltasize = [None, 0, 0L]
2073
2073
2074 def addsize(size, l):
2074 def addsize(size, l):
2075 if l[0] is None or size < l[0]:
2075 if l[0] is None or size < l[0]:
2076 l[0] = size
2076 l[0] = size
2077 if size > l[1]:
2077 if size > l[1]:
2078 l[1] = size
2078 l[1] = size
2079 l[2] += size
2079 l[2] += size
2080
2080
2081 numrevs = len(r)
2081 numrevs = len(r)
2082 for rev in xrange(numrevs):
2082 for rev in xrange(numrevs):
2083 p1, p2 = r.parentrevs(rev)
2083 p1, p2 = r.parentrevs(rev)
2084 delta = r.deltaparent(rev)
2084 delta = r.deltaparent(rev)
2085 if format > 0:
2085 if format > 0:
2086 addsize(r.rawsize(rev), datasize)
2086 addsize(r.rawsize(rev), datasize)
2087 if p2 != nullrev:
2087 if p2 != nullrev:
2088 nummerges += 1
2088 nummerges += 1
2089 size = r.length(rev)
2089 size = r.length(rev)
2090 if delta == nullrev:
2090 if delta == nullrev:
2091 chainlengths.append(0)
2091 chainlengths.append(0)
2092 numfull += 1
2092 numfull += 1
2093 addsize(size, fullsize)
2093 addsize(size, fullsize)
2094 else:
2094 else:
2095 chainlengths.append(chainlengths[delta] + 1)
2095 chainlengths.append(chainlengths[delta] + 1)
2096 addsize(size, deltasize)
2096 addsize(size, deltasize)
2097 if delta == rev - 1:
2097 if delta == rev - 1:
2098 numprev += 1
2098 numprev += 1
2099 if delta == p1:
2099 if delta == p1:
2100 nump1prev += 1
2100 nump1prev += 1
2101 elif delta == p2:
2101 elif delta == p2:
2102 nump2prev += 1
2102 nump2prev += 1
2103 elif delta == p1:
2103 elif delta == p1:
2104 nump1 += 1
2104 nump1 += 1
2105 elif delta == p2:
2105 elif delta == p2:
2106 nump2 += 1
2106 nump2 += 1
2107 elif delta != nullrev:
2107 elif delta != nullrev:
2108 numother += 1
2108 numother += 1
2109
2109
2110 numdeltas = numrevs - numfull
2110 numdeltas = numrevs - numfull
2111 numoprev = numprev - nump1prev - nump2prev
2111 numoprev = numprev - nump1prev - nump2prev
2112 totalrawsize = datasize[2]
2112 totalrawsize = datasize[2]
2113 datasize[2] /= numrevs
2113 datasize[2] /= numrevs
2114 fulltotal = fullsize[2]
2114 fulltotal = fullsize[2]
2115 fullsize[2] /= numfull
2115 fullsize[2] /= numfull
2116 deltatotal = deltasize[2]
2116 deltatotal = deltasize[2]
2117 deltasize[2] /= numrevs - numfull
2117 deltasize[2] /= numrevs - numfull
2118 totalsize = fulltotal + deltatotal
2118 totalsize = fulltotal + deltatotal
2119 avgchainlen = sum(chainlengths) / numrevs
2119 avgchainlen = sum(chainlengths) / numrevs
2120 compratio = totalrawsize / totalsize
2120 compratio = totalrawsize / totalsize
2121
2121
2122 basedfmtstr = '%%%dd\n'
2122 basedfmtstr = '%%%dd\n'
2123 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2123 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2124
2124
2125 def dfmtstr(max):
2125 def dfmtstr(max):
2126 return basedfmtstr % len(str(max))
2126 return basedfmtstr % len(str(max))
2127 def pcfmtstr(max, padding=0):
2127 def pcfmtstr(max, padding=0):
2128 return basepcfmtstr % (len(str(max)), ' ' * padding)
2128 return basepcfmtstr % (len(str(max)), ' ' * padding)
2129
2129
2130 def pcfmt(value, total):
2130 def pcfmt(value, total):
2131 return (value, 100 * float(value) / total)
2131 return (value, 100 * float(value) / total)
2132
2132
2133 ui.write('format : %d\n' % format)
2133 ui.write('format : %d\n' % format)
2134 ui.write('flags : %s\n' % ', '.join(flags))
2134 ui.write('flags : %s\n' % ', '.join(flags))
2135
2135
2136 ui.write('\n')
2136 ui.write('\n')
2137 fmt = pcfmtstr(totalsize)
2137 fmt = pcfmtstr(totalsize)
2138 fmt2 = dfmtstr(totalsize)
2138 fmt2 = dfmtstr(totalsize)
2139 ui.write('revisions : ' + fmt2 % numrevs)
2139 ui.write('revisions : ' + fmt2 % numrevs)
2140 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
2140 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
2141 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
2141 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
2142 ui.write('revisions : ' + fmt2 % numrevs)
2142 ui.write('revisions : ' + fmt2 % numrevs)
2143 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
2143 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
2144 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2144 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2145 ui.write('revision size : ' + fmt2 % totalsize)
2145 ui.write('revision size : ' + fmt2 % totalsize)
2146 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
2146 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
2147 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
2147 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
2148
2148
2149 ui.write('\n')
2149 ui.write('\n')
2150 fmt = dfmtstr(max(avgchainlen, compratio))
2150 fmt = dfmtstr(max(avgchainlen, compratio))
2151 ui.write('avg chain length : ' + fmt % avgchainlen)
2151 ui.write('avg chain length : ' + fmt % avgchainlen)
2152 ui.write('compression ratio : ' + fmt % compratio)
2152 ui.write('compression ratio : ' + fmt % compratio)
2153
2153
2154 if format > 0:
2154 if format > 0:
2155 ui.write('\n')
2155 ui.write('\n')
2156 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2156 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2157 % tuple(datasize))
2157 % tuple(datasize))
2158 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2158 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2159 % tuple(fullsize))
2159 % tuple(fullsize))
2160 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2160 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2161 % tuple(deltasize))
2161 % tuple(deltasize))
2162
2162
2163 if numdeltas > 0:
2163 if numdeltas > 0:
2164 ui.write('\n')
2164 ui.write('\n')
2165 fmt = pcfmtstr(numdeltas)
2165 fmt = pcfmtstr(numdeltas)
2166 fmt2 = pcfmtstr(numdeltas, 4)
2166 fmt2 = pcfmtstr(numdeltas, 4)
2167 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2167 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2168 if numprev > 0:
2168 if numprev > 0:
2169 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2169 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2170 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2170 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2171 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2171 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2172 if gdelta:
2172 if gdelta:
2173 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2173 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2174 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2174 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2175 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2175 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2176
2176
2177 @command('debugrevspec', [], ('REVSPEC'))
2177 @command('debugrevspec', [], ('REVSPEC'))
2178 def debugrevspec(ui, repo, expr):
2178 def debugrevspec(ui, repo, expr):
2179 """parse and apply a revision specification
2179 """parse and apply a revision specification
2180
2180
2181 Use --verbose to print the parsed tree before and after aliases
2181 Use --verbose to print the parsed tree before and after aliases
2182 expansion.
2182 expansion.
2183 """
2183 """
2184 if ui.verbose:
2184 if ui.verbose:
2185 tree = revset.parse(expr)[0]
2185 tree = revset.parse(expr)[0]
2186 ui.note(revset.prettyformat(tree), "\n")
2186 ui.note(revset.prettyformat(tree), "\n")
2187 newtree = revset.findaliases(ui, tree)
2187 newtree = revset.findaliases(ui, tree)
2188 if newtree != tree:
2188 if newtree != tree:
2189 ui.note(revset.prettyformat(newtree), "\n")
2189 ui.note(revset.prettyformat(newtree), "\n")
2190 func = revset.match(ui, expr)
2190 func = revset.match(ui, expr)
2191 for c in func(repo, range(len(repo))):
2191 for c in func(repo, range(len(repo))):
2192 ui.write("%s\n" % c)
2192 ui.write("%s\n" % c)
2193
2193
2194 @command('debugsetparents', [], _('REV1 [REV2]'))
2194 @command('debugsetparents', [], _('REV1 [REV2]'))
2195 def debugsetparents(ui, repo, rev1, rev2=None):
2195 def debugsetparents(ui, repo, rev1, rev2=None):
2196 """manually set the parents of the current working directory
2196 """manually set the parents of the current working directory
2197
2197
2198 This is useful for writing repository conversion tools, but should
2198 This is useful for writing repository conversion tools, but should
2199 be used with care.
2199 be used with care.
2200
2200
2201 Returns 0 on success.
2201 Returns 0 on success.
2202 """
2202 """
2203
2203
2204 r1 = scmutil.revsingle(repo, rev1).node()
2204 r1 = scmutil.revsingle(repo, rev1).node()
2205 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2205 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2206
2206
2207 wlock = repo.wlock()
2207 wlock = repo.wlock()
2208 try:
2208 try:
2209 repo.dirstate.setparents(r1, r2)
2209 repo.dirstate.setparents(r1, r2)
2210 finally:
2210 finally:
2211 wlock.release()
2211 wlock.release()
2212
2212
2213 @command('debugstate',
2213 @command('debugstate',
2214 [('', 'nodates', None, _('do not display the saved mtime')),
2214 [('', 'nodates', None, _('do not display the saved mtime')),
2215 ('', 'datesort', None, _('sort by saved mtime'))],
2215 ('', 'datesort', None, _('sort by saved mtime'))],
2216 _('[OPTION]...'))
2216 _('[OPTION]...'))
2217 def debugstate(ui, repo, nodates=None, datesort=None):
2217 def debugstate(ui, repo, nodates=None, datesort=None):
2218 """show the contents of the current dirstate"""
2218 """show the contents of the current dirstate"""
2219 timestr = ""
2219 timestr = ""
2220 showdate = not nodates
2220 showdate = not nodates
2221 if datesort:
2221 if datesort:
2222 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2222 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2223 else:
2223 else:
2224 keyfunc = None # sort by filename
2224 keyfunc = None # sort by filename
2225 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2225 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2226 if showdate:
2226 if showdate:
2227 if ent[3] == -1:
2227 if ent[3] == -1:
2228 # Pad or slice to locale representation
2228 # Pad or slice to locale representation
2229 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2229 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2230 time.localtime(0)))
2230 time.localtime(0)))
2231 timestr = 'unset'
2231 timestr = 'unset'
2232 timestr = (timestr[:locale_len] +
2232 timestr = (timestr[:locale_len] +
2233 ' ' * (locale_len - len(timestr)))
2233 ' ' * (locale_len - len(timestr)))
2234 else:
2234 else:
2235 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2235 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2236 time.localtime(ent[3]))
2236 time.localtime(ent[3]))
2237 if ent[1] & 020000:
2237 if ent[1] & 020000:
2238 mode = 'lnk'
2238 mode = 'lnk'
2239 else:
2239 else:
2240 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2240 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2241 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2241 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2242 for f in repo.dirstate.copies():
2242 for f in repo.dirstate.copies():
2243 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2243 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2244
2244
2245 @command('debugsub',
2245 @command('debugsub',
2246 [('r', 'rev', '',
2246 [('r', 'rev', '',
2247 _('revision to check'), _('REV'))],
2247 _('revision to check'), _('REV'))],
2248 _('[-r REV] [REV]'))
2248 _('[-r REV] [REV]'))
2249 def debugsub(ui, repo, rev=None):
2249 def debugsub(ui, repo, rev=None):
2250 ctx = scmutil.revsingle(repo, rev, None)
2250 ctx = scmutil.revsingle(repo, rev, None)
2251 for k, v in sorted(ctx.substate.items()):
2251 for k, v in sorted(ctx.substate.items()):
2252 ui.write('path %s\n' % k)
2252 ui.write('path %s\n' % k)
2253 ui.write(' source %s\n' % v[0])
2253 ui.write(' source %s\n' % v[0])
2254 ui.write(' revision %s\n' % v[1])
2254 ui.write(' revision %s\n' % v[1])
2255
2255
2256 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2256 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2257 def debugwalk(ui, repo, *pats, **opts):
2257 def debugwalk(ui, repo, *pats, **opts):
2258 """show how files match on given patterns"""
2258 """show how files match on given patterns"""
2259 m = scmutil.match(repo[None], pats, opts)
2259 m = scmutil.match(repo[None], pats, opts)
2260 items = list(repo.walk(m))
2260 items = list(repo.walk(m))
2261 if not items:
2261 if not items:
2262 return
2262 return
2263 fmt = 'f %%-%ds %%-%ds %%s' % (
2263 fmt = 'f %%-%ds %%-%ds %%s' % (
2264 max([len(abs) for abs in items]),
2264 max([len(abs) for abs in items]),
2265 max([len(m.rel(abs)) for abs in items]))
2265 max([len(m.rel(abs)) for abs in items]))
2266 for abs in items:
2266 for abs in items:
2267 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2267 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2268 ui.write("%s\n" % line.rstrip())
2268 ui.write("%s\n" % line.rstrip())
2269
2269
2270 @command('debugwireargs',
2270 @command('debugwireargs',
2271 [('', 'three', '', 'three'),
2271 [('', 'three', '', 'three'),
2272 ('', 'four', '', 'four'),
2272 ('', 'four', '', 'four'),
2273 ('', 'five', '', 'five'),
2273 ('', 'five', '', 'five'),
2274 ] + remoteopts,
2274 ] + remoteopts,
2275 _('REPO [OPTIONS]... [ONE [TWO]]'))
2275 _('REPO [OPTIONS]... [ONE [TWO]]'))
2276 def debugwireargs(ui, repopath, *vals, **opts):
2276 def debugwireargs(ui, repopath, *vals, **opts):
2277 repo = hg.peer(ui, opts, repopath)
2277 repo = hg.peer(ui, opts, repopath)
2278 for opt in remoteopts:
2278 for opt in remoteopts:
2279 del opts[opt[1]]
2279 del opts[opt[1]]
2280 args = {}
2280 args = {}
2281 for k, v in opts.iteritems():
2281 for k, v in opts.iteritems():
2282 if v:
2282 if v:
2283 args[k] = v
2283 args[k] = v
2284 # run twice to check that we don't mess up the stream for the next command
2284 # run twice to check that we don't mess up the stream for the next command
2285 res1 = repo.debugwireargs(*vals, **args)
2285 res1 = repo.debugwireargs(*vals, **args)
2286 res2 = repo.debugwireargs(*vals, **args)
2286 res2 = repo.debugwireargs(*vals, **args)
2287 ui.write("%s\n" % res1)
2287 ui.write("%s\n" % res1)
2288 if res1 != res2:
2288 if res1 != res2:
2289 ui.warn("%s\n" % res2)
2289 ui.warn("%s\n" % res2)
2290
2290
2291 @command('^diff',
2291 @command('^diff',
2292 [('r', 'rev', [], _('revision'), _('REV')),
2292 [('r', 'rev', [], _('revision'), _('REV')),
2293 ('c', 'change', '', _('change made by revision'), _('REV'))
2293 ('c', 'change', '', _('change made by revision'), _('REV'))
2294 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2294 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2295 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2295 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2296 def diff(ui, repo, *pats, **opts):
2296 def diff(ui, repo, *pats, **opts):
2297 """diff repository (or selected files)
2297 """diff repository (or selected files)
2298
2298
2299 Show differences between revisions for the specified files.
2299 Show differences between revisions for the specified files.
2300
2300
2301 Differences between files are shown using the unified diff format.
2301 Differences between files are shown using the unified diff format.
2302
2302
2303 .. note::
2303 .. note::
2304 diff may generate unexpected results for merges, as it will
2304 diff may generate unexpected results for merges, as it will
2305 default to comparing against the working directory's first
2305 default to comparing against the working directory's first
2306 parent changeset if no revisions are specified.
2306 parent changeset if no revisions are specified.
2307
2307
2308 When two revision arguments are given, then changes are shown
2308 When two revision arguments are given, then changes are shown
2309 between those revisions. If only one revision is specified then
2309 between those revisions. If only one revision is specified then
2310 that revision is compared to the working directory, and, when no
2310 that revision is compared to the working directory, and, when no
2311 revisions are specified, the working directory files are compared
2311 revisions are specified, the working directory files are compared
2312 to its parent.
2312 to its parent.
2313
2313
2314 Alternatively you can specify -c/--change with a revision to see
2314 Alternatively you can specify -c/--change with a revision to see
2315 the changes in that changeset relative to its first parent.
2315 the changes in that changeset relative to its first parent.
2316
2316
2317 Without the -a/--text option, diff will avoid generating diffs of
2317 Without the -a/--text option, diff will avoid generating diffs of
2318 files it detects as binary. With -a, diff will generate a diff
2318 files it detects as binary. With -a, diff will generate a diff
2319 anyway, probably with undesirable results.
2319 anyway, probably with undesirable results.
2320
2320
2321 Use the -g/--git option to generate diffs in the git extended diff
2321 Use the -g/--git option to generate diffs in the git extended diff
2322 format. For more information, read :hg:`help diffs`.
2322 format. For more information, read :hg:`help diffs`.
2323
2323
2324 .. container:: verbose
2324 .. container:: verbose
2325
2325
2326 Examples:
2326 Examples:
2327
2327
2328 - compare a file in the current working directory to its parent::
2328 - compare a file in the current working directory to its parent::
2329
2329
2330 hg diff foo.c
2330 hg diff foo.c
2331
2331
2332 - compare two historical versions of a directory, with rename info::
2332 - compare two historical versions of a directory, with rename info::
2333
2333
2334 hg diff --git -r 1.0:1.2 lib/
2334 hg diff --git -r 1.0:1.2 lib/
2335
2335
2336 - get change stats relative to the last change on some date::
2336 - get change stats relative to the last change on some date::
2337
2337
2338 hg diff --stat -r "date('may 2')"
2338 hg diff --stat -r "date('may 2')"
2339
2339
2340 - diff all newly-added files that contain a keyword::
2340 - diff all newly-added files that contain a keyword::
2341
2341
2342 hg diff "set:added() and grep(GNU)"
2342 hg diff "set:added() and grep(GNU)"
2343
2343
2344 - compare a revision and its parents::
2344 - compare a revision and its parents::
2345
2345
2346 hg diff -c 9353 # compare against first parent
2346 hg diff -c 9353 # compare against first parent
2347 hg diff -r 9353^:9353 # same using revset syntax
2347 hg diff -r 9353^:9353 # same using revset syntax
2348 hg diff -r 9353^2:9353 # compare against the second parent
2348 hg diff -r 9353^2:9353 # compare against the second parent
2349
2349
2350 Returns 0 on success.
2350 Returns 0 on success.
2351 """
2351 """
2352
2352
2353 revs = opts.get('rev')
2353 revs = opts.get('rev')
2354 change = opts.get('change')
2354 change = opts.get('change')
2355 stat = opts.get('stat')
2355 stat = opts.get('stat')
2356 reverse = opts.get('reverse')
2356 reverse = opts.get('reverse')
2357
2357
2358 if revs and change:
2358 if revs and change:
2359 msg = _('cannot specify --rev and --change at the same time')
2359 msg = _('cannot specify --rev and --change at the same time')
2360 raise util.Abort(msg)
2360 raise util.Abort(msg)
2361 elif change:
2361 elif change:
2362 node2 = scmutil.revsingle(repo, change, None).node()
2362 node2 = scmutil.revsingle(repo, change, None).node()
2363 node1 = repo[node2].p1().node()
2363 node1 = repo[node2].p1().node()
2364 else:
2364 else:
2365 node1, node2 = scmutil.revpair(repo, revs)
2365 node1, node2 = scmutil.revpair(repo, revs)
2366
2366
2367 if reverse:
2367 if reverse:
2368 node1, node2 = node2, node1
2368 node1, node2 = node2, node1
2369
2369
2370 diffopts = patch.diffopts(ui, opts)
2370 diffopts = patch.diffopts(ui, opts)
2371 m = scmutil.match(repo[node2], pats, opts)
2371 m = scmutil.match(repo[node2], pats, opts)
2372 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2372 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2373 listsubrepos=opts.get('subrepos'))
2373 listsubrepos=opts.get('subrepos'))
2374
2374
2375 @command('^export',
2375 @command('^export',
2376 [('o', 'output', '',
2376 [('o', 'output', '',
2377 _('print output to file with formatted name'), _('FORMAT')),
2377 _('print output to file with formatted name'), _('FORMAT')),
2378 ('', 'switch-parent', None, _('diff against the second parent')),
2378 ('', 'switch-parent', None, _('diff against the second parent')),
2379 ('r', 'rev', [], _('revisions to export'), _('REV')),
2379 ('r', 'rev', [], _('revisions to export'), _('REV')),
2380 ] + diffopts,
2380 ] + diffopts,
2381 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2381 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2382 def export(ui, repo, *changesets, **opts):
2382 def export(ui, repo, *changesets, **opts):
2383 """dump the header and diffs for one or more changesets
2383 """dump the header and diffs for one or more changesets
2384
2384
2385 Print the changeset header and diffs for one or more revisions.
2385 Print the changeset header and diffs for one or more revisions.
2386
2386
2387 The information shown in the changeset header is: author, date,
2387 The information shown in the changeset header is: author, date,
2388 branch name (if non-default), changeset hash, parent(s) and commit
2388 branch name (if non-default), changeset hash, parent(s) and commit
2389 comment.
2389 comment.
2390
2390
2391 .. note::
2391 .. note::
2392 export may generate unexpected diff output for merge
2392 export may generate unexpected diff output for merge
2393 changesets, as it will compare the merge changeset against its
2393 changesets, as it will compare the merge changeset against its
2394 first parent only.
2394 first parent only.
2395
2395
2396 Output may be to a file, in which case the name of the file is
2396 Output may be to a file, in which case the name of the file is
2397 given using a format string. The formatting rules are as follows:
2397 given using a format string. The formatting rules are as follows:
2398
2398
2399 :``%%``: literal "%" character
2399 :``%%``: literal "%" character
2400 :``%H``: changeset hash (40 hexadecimal digits)
2400 :``%H``: changeset hash (40 hexadecimal digits)
2401 :``%N``: number of patches being generated
2401 :``%N``: number of patches being generated
2402 :``%R``: changeset revision number
2402 :``%R``: changeset revision number
2403 :``%b``: basename of the exporting repository
2403 :``%b``: basename of the exporting repository
2404 :``%h``: short-form changeset hash (12 hexadecimal digits)
2404 :``%h``: short-form changeset hash (12 hexadecimal digits)
2405 :``%m``: first line of the commit message (only alphanumeric characters)
2405 :``%m``: first line of the commit message (only alphanumeric characters)
2406 :``%n``: zero-padded sequence number, starting at 1
2406 :``%n``: zero-padded sequence number, starting at 1
2407 :``%r``: zero-padded changeset revision number
2407 :``%r``: zero-padded changeset revision number
2408
2408
2409 Without the -a/--text option, export will avoid generating diffs
2409 Without the -a/--text option, export will avoid generating diffs
2410 of files it detects as binary. With -a, export will generate a
2410 of files it detects as binary. With -a, export will generate a
2411 diff anyway, probably with undesirable results.
2411 diff anyway, probably with undesirable results.
2412
2412
2413 Use the -g/--git option to generate diffs in the git extended diff
2413 Use the -g/--git option to generate diffs in the git extended diff
2414 format. See :hg:`help diffs` for more information.
2414 format. See :hg:`help diffs` for more information.
2415
2415
2416 With the --switch-parent option, the diff will be against the
2416 With the --switch-parent option, the diff will be against the
2417 second parent. It can be useful to review a merge.
2417 second parent. It can be useful to review a merge.
2418
2418
2419 .. container:: verbose
2419 .. container:: verbose
2420
2420
2421 Examples:
2421 Examples:
2422
2422
2423 - use export and import to transplant a bugfix to the current
2423 - use export and import to transplant a bugfix to the current
2424 branch::
2424 branch::
2425
2425
2426 hg export -r 9353 | hg import -
2426 hg export -r 9353 | hg import -
2427
2427
2428 - export all the changesets between two revisions to a file with
2428 - export all the changesets between two revisions to a file with
2429 rename information::
2429 rename information::
2430
2430
2431 hg export --git -r 123:150 > changes.txt
2431 hg export --git -r 123:150 > changes.txt
2432
2432
2433 - split outgoing changes into a series of patches with
2433 - split outgoing changes into a series of patches with
2434 descriptive names::
2434 descriptive names::
2435
2435
2436 hg export -r "outgoing()" -o "%n-%m.patch"
2436 hg export -r "outgoing()" -o "%n-%m.patch"
2437
2437
2438 Returns 0 on success.
2438 Returns 0 on success.
2439 """
2439 """
2440 changesets += tuple(opts.get('rev', []))
2440 changesets += tuple(opts.get('rev', []))
2441 if not changesets:
2441 revs = scmutil.revrange(repo, changesets)
2442 if not revs:
2442 raise util.Abort(_("export requires at least one changeset"))
2443 raise util.Abort(_("export requires at least one changeset"))
2443 revs = scmutil.revrange(repo, changesets)
2444 if len(revs) > 1:
2444 if len(revs) > 1:
2445 ui.note(_('exporting patches:\n'))
2445 ui.note(_('exporting patches:\n'))
2446 else:
2446 else:
2447 ui.note(_('exporting patch:\n'))
2447 ui.note(_('exporting patch:\n'))
2448 cmdutil.export(repo, revs, template=opts.get('output'),
2448 cmdutil.export(repo, revs, template=opts.get('output'),
2449 switch_parent=opts.get('switch_parent'),
2449 switch_parent=opts.get('switch_parent'),
2450 opts=patch.diffopts(ui, opts))
2450 opts=patch.diffopts(ui, opts))
2451
2451
2452 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2452 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2453 def forget(ui, repo, *pats, **opts):
2453 def forget(ui, repo, *pats, **opts):
2454 """forget the specified files on the next commit
2454 """forget the specified files on the next commit
2455
2455
2456 Mark the specified files so they will no longer be tracked
2456 Mark the specified files so they will no longer be tracked
2457 after the next commit.
2457 after the next commit.
2458
2458
2459 This only removes files from the current branch, not from the
2459 This only removes files from the current branch, not from the
2460 entire project history, and it does not delete them from the
2460 entire project history, and it does not delete them from the
2461 working directory.
2461 working directory.
2462
2462
2463 To undo a forget before the next commit, see :hg:`add`.
2463 To undo a forget before the next commit, see :hg:`add`.
2464
2464
2465 .. container:: verbose
2465 .. container:: verbose
2466
2466
2467 Examples:
2467 Examples:
2468
2468
2469 - forget newly-added binary files::
2469 - forget newly-added binary files::
2470
2470
2471 hg forget "set:added() and binary()"
2471 hg forget "set:added() and binary()"
2472
2472
2473 - forget files that would be excluded by .hgignore::
2473 - forget files that would be excluded by .hgignore::
2474
2474
2475 hg forget "set:hgignore()"
2475 hg forget "set:hgignore()"
2476
2476
2477 Returns 0 on success.
2477 Returns 0 on success.
2478 """
2478 """
2479
2479
2480 if not pats:
2480 if not pats:
2481 raise util.Abort(_('no files specified'))
2481 raise util.Abort(_('no files specified'))
2482
2482
2483 m = scmutil.match(repo[None], pats, opts)
2483 m = scmutil.match(repo[None], pats, opts)
2484 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2484 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2485 return rejected and 1 or 0
2485 return rejected and 1 or 0
2486
2486
2487 @command(
2487 @command(
2488 'graft',
2488 'graft',
2489 [('c', 'continue', False, _('resume interrupted graft')),
2489 [('c', 'continue', False, _('resume interrupted graft')),
2490 ('e', 'edit', False, _('invoke editor on commit messages')),
2490 ('e', 'edit', False, _('invoke editor on commit messages')),
2491 ('D', 'currentdate', False,
2491 ('D', 'currentdate', False,
2492 _('record the current date as commit date')),
2492 _('record the current date as commit date')),
2493 ('U', 'currentuser', False,
2493 ('U', 'currentuser', False,
2494 _('record the current user as committer'), _('DATE'))]
2494 _('record the current user as committer'), _('DATE'))]
2495 + commitopts2 + mergetoolopts,
2495 + commitopts2 + mergetoolopts,
2496 _('[OPTION]... REVISION...'))
2496 _('[OPTION]... REVISION...'))
2497 def graft(ui, repo, *revs, **opts):
2497 def graft(ui, repo, *revs, **opts):
2498 '''copy changes from other branches onto the current branch
2498 '''copy changes from other branches onto the current branch
2499
2499
2500 This command uses Mercurial's merge logic to copy individual
2500 This command uses Mercurial's merge logic to copy individual
2501 changes from other branches without merging branches in the
2501 changes from other branches without merging branches in the
2502 history graph. This is sometimes known as 'backporting' or
2502 history graph. This is sometimes known as 'backporting' or
2503 'cherry-picking'. By default, graft will copy user, date, and
2503 'cherry-picking'. By default, graft will copy user, date, and
2504 description from the source changesets.
2504 description from the source changesets.
2505
2505
2506 Changesets that are ancestors of the current revision, that have
2506 Changesets that are ancestors of the current revision, that have
2507 already been grafted, or that are merges will be skipped.
2507 already been grafted, or that are merges will be skipped.
2508
2508
2509 If a graft merge results in conflicts, the graft process is
2509 If a graft merge results in conflicts, the graft process is
2510 interrupted so that the current merge can be manually resolved.
2510 interrupted so that the current merge can be manually resolved.
2511 Once all conflicts are addressed, the graft process can be
2511 Once all conflicts are addressed, the graft process can be
2512 continued with the -c/--continue option.
2512 continued with the -c/--continue option.
2513
2513
2514 .. note::
2514 .. note::
2515 The -c/--continue option does not reapply earlier options.
2515 The -c/--continue option does not reapply earlier options.
2516
2516
2517 .. container:: verbose
2517 .. container:: verbose
2518
2518
2519 Examples:
2519 Examples:
2520
2520
2521 - copy a single change to the stable branch and edit its description::
2521 - copy a single change to the stable branch and edit its description::
2522
2522
2523 hg update stable
2523 hg update stable
2524 hg graft --edit 9393
2524 hg graft --edit 9393
2525
2525
2526 - graft a range of changesets with one exception, updating dates::
2526 - graft a range of changesets with one exception, updating dates::
2527
2527
2528 hg graft -D "2085::2093 and not 2091"
2528 hg graft -D "2085::2093 and not 2091"
2529
2529
2530 - continue a graft after resolving conflicts::
2530 - continue a graft after resolving conflicts::
2531
2531
2532 hg graft -c
2532 hg graft -c
2533
2533
2534 - show the source of a grafted changeset::
2534 - show the source of a grafted changeset::
2535
2535
2536 hg log --debug -r tip
2536 hg log --debug -r tip
2537
2537
2538 Returns 0 on successful completion.
2538 Returns 0 on successful completion.
2539 '''
2539 '''
2540
2540
2541 if not opts.get('user') and opts.get('currentuser'):
2541 if not opts.get('user') and opts.get('currentuser'):
2542 opts['user'] = ui.username()
2542 opts['user'] = ui.username()
2543 if not opts.get('date') and opts.get('currentdate'):
2543 if not opts.get('date') and opts.get('currentdate'):
2544 opts['date'] = "%d %d" % util.makedate()
2544 opts['date'] = "%d %d" % util.makedate()
2545
2545
2546 editor = None
2546 editor = None
2547 if opts.get('edit'):
2547 if opts.get('edit'):
2548 editor = cmdutil.commitforceeditor
2548 editor = cmdutil.commitforceeditor
2549
2549
2550 cont = False
2550 cont = False
2551 if opts['continue']:
2551 if opts['continue']:
2552 cont = True
2552 cont = True
2553 if revs:
2553 if revs:
2554 raise util.Abort(_("can't specify --continue and revisions"))
2554 raise util.Abort(_("can't specify --continue and revisions"))
2555 # read in unfinished revisions
2555 # read in unfinished revisions
2556 try:
2556 try:
2557 nodes = repo.opener.read('graftstate').splitlines()
2557 nodes = repo.opener.read('graftstate').splitlines()
2558 revs = [repo[node].rev() for node in nodes]
2558 revs = [repo[node].rev() for node in nodes]
2559 except IOError, inst:
2559 except IOError, inst:
2560 if inst.errno != errno.ENOENT:
2560 if inst.errno != errno.ENOENT:
2561 raise
2561 raise
2562 raise util.Abort(_("no graft state found, can't continue"))
2562 raise util.Abort(_("no graft state found, can't continue"))
2563 else:
2563 else:
2564 cmdutil.bailifchanged(repo)
2564 cmdutil.bailifchanged(repo)
2565 if not revs:
2565 if not revs:
2566 raise util.Abort(_('no revisions specified'))
2566 raise util.Abort(_('no revisions specified'))
2567 revs = scmutil.revrange(repo, revs)
2567 revs = scmutil.revrange(repo, revs)
2568
2568
2569 # check for merges
2569 # check for merges
2570 for rev in repo.revs('%ld and merge()', revs):
2570 for rev in repo.revs('%ld and merge()', revs):
2571 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2571 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2572 revs.remove(rev)
2572 revs.remove(rev)
2573 if not revs:
2573 if not revs:
2574 return -1
2574 return -1
2575
2575
2576 # check for ancestors of dest branch
2576 # check for ancestors of dest branch
2577 for rev in repo.revs('::. and %ld', revs):
2577 for rev in repo.revs('::. and %ld', revs):
2578 ui.warn(_('skipping ancestor revision %s\n') % rev)
2578 ui.warn(_('skipping ancestor revision %s\n') % rev)
2579 revs.remove(rev)
2579 revs.remove(rev)
2580 if not revs:
2580 if not revs:
2581 return -1
2581 return -1
2582
2582
2583 # analyze revs for earlier grafts
2583 # analyze revs for earlier grafts
2584 ids = {}
2584 ids = {}
2585 for ctx in repo.set("%ld", revs):
2585 for ctx in repo.set("%ld", revs):
2586 ids[ctx.hex()] = ctx.rev()
2586 ids[ctx.hex()] = ctx.rev()
2587 n = ctx.extra().get('source')
2587 n = ctx.extra().get('source')
2588 if n:
2588 if n:
2589 ids[n] = ctx.rev()
2589 ids[n] = ctx.rev()
2590
2590
2591 # check ancestors for earlier grafts
2591 # check ancestors for earlier grafts
2592 ui.debug('scanning for duplicate grafts\n')
2592 ui.debug('scanning for duplicate grafts\n')
2593 for ctx in repo.set("::. - ::%ld", revs):
2593 for ctx in repo.set("::. - ::%ld", revs):
2594 n = ctx.extra().get('source')
2594 n = ctx.extra().get('source')
2595 if n in ids:
2595 if n in ids:
2596 r = repo[n].rev()
2596 r = repo[n].rev()
2597 if r in revs:
2597 if r in revs:
2598 ui.warn(_('skipping already grafted revision %s\n') % r)
2598 ui.warn(_('skipping already grafted revision %s\n') % r)
2599 revs.remove(r)
2599 revs.remove(r)
2600 elif ids[n] in revs:
2600 elif ids[n] in revs:
2601 ui.warn(_('skipping already grafted revision %s '
2601 ui.warn(_('skipping already grafted revision %s '
2602 '(same origin %d)\n') % (ids[n], r))
2602 '(same origin %d)\n') % (ids[n], r))
2603 revs.remove(ids[n])
2603 revs.remove(ids[n])
2604 elif ctx.hex() in ids:
2604 elif ctx.hex() in ids:
2605 r = ids[ctx.hex()]
2605 r = ids[ctx.hex()]
2606 ui.warn(_('skipping already grafted revision %s '
2606 ui.warn(_('skipping already grafted revision %s '
2607 '(was grafted from %d)\n') % (r, ctx.rev()))
2607 '(was grafted from %d)\n') % (r, ctx.rev()))
2608 revs.remove(r)
2608 revs.remove(r)
2609 if not revs:
2609 if not revs:
2610 return -1
2610 return -1
2611
2611
2612 for pos, ctx in enumerate(repo.set("%ld", revs)):
2612 for pos, ctx in enumerate(repo.set("%ld", revs)):
2613 current = repo['.']
2613 current = repo['.']
2614 ui.status(_('grafting revision %s\n') % ctx.rev())
2614 ui.status(_('grafting revision %s\n') % ctx.rev())
2615
2615
2616 # we don't merge the first commit when continuing
2616 # we don't merge the first commit when continuing
2617 if not cont:
2617 if not cont:
2618 # perform the graft merge with p1(rev) as 'ancestor'
2618 # perform the graft merge with p1(rev) as 'ancestor'
2619 try:
2619 try:
2620 # ui.forcemerge is an internal variable, do not document
2620 # ui.forcemerge is an internal variable, do not document
2621 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
2621 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
2622 stats = mergemod.update(repo, ctx.node(), True, True, False,
2622 stats = mergemod.update(repo, ctx.node(), True, True, False,
2623 ctx.p1().node())
2623 ctx.p1().node())
2624 finally:
2624 finally:
2625 ui.setconfig('ui', 'forcemerge', '')
2625 ui.setconfig('ui', 'forcemerge', '')
2626 # drop the second merge parent
2626 # drop the second merge parent
2627 repo.dirstate.setparents(current.node(), nullid)
2627 repo.dirstate.setparents(current.node(), nullid)
2628 repo.dirstate.write()
2628 repo.dirstate.write()
2629 # fix up dirstate for copies and renames
2629 # fix up dirstate for copies and renames
2630 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
2630 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
2631 # report any conflicts
2631 # report any conflicts
2632 if stats and stats[3] > 0:
2632 if stats and stats[3] > 0:
2633 # write out state for --continue
2633 # write out state for --continue
2634 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2634 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2635 repo.opener.write('graftstate', ''.join(nodelines))
2635 repo.opener.write('graftstate', ''.join(nodelines))
2636 raise util.Abort(
2636 raise util.Abort(
2637 _("unresolved conflicts, can't continue"),
2637 _("unresolved conflicts, can't continue"),
2638 hint=_('use hg resolve and hg graft --continue'))
2638 hint=_('use hg resolve and hg graft --continue'))
2639 else:
2639 else:
2640 cont = False
2640 cont = False
2641
2641
2642 # commit
2642 # commit
2643 source = ctx.extra().get('source')
2643 source = ctx.extra().get('source')
2644 if not source:
2644 if not source:
2645 source = ctx.hex()
2645 source = ctx.hex()
2646 extra = {'source': source}
2646 extra = {'source': source}
2647 user = ctx.user()
2647 user = ctx.user()
2648 if opts.get('user'):
2648 if opts.get('user'):
2649 user = opts['user']
2649 user = opts['user']
2650 date = ctx.date()
2650 date = ctx.date()
2651 if opts.get('date'):
2651 if opts.get('date'):
2652 date = opts['date']
2652 date = opts['date']
2653 repo.commit(text=ctx.description(), user=user,
2653 repo.commit(text=ctx.description(), user=user,
2654 date=date, extra=extra, editor=editor)
2654 date=date, extra=extra, editor=editor)
2655
2655
2656 # remove state when we complete successfully
2656 # remove state when we complete successfully
2657 if os.path.exists(repo.join('graftstate')):
2657 if os.path.exists(repo.join('graftstate')):
2658 util.unlinkpath(repo.join('graftstate'))
2658 util.unlinkpath(repo.join('graftstate'))
2659
2659
2660 return 0
2660 return 0
2661
2661
2662 @command('grep',
2662 @command('grep',
2663 [('0', 'print0', None, _('end fields with NUL')),
2663 [('0', 'print0', None, _('end fields with NUL')),
2664 ('', 'all', None, _('print all revisions that match')),
2664 ('', 'all', None, _('print all revisions that match')),
2665 ('a', 'text', None, _('treat all files as text')),
2665 ('a', 'text', None, _('treat all files as text')),
2666 ('f', 'follow', None,
2666 ('f', 'follow', None,
2667 _('follow changeset history,'
2667 _('follow changeset history,'
2668 ' or file history across copies and renames')),
2668 ' or file history across copies and renames')),
2669 ('i', 'ignore-case', None, _('ignore case when matching')),
2669 ('i', 'ignore-case', None, _('ignore case when matching')),
2670 ('l', 'files-with-matches', None,
2670 ('l', 'files-with-matches', None,
2671 _('print only filenames and revisions that match')),
2671 _('print only filenames and revisions that match')),
2672 ('n', 'line-number', None, _('print matching line numbers')),
2672 ('n', 'line-number', None, _('print matching line numbers')),
2673 ('r', 'rev', [],
2673 ('r', 'rev', [],
2674 _('only search files changed within revision range'), _('REV')),
2674 _('only search files changed within revision range'), _('REV')),
2675 ('u', 'user', None, _('list the author (long with -v)')),
2675 ('u', 'user', None, _('list the author (long with -v)')),
2676 ('d', 'date', None, _('list the date (short with -q)')),
2676 ('d', 'date', None, _('list the date (short with -q)')),
2677 ] + walkopts,
2677 ] + walkopts,
2678 _('[OPTION]... PATTERN [FILE]...'))
2678 _('[OPTION]... PATTERN [FILE]...'))
2679 def grep(ui, repo, pattern, *pats, **opts):
2679 def grep(ui, repo, pattern, *pats, **opts):
2680 """search for a pattern in specified files and revisions
2680 """search for a pattern in specified files and revisions
2681
2681
2682 Search revisions of files for a regular expression.
2682 Search revisions of files for a regular expression.
2683
2683
2684 This command behaves differently than Unix grep. It only accepts
2684 This command behaves differently than Unix grep. It only accepts
2685 Python/Perl regexps. It searches repository history, not the
2685 Python/Perl regexps. It searches repository history, not the
2686 working directory. It always prints the revision number in which a
2686 working directory. It always prints the revision number in which a
2687 match appears.
2687 match appears.
2688
2688
2689 By default, grep only prints output for the first revision of a
2689 By default, grep only prints output for the first revision of a
2690 file in which it finds a match. To get it to print every revision
2690 file in which it finds a match. To get it to print every revision
2691 that contains a change in match status ("-" for a match that
2691 that contains a change in match status ("-" for a match that
2692 becomes a non-match, or "+" for a non-match that becomes a match),
2692 becomes a non-match, or "+" for a non-match that becomes a match),
2693 use the --all flag.
2693 use the --all flag.
2694
2694
2695 Returns 0 if a match is found, 1 otherwise.
2695 Returns 0 if a match is found, 1 otherwise.
2696 """
2696 """
2697 reflags = re.M
2697 reflags = re.M
2698 if opts.get('ignore_case'):
2698 if opts.get('ignore_case'):
2699 reflags |= re.I
2699 reflags |= re.I
2700 try:
2700 try:
2701 regexp = re.compile(pattern, reflags)
2701 regexp = re.compile(pattern, reflags)
2702 except re.error, inst:
2702 except re.error, inst:
2703 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2703 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2704 return 1
2704 return 1
2705 sep, eol = ':', '\n'
2705 sep, eol = ':', '\n'
2706 if opts.get('print0'):
2706 if opts.get('print0'):
2707 sep = eol = '\0'
2707 sep = eol = '\0'
2708
2708
2709 getfile = util.lrucachefunc(repo.file)
2709 getfile = util.lrucachefunc(repo.file)
2710
2710
2711 def matchlines(body):
2711 def matchlines(body):
2712 begin = 0
2712 begin = 0
2713 linenum = 0
2713 linenum = 0
2714 while True:
2714 while True:
2715 match = regexp.search(body, begin)
2715 match = regexp.search(body, begin)
2716 if not match:
2716 if not match:
2717 break
2717 break
2718 mstart, mend = match.span()
2718 mstart, mend = match.span()
2719 linenum += body.count('\n', begin, mstart) + 1
2719 linenum += body.count('\n', begin, mstart) + 1
2720 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2720 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2721 begin = body.find('\n', mend) + 1 or len(body) + 1
2721 begin = body.find('\n', mend) + 1 or len(body) + 1
2722 lend = begin - 1
2722 lend = begin - 1
2723 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2723 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2724
2724
2725 class linestate(object):
2725 class linestate(object):
2726 def __init__(self, line, linenum, colstart, colend):
2726 def __init__(self, line, linenum, colstart, colend):
2727 self.line = line
2727 self.line = line
2728 self.linenum = linenum
2728 self.linenum = linenum
2729 self.colstart = colstart
2729 self.colstart = colstart
2730 self.colend = colend
2730 self.colend = colend
2731
2731
2732 def __hash__(self):
2732 def __hash__(self):
2733 return hash((self.linenum, self.line))
2733 return hash((self.linenum, self.line))
2734
2734
2735 def __eq__(self, other):
2735 def __eq__(self, other):
2736 return self.line == other.line
2736 return self.line == other.line
2737
2737
2738 matches = {}
2738 matches = {}
2739 copies = {}
2739 copies = {}
2740 def grepbody(fn, rev, body):
2740 def grepbody(fn, rev, body):
2741 matches[rev].setdefault(fn, [])
2741 matches[rev].setdefault(fn, [])
2742 m = matches[rev][fn]
2742 m = matches[rev][fn]
2743 for lnum, cstart, cend, line in matchlines(body):
2743 for lnum, cstart, cend, line in matchlines(body):
2744 s = linestate(line, lnum, cstart, cend)
2744 s = linestate(line, lnum, cstart, cend)
2745 m.append(s)
2745 m.append(s)
2746
2746
2747 def difflinestates(a, b):
2747 def difflinestates(a, b):
2748 sm = difflib.SequenceMatcher(None, a, b)
2748 sm = difflib.SequenceMatcher(None, a, b)
2749 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2749 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2750 if tag == 'insert':
2750 if tag == 'insert':
2751 for i in xrange(blo, bhi):
2751 for i in xrange(blo, bhi):
2752 yield ('+', b[i])
2752 yield ('+', b[i])
2753 elif tag == 'delete':
2753 elif tag == 'delete':
2754 for i in xrange(alo, ahi):
2754 for i in xrange(alo, ahi):
2755 yield ('-', a[i])
2755 yield ('-', a[i])
2756 elif tag == 'replace':
2756 elif tag == 'replace':
2757 for i in xrange(alo, ahi):
2757 for i in xrange(alo, ahi):
2758 yield ('-', a[i])
2758 yield ('-', a[i])
2759 for i in xrange(blo, bhi):
2759 for i in xrange(blo, bhi):
2760 yield ('+', b[i])
2760 yield ('+', b[i])
2761
2761
2762 def display(fn, ctx, pstates, states):
2762 def display(fn, ctx, pstates, states):
2763 rev = ctx.rev()
2763 rev = ctx.rev()
2764 datefunc = ui.quiet and util.shortdate or util.datestr
2764 datefunc = ui.quiet and util.shortdate or util.datestr
2765 found = False
2765 found = False
2766 filerevmatches = {}
2766 filerevmatches = {}
2767 def binary():
2767 def binary():
2768 flog = getfile(fn)
2768 flog = getfile(fn)
2769 return util.binary(flog.read(ctx.filenode(fn)))
2769 return util.binary(flog.read(ctx.filenode(fn)))
2770
2770
2771 if opts.get('all'):
2771 if opts.get('all'):
2772 iter = difflinestates(pstates, states)
2772 iter = difflinestates(pstates, states)
2773 else:
2773 else:
2774 iter = [('', l) for l in states]
2774 iter = [('', l) for l in states]
2775 for change, l in iter:
2775 for change, l in iter:
2776 cols = [fn, str(rev)]
2776 cols = [fn, str(rev)]
2777 before, match, after = None, None, None
2777 before, match, after = None, None, None
2778 if opts.get('line_number'):
2778 if opts.get('line_number'):
2779 cols.append(str(l.linenum))
2779 cols.append(str(l.linenum))
2780 if opts.get('all'):
2780 if opts.get('all'):
2781 cols.append(change)
2781 cols.append(change)
2782 if opts.get('user'):
2782 if opts.get('user'):
2783 cols.append(ui.shortuser(ctx.user()))
2783 cols.append(ui.shortuser(ctx.user()))
2784 if opts.get('date'):
2784 if opts.get('date'):
2785 cols.append(datefunc(ctx.date()))
2785 cols.append(datefunc(ctx.date()))
2786 if opts.get('files_with_matches'):
2786 if opts.get('files_with_matches'):
2787 c = (fn, rev)
2787 c = (fn, rev)
2788 if c in filerevmatches:
2788 if c in filerevmatches:
2789 continue
2789 continue
2790 filerevmatches[c] = 1
2790 filerevmatches[c] = 1
2791 else:
2791 else:
2792 before = l.line[:l.colstart]
2792 before = l.line[:l.colstart]
2793 match = l.line[l.colstart:l.colend]
2793 match = l.line[l.colstart:l.colend]
2794 after = l.line[l.colend:]
2794 after = l.line[l.colend:]
2795 ui.write(sep.join(cols))
2795 ui.write(sep.join(cols))
2796 if before is not None:
2796 if before is not None:
2797 if not opts.get('text') and binary():
2797 if not opts.get('text') and binary():
2798 ui.write(sep + " Binary file matches")
2798 ui.write(sep + " Binary file matches")
2799 else:
2799 else:
2800 ui.write(sep + before)
2800 ui.write(sep + before)
2801 ui.write(match, label='grep.match')
2801 ui.write(match, label='grep.match')
2802 ui.write(after)
2802 ui.write(after)
2803 ui.write(eol)
2803 ui.write(eol)
2804 found = True
2804 found = True
2805 return found
2805 return found
2806
2806
2807 skip = {}
2807 skip = {}
2808 revfiles = {}
2808 revfiles = {}
2809 matchfn = scmutil.match(repo[None], pats, opts)
2809 matchfn = scmutil.match(repo[None], pats, opts)
2810 found = False
2810 found = False
2811 follow = opts.get('follow')
2811 follow = opts.get('follow')
2812
2812
2813 def prep(ctx, fns):
2813 def prep(ctx, fns):
2814 rev = ctx.rev()
2814 rev = ctx.rev()
2815 pctx = ctx.p1()
2815 pctx = ctx.p1()
2816 parent = pctx.rev()
2816 parent = pctx.rev()
2817 matches.setdefault(rev, {})
2817 matches.setdefault(rev, {})
2818 matches.setdefault(parent, {})
2818 matches.setdefault(parent, {})
2819 files = revfiles.setdefault(rev, [])
2819 files = revfiles.setdefault(rev, [])
2820 for fn in fns:
2820 for fn in fns:
2821 flog = getfile(fn)
2821 flog = getfile(fn)
2822 try:
2822 try:
2823 fnode = ctx.filenode(fn)
2823 fnode = ctx.filenode(fn)
2824 except error.LookupError:
2824 except error.LookupError:
2825 continue
2825 continue
2826
2826
2827 copied = flog.renamed(fnode)
2827 copied = flog.renamed(fnode)
2828 copy = follow and copied and copied[0]
2828 copy = follow and copied and copied[0]
2829 if copy:
2829 if copy:
2830 copies.setdefault(rev, {})[fn] = copy
2830 copies.setdefault(rev, {})[fn] = copy
2831 if fn in skip:
2831 if fn in skip:
2832 if copy:
2832 if copy:
2833 skip[copy] = True
2833 skip[copy] = True
2834 continue
2834 continue
2835 files.append(fn)
2835 files.append(fn)
2836
2836
2837 if fn not in matches[rev]:
2837 if fn not in matches[rev]:
2838 grepbody(fn, rev, flog.read(fnode))
2838 grepbody(fn, rev, flog.read(fnode))
2839
2839
2840 pfn = copy or fn
2840 pfn = copy or fn
2841 if pfn not in matches[parent]:
2841 if pfn not in matches[parent]:
2842 try:
2842 try:
2843 fnode = pctx.filenode(pfn)
2843 fnode = pctx.filenode(pfn)
2844 grepbody(pfn, parent, flog.read(fnode))
2844 grepbody(pfn, parent, flog.read(fnode))
2845 except error.LookupError:
2845 except error.LookupError:
2846 pass
2846 pass
2847
2847
2848 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2848 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2849 rev = ctx.rev()
2849 rev = ctx.rev()
2850 parent = ctx.p1().rev()
2850 parent = ctx.p1().rev()
2851 for fn in sorted(revfiles.get(rev, [])):
2851 for fn in sorted(revfiles.get(rev, [])):
2852 states = matches[rev][fn]
2852 states = matches[rev][fn]
2853 copy = copies.get(rev, {}).get(fn)
2853 copy = copies.get(rev, {}).get(fn)
2854 if fn in skip:
2854 if fn in skip:
2855 if copy:
2855 if copy:
2856 skip[copy] = True
2856 skip[copy] = True
2857 continue
2857 continue
2858 pstates = matches.get(parent, {}).get(copy or fn, [])
2858 pstates = matches.get(parent, {}).get(copy or fn, [])
2859 if pstates or states:
2859 if pstates or states:
2860 r = display(fn, ctx, pstates, states)
2860 r = display(fn, ctx, pstates, states)
2861 found = found or r
2861 found = found or r
2862 if r and not opts.get('all'):
2862 if r and not opts.get('all'):
2863 skip[fn] = True
2863 skip[fn] = True
2864 if copy:
2864 if copy:
2865 skip[copy] = True
2865 skip[copy] = True
2866 del matches[rev]
2866 del matches[rev]
2867 del revfiles[rev]
2867 del revfiles[rev]
2868
2868
2869 return not found
2869 return not found
2870
2870
2871 @command('heads',
2871 @command('heads',
2872 [('r', 'rev', '',
2872 [('r', 'rev', '',
2873 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2873 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2874 ('t', 'topo', False, _('show topological heads only')),
2874 ('t', 'topo', False, _('show topological heads only')),
2875 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2875 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2876 ('c', 'closed', False, _('show normal and closed branch heads')),
2876 ('c', 'closed', False, _('show normal and closed branch heads')),
2877 ] + templateopts,
2877 ] + templateopts,
2878 _('[-ac] [-r STARTREV] [REV]...'))
2878 _('[-ac] [-r STARTREV] [REV]...'))
2879 def heads(ui, repo, *branchrevs, **opts):
2879 def heads(ui, repo, *branchrevs, **opts):
2880 """show current repository heads or show branch heads
2880 """show current repository heads or show branch heads
2881
2881
2882 With no arguments, show all repository branch heads.
2882 With no arguments, show all repository branch heads.
2883
2883
2884 Repository "heads" are changesets with no child changesets. They are
2884 Repository "heads" are changesets with no child changesets. They are
2885 where development generally takes place and are the usual targets
2885 where development generally takes place and are the usual targets
2886 for update and merge operations. Branch heads are changesets that have
2886 for update and merge operations. Branch heads are changesets that have
2887 no child changeset on the same branch.
2887 no child changeset on the same branch.
2888
2888
2889 If one or more REVs are given, only branch heads on the branches
2889 If one or more REVs are given, only branch heads on the branches
2890 associated with the specified changesets are shown. This means
2890 associated with the specified changesets are shown. This means
2891 that you can use :hg:`heads foo` to see the heads on a branch
2891 that you can use :hg:`heads foo` to see the heads on a branch
2892 named ``foo``.
2892 named ``foo``.
2893
2893
2894 If -c/--closed is specified, also show branch heads marked closed
2894 If -c/--closed is specified, also show branch heads marked closed
2895 (see :hg:`commit --close-branch`).
2895 (see :hg:`commit --close-branch`).
2896
2896
2897 If STARTREV is specified, only those heads that are descendants of
2897 If STARTREV is specified, only those heads that are descendants of
2898 STARTREV will be displayed.
2898 STARTREV will be displayed.
2899
2899
2900 If -t/--topo is specified, named branch mechanics will be ignored and only
2900 If -t/--topo is specified, named branch mechanics will be ignored and only
2901 changesets without children will be shown.
2901 changesets without children will be shown.
2902
2902
2903 Returns 0 if matching heads are found, 1 if not.
2903 Returns 0 if matching heads are found, 1 if not.
2904 """
2904 """
2905
2905
2906 start = None
2906 start = None
2907 if 'rev' in opts:
2907 if 'rev' in opts:
2908 start = scmutil.revsingle(repo, opts['rev'], None).node()
2908 start = scmutil.revsingle(repo, opts['rev'], None).node()
2909
2909
2910 if opts.get('topo'):
2910 if opts.get('topo'):
2911 heads = [repo[h] for h in repo.heads(start)]
2911 heads = [repo[h] for h in repo.heads(start)]
2912 else:
2912 else:
2913 heads = []
2913 heads = []
2914 for branch in repo.branchmap():
2914 for branch in repo.branchmap():
2915 heads += repo.branchheads(branch, start, opts.get('closed'))
2915 heads += repo.branchheads(branch, start, opts.get('closed'))
2916 heads = [repo[h] for h in heads]
2916 heads = [repo[h] for h in heads]
2917
2917
2918 if branchrevs:
2918 if branchrevs:
2919 branches = set(repo[br].branch() for br in branchrevs)
2919 branches = set(repo[br].branch() for br in branchrevs)
2920 heads = [h for h in heads if h.branch() in branches]
2920 heads = [h for h in heads if h.branch() in branches]
2921
2921
2922 if opts.get('active') and branchrevs:
2922 if opts.get('active') and branchrevs:
2923 dagheads = repo.heads(start)
2923 dagheads = repo.heads(start)
2924 heads = [h for h in heads if h.node() in dagheads]
2924 heads = [h for h in heads if h.node() in dagheads]
2925
2925
2926 if branchrevs:
2926 if branchrevs:
2927 haveheads = set(h.branch() for h in heads)
2927 haveheads = set(h.branch() for h in heads)
2928 if branches - haveheads:
2928 if branches - haveheads:
2929 headless = ', '.join(b for b in branches - haveheads)
2929 headless = ', '.join(b for b in branches - haveheads)
2930 msg = _('no open branch heads found on branches %s')
2930 msg = _('no open branch heads found on branches %s')
2931 if opts.get('rev'):
2931 if opts.get('rev'):
2932 msg += _(' (started at %s)') % opts['rev']
2932 msg += _(' (started at %s)') % opts['rev']
2933 ui.warn((msg + '\n') % headless)
2933 ui.warn((msg + '\n') % headless)
2934
2934
2935 if not heads:
2935 if not heads:
2936 return 1
2936 return 1
2937
2937
2938 heads = sorted(heads, key=lambda x: -x.rev())
2938 heads = sorted(heads, key=lambda x: -x.rev())
2939 displayer = cmdutil.show_changeset(ui, repo, opts)
2939 displayer = cmdutil.show_changeset(ui, repo, opts)
2940 for ctx in heads:
2940 for ctx in heads:
2941 displayer.show(ctx)
2941 displayer.show(ctx)
2942 displayer.close()
2942 displayer.close()
2943
2943
2944 @command('help',
2944 @command('help',
2945 [('e', 'extension', None, _('show only help for extensions')),
2945 [('e', 'extension', None, _('show only help for extensions')),
2946 ('c', 'command', None, _('show only help for commands'))],
2946 ('c', 'command', None, _('show only help for commands'))],
2947 _('[-ec] [TOPIC]'))
2947 _('[-ec] [TOPIC]'))
2948 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
2948 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
2949 """show help for a given topic or a help overview
2949 """show help for a given topic or a help overview
2950
2950
2951 With no arguments, print a list of commands with short help messages.
2951 With no arguments, print a list of commands with short help messages.
2952
2952
2953 Given a topic, extension, or command name, print help for that
2953 Given a topic, extension, or command name, print help for that
2954 topic.
2954 topic.
2955
2955
2956 Returns 0 if successful.
2956 Returns 0 if successful.
2957 """
2957 """
2958
2958
2959 textwidth = min(ui.termwidth(), 80) - 2
2959 textwidth = min(ui.termwidth(), 80) - 2
2960
2960
2961 def optrst(options):
2961 def optrst(options):
2962 data = []
2962 data = []
2963 multioccur = False
2963 multioccur = False
2964 for option in options:
2964 for option in options:
2965 if len(option) == 5:
2965 if len(option) == 5:
2966 shortopt, longopt, default, desc, optlabel = option
2966 shortopt, longopt, default, desc, optlabel = option
2967 else:
2967 else:
2968 shortopt, longopt, default, desc = option
2968 shortopt, longopt, default, desc = option
2969 optlabel = _("VALUE") # default label
2969 optlabel = _("VALUE") # default label
2970
2970
2971 if _("DEPRECATED") in desc and not ui.verbose:
2971 if _("DEPRECATED") in desc and not ui.verbose:
2972 continue
2972 continue
2973
2973
2974 so = ''
2974 so = ''
2975 if shortopt:
2975 if shortopt:
2976 so = '-' + shortopt
2976 so = '-' + shortopt
2977 lo = '--' + longopt
2977 lo = '--' + longopt
2978 if default:
2978 if default:
2979 desc += _(" (default: %s)") % default
2979 desc += _(" (default: %s)") % default
2980
2980
2981 if isinstance(default, list):
2981 if isinstance(default, list):
2982 lo += " %s [+]" % optlabel
2982 lo += " %s [+]" % optlabel
2983 multioccur = True
2983 multioccur = True
2984 elif (default is not None) and not isinstance(default, bool):
2984 elif (default is not None) and not isinstance(default, bool):
2985 lo += " %s" % optlabel
2985 lo += " %s" % optlabel
2986
2986
2987 data.append((so, lo, desc))
2987 data.append((so, lo, desc))
2988
2988
2989 rst = minirst.maketable(data, 1)
2989 rst = minirst.maketable(data, 1)
2990
2990
2991 if multioccur:
2991 if multioccur:
2992 rst += _("\n[+] marked option can be specified multiple times\n")
2992 rst += _("\n[+] marked option can be specified multiple times\n")
2993
2993
2994 return rst
2994 return rst
2995
2995
2996 # list all option lists
2996 # list all option lists
2997 def opttext(optlist, width):
2997 def opttext(optlist, width):
2998 rst = ''
2998 rst = ''
2999 if not optlist:
2999 if not optlist:
3000 return ''
3000 return ''
3001
3001
3002 for title, options in optlist:
3002 for title, options in optlist:
3003 rst += '\n%s\n' % title
3003 rst += '\n%s\n' % title
3004 if options:
3004 if options:
3005 rst += "\n"
3005 rst += "\n"
3006 rst += optrst(options)
3006 rst += optrst(options)
3007 rst += '\n'
3007 rst += '\n'
3008
3008
3009 return '\n' + minirst.format(rst, width)
3009 return '\n' + minirst.format(rst, width)
3010
3010
3011 def addglobalopts(optlist, aliases):
3011 def addglobalopts(optlist, aliases):
3012 if ui.quiet:
3012 if ui.quiet:
3013 return []
3013 return []
3014
3014
3015 if ui.verbose:
3015 if ui.verbose:
3016 optlist.append((_("global options:"), globalopts))
3016 optlist.append((_("global options:"), globalopts))
3017 if name == 'shortlist':
3017 if name == 'shortlist':
3018 optlist.append((_('use "hg help" for the full list '
3018 optlist.append((_('use "hg help" for the full list '
3019 'of commands'), ()))
3019 'of commands'), ()))
3020 else:
3020 else:
3021 if name == 'shortlist':
3021 if name == 'shortlist':
3022 msg = _('use "hg help" for the full list of commands '
3022 msg = _('use "hg help" for the full list of commands '
3023 'or "hg -v" for details')
3023 'or "hg -v" for details')
3024 elif name and not full:
3024 elif name and not full:
3025 msg = _('use "hg help %s" to show the full help text') % name
3025 msg = _('use "hg help %s" to show the full help text') % name
3026 elif aliases:
3026 elif aliases:
3027 msg = _('use "hg -v help%s" to show builtin aliases and '
3027 msg = _('use "hg -v help%s" to show builtin aliases and '
3028 'global options') % (name and " " + name or "")
3028 'global options') % (name and " " + name or "")
3029 else:
3029 else:
3030 msg = _('use "hg -v help %s" to show more info') % name
3030 msg = _('use "hg -v help %s" to show more info') % name
3031 optlist.append((msg, ()))
3031 optlist.append((msg, ()))
3032
3032
3033 def helpcmd(name):
3033 def helpcmd(name):
3034 try:
3034 try:
3035 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
3035 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
3036 except error.AmbiguousCommand, inst:
3036 except error.AmbiguousCommand, inst:
3037 # py3k fix: except vars can't be used outside the scope of the
3037 # py3k fix: except vars can't be used outside the scope of the
3038 # except block, nor can be used inside a lambda. python issue4617
3038 # except block, nor can be used inside a lambda. python issue4617
3039 prefix = inst.args[0]
3039 prefix = inst.args[0]
3040 select = lambda c: c.lstrip('^').startswith(prefix)
3040 select = lambda c: c.lstrip('^').startswith(prefix)
3041 helplist(select)
3041 helplist(select)
3042 return
3042 return
3043
3043
3044 # check if it's an invalid alias and display its error if it is
3044 # check if it's an invalid alias and display its error if it is
3045 if getattr(entry[0], 'badalias', False):
3045 if getattr(entry[0], 'badalias', False):
3046 if not unknowncmd:
3046 if not unknowncmd:
3047 entry[0](ui)
3047 entry[0](ui)
3048 return
3048 return
3049
3049
3050 rst = ""
3050 rst = ""
3051
3051
3052 # synopsis
3052 # synopsis
3053 if len(entry) > 2:
3053 if len(entry) > 2:
3054 if entry[2].startswith('hg'):
3054 if entry[2].startswith('hg'):
3055 rst += "%s\n" % entry[2]
3055 rst += "%s\n" % entry[2]
3056 else:
3056 else:
3057 rst += 'hg %s %s\n' % (aliases[0], entry[2])
3057 rst += 'hg %s %s\n' % (aliases[0], entry[2])
3058 else:
3058 else:
3059 rst += 'hg %s\n' % aliases[0]
3059 rst += 'hg %s\n' % aliases[0]
3060
3060
3061 # aliases
3061 # aliases
3062 if full and not ui.quiet and len(aliases) > 1:
3062 if full and not ui.quiet and len(aliases) > 1:
3063 rst += _("\naliases: %s\n") % ', '.join(aliases[1:])
3063 rst += _("\naliases: %s\n") % ', '.join(aliases[1:])
3064
3064
3065 # description
3065 # description
3066 doc = gettext(entry[0].__doc__)
3066 doc = gettext(entry[0].__doc__)
3067 if not doc:
3067 if not doc:
3068 doc = _("(no help text available)")
3068 doc = _("(no help text available)")
3069 if util.safehasattr(entry[0], 'definition'): # aliased command
3069 if util.safehasattr(entry[0], 'definition'): # aliased command
3070 if entry[0].definition.startswith('!'): # shell alias
3070 if entry[0].definition.startswith('!'): # shell alias
3071 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
3071 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
3072 else:
3072 else:
3073 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
3073 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
3074 if ui.quiet or not full:
3074 if ui.quiet or not full:
3075 doc = doc.splitlines()[0]
3075 doc = doc.splitlines()[0]
3076 rst += "\n" + doc + "\n"
3076 rst += "\n" + doc + "\n"
3077
3077
3078 # check if this command shadows a non-trivial (multi-line)
3078 # check if this command shadows a non-trivial (multi-line)
3079 # extension help text
3079 # extension help text
3080 try:
3080 try:
3081 mod = extensions.find(name)
3081 mod = extensions.find(name)
3082 doc = gettext(mod.__doc__) or ''
3082 doc = gettext(mod.__doc__) or ''
3083 if '\n' in doc.strip():
3083 if '\n' in doc.strip():
3084 msg = _('use "hg help -e %s" to show help for '
3084 msg = _('use "hg help -e %s" to show help for '
3085 'the %s extension') % (name, name)
3085 'the %s extension') % (name, name)
3086 rst += '\n%s\n' % msg
3086 rst += '\n%s\n' % msg
3087 except KeyError:
3087 except KeyError:
3088 pass
3088 pass
3089
3089
3090 # options
3090 # options
3091 if not ui.quiet and entry[1]:
3091 if not ui.quiet and entry[1]:
3092 rst += '\n'
3092 rst += '\n'
3093 rst += _("options:")
3093 rst += _("options:")
3094 rst += '\n\n'
3094 rst += '\n\n'
3095 rst += optrst(entry[1])
3095 rst += optrst(entry[1])
3096
3096
3097 if ui.verbose:
3097 if ui.verbose:
3098 rst += '\n'
3098 rst += '\n'
3099 rst += _("global options:")
3099 rst += _("global options:")
3100 rst += '\n\n'
3100 rst += '\n\n'
3101 rst += optrst(globalopts)
3101 rst += optrst(globalopts)
3102
3102
3103 keep = ui.verbose and ['verbose'] or []
3103 keep = ui.verbose and ['verbose'] or []
3104 formatted, pruned = minirst.format(rst, textwidth, keep=keep)
3104 formatted, pruned = minirst.format(rst, textwidth, keep=keep)
3105 ui.write(formatted)
3105 ui.write(formatted)
3106
3106
3107 if not ui.verbose:
3107 if not ui.verbose:
3108 if not full:
3108 if not full:
3109 ui.write(_('\nuse "hg help %s" to show the full help text\n')
3109 ui.write(_('\nuse "hg help %s" to show the full help text\n')
3110 % name)
3110 % name)
3111 elif not ui.quiet:
3111 elif not ui.quiet:
3112 ui.write(_('\nuse "hg -v help %s" to show more info\n') % name)
3112 ui.write(_('\nuse "hg -v help %s" to show more info\n') % name)
3113
3113
3114
3114
3115 def helplist(select=None):
3115 def helplist(select=None):
3116 # list of commands
3116 # list of commands
3117 if name == "shortlist":
3117 if name == "shortlist":
3118 header = _('basic commands:\n\n')
3118 header = _('basic commands:\n\n')
3119 else:
3119 else:
3120 header = _('list of commands:\n\n')
3120 header = _('list of commands:\n\n')
3121
3121
3122 h = {}
3122 h = {}
3123 cmds = {}
3123 cmds = {}
3124 for c, e in table.iteritems():
3124 for c, e in table.iteritems():
3125 f = c.split("|", 1)[0]
3125 f = c.split("|", 1)[0]
3126 if select and not select(f):
3126 if select and not select(f):
3127 continue
3127 continue
3128 if (not select and name != 'shortlist' and
3128 if (not select and name != 'shortlist' and
3129 e[0].__module__ != __name__):
3129 e[0].__module__ != __name__):
3130 continue
3130 continue
3131 if name == "shortlist" and not f.startswith("^"):
3131 if name == "shortlist" and not f.startswith("^"):
3132 continue
3132 continue
3133 f = f.lstrip("^")
3133 f = f.lstrip("^")
3134 if not ui.debugflag and f.startswith("debug"):
3134 if not ui.debugflag and f.startswith("debug"):
3135 continue
3135 continue
3136 doc = e[0].__doc__
3136 doc = e[0].__doc__
3137 if doc and 'DEPRECATED' in doc and not ui.verbose:
3137 if doc and 'DEPRECATED' in doc and not ui.verbose:
3138 continue
3138 continue
3139 doc = gettext(doc)
3139 doc = gettext(doc)
3140 if not doc:
3140 if not doc:
3141 doc = _("(no help text available)")
3141 doc = _("(no help text available)")
3142 h[f] = doc.splitlines()[0].rstrip()
3142 h[f] = doc.splitlines()[0].rstrip()
3143 cmds[f] = c.lstrip("^")
3143 cmds[f] = c.lstrip("^")
3144
3144
3145 if not h:
3145 if not h:
3146 ui.status(_('no commands defined\n'))
3146 ui.status(_('no commands defined\n'))
3147 return
3147 return
3148
3148
3149 ui.status(header)
3149 ui.status(header)
3150 fns = sorted(h)
3150 fns = sorted(h)
3151 m = max(map(len, fns))
3151 m = max(map(len, fns))
3152 for f in fns:
3152 for f in fns:
3153 if ui.verbose:
3153 if ui.verbose:
3154 commands = cmds[f].replace("|",", ")
3154 commands = cmds[f].replace("|",", ")
3155 ui.write(" %s:\n %s\n"%(commands, h[f]))
3155 ui.write(" %s:\n %s\n"%(commands, h[f]))
3156 else:
3156 else:
3157 ui.write('%s\n' % (util.wrap(h[f], textwidth,
3157 ui.write('%s\n' % (util.wrap(h[f], textwidth,
3158 initindent=' %-*s ' % (m, f),
3158 initindent=' %-*s ' % (m, f),
3159 hangindent=' ' * (m + 4))))
3159 hangindent=' ' * (m + 4))))
3160
3160
3161 if not name:
3161 if not name:
3162 text = help.listexts(_('enabled extensions:'), extensions.enabled())
3162 text = help.listexts(_('enabled extensions:'), extensions.enabled())
3163 if text:
3163 if text:
3164 ui.write("\n%s" % minirst.format(text, textwidth))
3164 ui.write("\n%s" % minirst.format(text, textwidth))
3165
3165
3166 ui.write(_("\nadditional help topics:\n\n"))
3166 ui.write(_("\nadditional help topics:\n\n"))
3167 topics = []
3167 topics = []
3168 for names, header, doc in help.helptable:
3168 for names, header, doc in help.helptable:
3169 topics.append((sorted(names, key=len, reverse=True)[0], header))
3169 topics.append((sorted(names, key=len, reverse=True)[0], header))
3170 topics_len = max([len(s[0]) for s in topics])
3170 topics_len = max([len(s[0]) for s in topics])
3171 for t, desc in topics:
3171 for t, desc in topics:
3172 ui.write(" %-*s %s\n" % (topics_len, t, desc))
3172 ui.write(" %-*s %s\n" % (topics_len, t, desc))
3173
3173
3174 optlist = []
3174 optlist = []
3175 addglobalopts(optlist, True)
3175 addglobalopts(optlist, True)
3176 ui.write(opttext(optlist, textwidth))
3176 ui.write(opttext(optlist, textwidth))
3177
3177
3178 def helptopic(name):
3178 def helptopic(name):
3179 for names, header, doc in help.helptable:
3179 for names, header, doc in help.helptable:
3180 if name in names:
3180 if name in names:
3181 break
3181 break
3182 else:
3182 else:
3183 raise error.UnknownCommand(name)
3183 raise error.UnknownCommand(name)
3184
3184
3185 # description
3185 # description
3186 if not doc:
3186 if not doc:
3187 doc = _("(no help text available)")
3187 doc = _("(no help text available)")
3188 if util.safehasattr(doc, '__call__'):
3188 if util.safehasattr(doc, '__call__'):
3189 doc = doc()
3189 doc = doc()
3190
3190
3191 ui.write("%s\n\n" % header)
3191 ui.write("%s\n\n" % header)
3192 ui.write("%s" % minirst.format(doc, textwidth, indent=4))
3192 ui.write("%s" % minirst.format(doc, textwidth, indent=4))
3193 try:
3193 try:
3194 cmdutil.findcmd(name, table)
3194 cmdutil.findcmd(name, table)
3195 ui.write(_('\nuse "hg help -c %s" to see help for '
3195 ui.write(_('\nuse "hg help -c %s" to see help for '
3196 'the %s command\n') % (name, name))
3196 'the %s command\n') % (name, name))
3197 except error.UnknownCommand:
3197 except error.UnknownCommand:
3198 pass
3198 pass
3199
3199
3200 def helpext(name):
3200 def helpext(name):
3201 try:
3201 try:
3202 mod = extensions.find(name)
3202 mod = extensions.find(name)
3203 doc = gettext(mod.__doc__) or _('no help text available')
3203 doc = gettext(mod.__doc__) or _('no help text available')
3204 except KeyError:
3204 except KeyError:
3205 mod = None
3205 mod = None
3206 doc = extensions.disabledext(name)
3206 doc = extensions.disabledext(name)
3207 if not doc:
3207 if not doc:
3208 raise error.UnknownCommand(name)
3208 raise error.UnknownCommand(name)
3209
3209
3210 if '\n' not in doc:
3210 if '\n' not in doc:
3211 head, tail = doc, ""
3211 head, tail = doc, ""
3212 else:
3212 else:
3213 head, tail = doc.split('\n', 1)
3213 head, tail = doc.split('\n', 1)
3214 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
3214 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
3215 if tail:
3215 if tail:
3216 ui.write(minirst.format(tail, textwidth))
3216 ui.write(minirst.format(tail, textwidth))
3217 ui.status('\n')
3217 ui.status('\n')
3218
3218
3219 if mod:
3219 if mod:
3220 try:
3220 try:
3221 ct = mod.cmdtable
3221 ct = mod.cmdtable
3222 except AttributeError:
3222 except AttributeError:
3223 ct = {}
3223 ct = {}
3224 modcmds = set([c.split('|', 1)[0] for c in ct])
3224 modcmds = set([c.split('|', 1)[0] for c in ct])
3225 helplist(modcmds.__contains__)
3225 helplist(modcmds.__contains__)
3226 else:
3226 else:
3227 ui.write(_('use "hg help extensions" for information on enabling '
3227 ui.write(_('use "hg help extensions" for information on enabling '
3228 'extensions\n'))
3228 'extensions\n'))
3229
3229
3230 def helpextcmd(name):
3230 def helpextcmd(name):
3231 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
3231 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
3232 doc = gettext(mod.__doc__).splitlines()[0]
3232 doc = gettext(mod.__doc__).splitlines()[0]
3233
3233
3234 msg = help.listexts(_("'%s' is provided by the following "
3234 msg = help.listexts(_("'%s' is provided by the following "
3235 "extension:") % cmd, {ext: doc}, indent=4)
3235 "extension:") % cmd, {ext: doc}, indent=4)
3236 ui.write(minirst.format(msg, textwidth))
3236 ui.write(minirst.format(msg, textwidth))
3237 ui.write('\n')
3237 ui.write('\n')
3238 ui.write(_('use "hg help extensions" for information on enabling '
3238 ui.write(_('use "hg help extensions" for information on enabling '
3239 'extensions\n'))
3239 'extensions\n'))
3240
3240
3241 if name and name != 'shortlist':
3241 if name and name != 'shortlist':
3242 i = None
3242 i = None
3243 if unknowncmd:
3243 if unknowncmd:
3244 queries = (helpextcmd,)
3244 queries = (helpextcmd,)
3245 elif opts.get('extension'):
3245 elif opts.get('extension'):
3246 queries = (helpext,)
3246 queries = (helpext,)
3247 elif opts.get('command'):
3247 elif opts.get('command'):
3248 queries = (helpcmd,)
3248 queries = (helpcmd,)
3249 else:
3249 else:
3250 queries = (helptopic, helpcmd, helpext, helpextcmd)
3250 queries = (helptopic, helpcmd, helpext, helpextcmd)
3251 for f in queries:
3251 for f in queries:
3252 try:
3252 try:
3253 f(name)
3253 f(name)
3254 i = None
3254 i = None
3255 break
3255 break
3256 except error.UnknownCommand, inst:
3256 except error.UnknownCommand, inst:
3257 i = inst
3257 i = inst
3258 if i:
3258 if i:
3259 raise i
3259 raise i
3260 else:
3260 else:
3261 # program name
3261 # program name
3262 ui.status(_("Mercurial Distributed SCM\n"))
3262 ui.status(_("Mercurial Distributed SCM\n"))
3263 ui.status('\n')
3263 ui.status('\n')
3264 helplist()
3264 helplist()
3265
3265
3266
3266
3267 @command('identify|id',
3267 @command('identify|id',
3268 [('r', 'rev', '',
3268 [('r', 'rev', '',
3269 _('identify the specified revision'), _('REV')),
3269 _('identify the specified revision'), _('REV')),
3270 ('n', 'num', None, _('show local revision number')),
3270 ('n', 'num', None, _('show local revision number')),
3271 ('i', 'id', None, _('show global revision id')),
3271 ('i', 'id', None, _('show global revision id')),
3272 ('b', 'branch', None, _('show branch')),
3272 ('b', 'branch', None, _('show branch')),
3273 ('t', 'tags', None, _('show tags')),
3273 ('t', 'tags', None, _('show tags')),
3274 ('B', 'bookmarks', None, _('show bookmarks')),
3274 ('B', 'bookmarks', None, _('show bookmarks')),
3275 ] + remoteopts,
3275 ] + remoteopts,
3276 _('[-nibtB] [-r REV] [SOURCE]'))
3276 _('[-nibtB] [-r REV] [SOURCE]'))
3277 def identify(ui, repo, source=None, rev=None,
3277 def identify(ui, repo, source=None, rev=None,
3278 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3278 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3279 """identify the working copy or specified revision
3279 """identify the working copy or specified revision
3280
3280
3281 Print a summary identifying the repository state at REV using one or
3281 Print a summary identifying the repository state at REV using one or
3282 two parent hash identifiers, followed by a "+" if the working
3282 two parent hash identifiers, followed by a "+" if the working
3283 directory has uncommitted changes, the branch name (if not default),
3283 directory has uncommitted changes, the branch name (if not default),
3284 a list of tags, and a list of bookmarks.
3284 a list of tags, and a list of bookmarks.
3285
3285
3286 When REV is not given, print a summary of the current state of the
3286 When REV is not given, print a summary of the current state of the
3287 repository.
3287 repository.
3288
3288
3289 Specifying a path to a repository root or Mercurial bundle will
3289 Specifying a path to a repository root or Mercurial bundle will
3290 cause lookup to operate on that repository/bundle.
3290 cause lookup to operate on that repository/bundle.
3291
3291
3292 .. container:: verbose
3292 .. container:: verbose
3293
3293
3294 Examples:
3294 Examples:
3295
3295
3296 - generate a build identifier for the working directory::
3296 - generate a build identifier for the working directory::
3297
3297
3298 hg id --id > build-id.dat
3298 hg id --id > build-id.dat
3299
3299
3300 - find the revision corresponding to a tag::
3300 - find the revision corresponding to a tag::
3301
3301
3302 hg id -n -r 1.3
3302 hg id -n -r 1.3
3303
3303
3304 - check the most recent revision of a remote repository::
3304 - check the most recent revision of a remote repository::
3305
3305
3306 hg id -r tip http://selenic.com/hg/
3306 hg id -r tip http://selenic.com/hg/
3307
3307
3308 Returns 0 if successful.
3308 Returns 0 if successful.
3309 """
3309 """
3310
3310
3311 if not repo and not source:
3311 if not repo and not source:
3312 raise util.Abort(_("there is no Mercurial repository here "
3312 raise util.Abort(_("there is no Mercurial repository here "
3313 "(.hg not found)"))
3313 "(.hg not found)"))
3314
3314
3315 hexfunc = ui.debugflag and hex or short
3315 hexfunc = ui.debugflag and hex or short
3316 default = not (num or id or branch or tags or bookmarks)
3316 default = not (num or id or branch or tags or bookmarks)
3317 output = []
3317 output = []
3318 revs = []
3318 revs = []
3319
3319
3320 if source:
3320 if source:
3321 source, branches = hg.parseurl(ui.expandpath(source))
3321 source, branches = hg.parseurl(ui.expandpath(source))
3322 repo = hg.peer(ui, opts, source)
3322 repo = hg.peer(ui, opts, source)
3323 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3323 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3324
3324
3325 if not repo.local():
3325 if not repo.local():
3326 if num or branch or tags:
3326 if num or branch or tags:
3327 raise util.Abort(
3327 raise util.Abort(
3328 _("can't query remote revision number, branch, or tags"))
3328 _("can't query remote revision number, branch, or tags"))
3329 if not rev and revs:
3329 if not rev and revs:
3330 rev = revs[0]
3330 rev = revs[0]
3331 if not rev:
3331 if not rev:
3332 rev = "tip"
3332 rev = "tip"
3333
3333
3334 remoterev = repo.lookup(rev)
3334 remoterev = repo.lookup(rev)
3335 if default or id:
3335 if default or id:
3336 output = [hexfunc(remoterev)]
3336 output = [hexfunc(remoterev)]
3337
3337
3338 def getbms():
3338 def getbms():
3339 bms = []
3339 bms = []
3340
3340
3341 if 'bookmarks' in repo.listkeys('namespaces'):
3341 if 'bookmarks' in repo.listkeys('namespaces'):
3342 hexremoterev = hex(remoterev)
3342 hexremoterev = hex(remoterev)
3343 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
3343 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
3344 if bmr == hexremoterev]
3344 if bmr == hexremoterev]
3345
3345
3346 return bms
3346 return bms
3347
3347
3348 if bookmarks:
3348 if bookmarks:
3349 output.extend(getbms())
3349 output.extend(getbms())
3350 elif default and not ui.quiet:
3350 elif default and not ui.quiet:
3351 # multiple bookmarks for a single parent separated by '/'
3351 # multiple bookmarks for a single parent separated by '/'
3352 bm = '/'.join(getbms())
3352 bm = '/'.join(getbms())
3353 if bm:
3353 if bm:
3354 output.append(bm)
3354 output.append(bm)
3355 else:
3355 else:
3356 if not rev:
3356 if not rev:
3357 ctx = repo[None]
3357 ctx = repo[None]
3358 parents = ctx.parents()
3358 parents = ctx.parents()
3359 changed = ""
3359 changed = ""
3360 if default or id or num:
3360 if default or id or num:
3361 changed = util.any(repo.status()) and "+" or ""
3361 changed = util.any(repo.status()) and "+" or ""
3362 if default or id:
3362 if default or id:
3363 output = ["%s%s" %
3363 output = ["%s%s" %
3364 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3364 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3365 if num:
3365 if num:
3366 output.append("%s%s" %
3366 output.append("%s%s" %
3367 ('+'.join([str(p.rev()) for p in parents]), changed))
3367 ('+'.join([str(p.rev()) for p in parents]), changed))
3368 else:
3368 else:
3369 ctx = scmutil.revsingle(repo, rev)
3369 ctx = scmutil.revsingle(repo, rev)
3370 if default or id:
3370 if default or id:
3371 output = [hexfunc(ctx.node())]
3371 output = [hexfunc(ctx.node())]
3372 if num:
3372 if num:
3373 output.append(str(ctx.rev()))
3373 output.append(str(ctx.rev()))
3374
3374
3375 if default and not ui.quiet:
3375 if default and not ui.quiet:
3376 b = ctx.branch()
3376 b = ctx.branch()
3377 if b != 'default':
3377 if b != 'default':
3378 output.append("(%s)" % b)
3378 output.append("(%s)" % b)
3379
3379
3380 # multiple tags for a single parent separated by '/'
3380 # multiple tags for a single parent separated by '/'
3381 t = '/'.join(ctx.tags())
3381 t = '/'.join(ctx.tags())
3382 if t:
3382 if t:
3383 output.append(t)
3383 output.append(t)
3384
3384
3385 # multiple bookmarks for a single parent separated by '/'
3385 # multiple bookmarks for a single parent separated by '/'
3386 bm = '/'.join(ctx.bookmarks())
3386 bm = '/'.join(ctx.bookmarks())
3387 if bm:
3387 if bm:
3388 output.append(bm)
3388 output.append(bm)
3389 else:
3389 else:
3390 if branch:
3390 if branch:
3391 output.append(ctx.branch())
3391 output.append(ctx.branch())
3392
3392
3393 if tags:
3393 if tags:
3394 output.extend(ctx.tags())
3394 output.extend(ctx.tags())
3395
3395
3396 if bookmarks:
3396 if bookmarks:
3397 output.extend(ctx.bookmarks())
3397 output.extend(ctx.bookmarks())
3398
3398
3399 ui.write("%s\n" % ' '.join(output))
3399 ui.write("%s\n" % ' '.join(output))
3400
3400
3401 @command('import|patch',
3401 @command('import|patch',
3402 [('p', 'strip', 1,
3402 [('p', 'strip', 1,
3403 _('directory strip option for patch. This has the same '
3403 _('directory strip option for patch. This has the same '
3404 'meaning as the corresponding patch option'), _('NUM')),
3404 'meaning as the corresponding patch option'), _('NUM')),
3405 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3405 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3406 ('e', 'edit', False, _('invoke editor on commit messages')),
3406 ('e', 'edit', False, _('invoke editor on commit messages')),
3407 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3407 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3408 ('', 'no-commit', None,
3408 ('', 'no-commit', None,
3409 _("don't commit, just update the working directory")),
3409 _("don't commit, just update the working directory")),
3410 ('', 'bypass', None,
3410 ('', 'bypass', None,
3411 _("apply patch without touching the working directory")),
3411 _("apply patch without touching the working directory")),
3412 ('', 'exact', None,
3412 ('', 'exact', None,
3413 _('apply patch to the nodes from which it was generated')),
3413 _('apply patch to the nodes from which it was generated')),
3414 ('', 'import-branch', None,
3414 ('', 'import-branch', None,
3415 _('use any branch information in patch (implied by --exact)'))] +
3415 _('use any branch information in patch (implied by --exact)'))] +
3416 commitopts + commitopts2 + similarityopts,
3416 commitopts + commitopts2 + similarityopts,
3417 _('[OPTION]... PATCH...'))
3417 _('[OPTION]... PATCH...'))
3418 def import_(ui, repo, patch1=None, *patches, **opts):
3418 def import_(ui, repo, patch1=None, *patches, **opts):
3419 """import an ordered set of patches
3419 """import an ordered set of patches
3420
3420
3421 Import a list of patches and commit them individually (unless
3421 Import a list of patches and commit them individually (unless
3422 --no-commit is specified).
3422 --no-commit is specified).
3423
3423
3424 If there are outstanding changes in the working directory, import
3424 If there are outstanding changes in the working directory, import
3425 will abort unless given the -f/--force flag.
3425 will abort unless given the -f/--force flag.
3426
3426
3427 You can import a patch straight from a mail message. Even patches
3427 You can import a patch straight from a mail message. Even patches
3428 as attachments work (to use the body part, it must have type
3428 as attachments work (to use the body part, it must have type
3429 text/plain or text/x-patch). From and Subject headers of email
3429 text/plain or text/x-patch). From and Subject headers of email
3430 message are used as default committer and commit message. All
3430 message are used as default committer and commit message. All
3431 text/plain body parts before first diff are added to commit
3431 text/plain body parts before first diff are added to commit
3432 message.
3432 message.
3433
3433
3434 If the imported patch was generated by :hg:`export`, user and
3434 If the imported patch was generated by :hg:`export`, user and
3435 description from patch override values from message headers and
3435 description from patch override values from message headers and
3436 body. Values given on command line with -m/--message and -u/--user
3436 body. Values given on command line with -m/--message and -u/--user
3437 override these.
3437 override these.
3438
3438
3439 If --exact is specified, import will set the working directory to
3439 If --exact is specified, import will set the working directory to
3440 the parent of each patch before applying it, and will abort if the
3440 the parent of each patch before applying it, and will abort if the
3441 resulting changeset has a different ID than the one recorded in
3441 resulting changeset has a different ID than the one recorded in
3442 the patch. This may happen due to character set problems or other
3442 the patch. This may happen due to character set problems or other
3443 deficiencies in the text patch format.
3443 deficiencies in the text patch format.
3444
3444
3445 Use --bypass to apply and commit patches directly to the
3445 Use --bypass to apply and commit patches directly to the
3446 repository, not touching the working directory. Without --exact,
3446 repository, not touching the working directory. Without --exact,
3447 patches will be applied on top of the working directory parent
3447 patches will be applied on top of the working directory parent
3448 revision.
3448 revision.
3449
3449
3450 With -s/--similarity, hg will attempt to discover renames and
3450 With -s/--similarity, hg will attempt to discover renames and
3451 copies in the patch in the same way as :hg:`addremove`.
3451 copies in the patch in the same way as :hg:`addremove`.
3452
3452
3453 To read a patch from standard input, use "-" as the patch name. If
3453 To read a patch from standard input, use "-" as the patch name. If
3454 a URL is specified, the patch will be downloaded from it.
3454 a URL is specified, the patch will be downloaded from it.
3455 See :hg:`help dates` for a list of formats valid for -d/--date.
3455 See :hg:`help dates` for a list of formats valid for -d/--date.
3456
3456
3457 .. container:: verbose
3457 .. container:: verbose
3458
3458
3459 Examples:
3459 Examples:
3460
3460
3461 - import a traditional patch from a website and detect renames::
3461 - import a traditional patch from a website and detect renames::
3462
3462
3463 hg import -s 80 http://example.com/bugfix.patch
3463 hg import -s 80 http://example.com/bugfix.patch
3464
3464
3465 - import a changeset from an hgweb server::
3465 - import a changeset from an hgweb server::
3466
3466
3467 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3467 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3468
3468
3469 - import all the patches in an Unix-style mbox::
3469 - import all the patches in an Unix-style mbox::
3470
3470
3471 hg import incoming-patches.mbox
3471 hg import incoming-patches.mbox
3472
3472
3473 - attempt to exactly restore an exported changeset (not always
3473 - attempt to exactly restore an exported changeset (not always
3474 possible)::
3474 possible)::
3475
3475
3476 hg import --exact proposed-fix.patch
3476 hg import --exact proposed-fix.patch
3477
3477
3478 Returns 0 on success.
3478 Returns 0 on success.
3479 """
3479 """
3480
3480
3481 if not patch1:
3481 if not patch1:
3482 raise util.Abort(_('need at least one patch to import'))
3482 raise util.Abort(_('need at least one patch to import'))
3483
3483
3484 patches = (patch1,) + patches
3484 patches = (patch1,) + patches
3485
3485
3486 date = opts.get('date')
3486 date = opts.get('date')
3487 if date:
3487 if date:
3488 opts['date'] = util.parsedate(date)
3488 opts['date'] = util.parsedate(date)
3489
3489
3490 editor = cmdutil.commiteditor
3490 editor = cmdutil.commiteditor
3491 if opts.get('edit'):
3491 if opts.get('edit'):
3492 editor = cmdutil.commitforceeditor
3492 editor = cmdutil.commitforceeditor
3493
3493
3494 update = not opts.get('bypass')
3494 update = not opts.get('bypass')
3495 if not update and opts.get('no_commit'):
3495 if not update and opts.get('no_commit'):
3496 raise util.Abort(_('cannot use --no-commit with --bypass'))
3496 raise util.Abort(_('cannot use --no-commit with --bypass'))
3497 try:
3497 try:
3498 sim = float(opts.get('similarity') or 0)
3498 sim = float(opts.get('similarity') or 0)
3499 except ValueError:
3499 except ValueError:
3500 raise util.Abort(_('similarity must be a number'))
3500 raise util.Abort(_('similarity must be a number'))
3501 if sim < 0 or sim > 100:
3501 if sim < 0 or sim > 100:
3502 raise util.Abort(_('similarity must be between 0 and 100'))
3502 raise util.Abort(_('similarity must be between 0 and 100'))
3503 if sim and not update:
3503 if sim and not update:
3504 raise util.Abort(_('cannot use --similarity with --bypass'))
3504 raise util.Abort(_('cannot use --similarity with --bypass'))
3505
3505
3506 if (opts.get('exact') or not opts.get('force')) and update:
3506 if (opts.get('exact') or not opts.get('force')) and update:
3507 cmdutil.bailifchanged(repo)
3507 cmdutil.bailifchanged(repo)
3508
3508
3509 base = opts["base"]
3509 base = opts["base"]
3510 strip = opts["strip"]
3510 strip = opts["strip"]
3511 wlock = lock = tr = None
3511 wlock = lock = tr = None
3512 msgs = []
3512 msgs = []
3513
3513
3514 def checkexact(repo, n, nodeid):
3514 def checkexact(repo, n, nodeid):
3515 if opts.get('exact') and hex(n) != nodeid:
3515 if opts.get('exact') and hex(n) != nodeid:
3516 repo.rollback()
3516 repo.rollback()
3517 raise util.Abort(_('patch is damaged or loses information'))
3517 raise util.Abort(_('patch is damaged or loses information'))
3518
3518
3519 def tryone(ui, hunk, parents):
3519 def tryone(ui, hunk, parents):
3520 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3520 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3521 patch.extract(ui, hunk)
3521 patch.extract(ui, hunk)
3522
3522
3523 if not tmpname:
3523 if not tmpname:
3524 return (None, None)
3524 return (None, None)
3525 msg = _('applied to working directory')
3525 msg = _('applied to working directory')
3526
3526
3527 try:
3527 try:
3528 cmdline_message = cmdutil.logmessage(ui, opts)
3528 cmdline_message = cmdutil.logmessage(ui, opts)
3529 if cmdline_message:
3529 if cmdline_message:
3530 # pickup the cmdline msg
3530 # pickup the cmdline msg
3531 message = cmdline_message
3531 message = cmdline_message
3532 elif message:
3532 elif message:
3533 # pickup the patch msg
3533 # pickup the patch msg
3534 message = message.strip()
3534 message = message.strip()
3535 else:
3535 else:
3536 # launch the editor
3536 # launch the editor
3537 message = None
3537 message = None
3538 ui.debug('message:\n%s\n' % message)
3538 ui.debug('message:\n%s\n' % message)
3539
3539
3540 if len(parents) == 1:
3540 if len(parents) == 1:
3541 parents.append(repo[nullid])
3541 parents.append(repo[nullid])
3542 if opts.get('exact'):
3542 if opts.get('exact'):
3543 if not nodeid or not p1:
3543 if not nodeid or not p1:
3544 raise util.Abort(_('not a Mercurial patch'))
3544 raise util.Abort(_('not a Mercurial patch'))
3545 p1 = repo[p1]
3545 p1 = repo[p1]
3546 p2 = repo[p2 or nullid]
3546 p2 = repo[p2 or nullid]
3547 elif p2:
3547 elif p2:
3548 try:
3548 try:
3549 p1 = repo[p1]
3549 p1 = repo[p1]
3550 p2 = repo[p2]
3550 p2 = repo[p2]
3551 # Without any options, consider p2 only if the
3551 # Without any options, consider p2 only if the
3552 # patch is being applied on top of the recorded
3552 # patch is being applied on top of the recorded
3553 # first parent.
3553 # first parent.
3554 if p1 != parents[0]:
3554 if p1 != parents[0]:
3555 p1 = parents[0]
3555 p1 = parents[0]
3556 p2 = repo[nullid]
3556 p2 = repo[nullid]
3557 except error.RepoError:
3557 except error.RepoError:
3558 p1, p2 = parents
3558 p1, p2 = parents
3559 else:
3559 else:
3560 p1, p2 = parents
3560 p1, p2 = parents
3561
3561
3562 n = None
3562 n = None
3563 if update:
3563 if update:
3564 if p1 != parents[0]:
3564 if p1 != parents[0]:
3565 hg.clean(repo, p1.node())
3565 hg.clean(repo, p1.node())
3566 if p2 != parents[1]:
3566 if p2 != parents[1]:
3567 repo.dirstate.setparents(p1.node(), p2.node())
3567 repo.dirstate.setparents(p1.node(), p2.node())
3568
3568
3569 if opts.get('exact') or opts.get('import_branch'):
3569 if opts.get('exact') or opts.get('import_branch'):
3570 repo.dirstate.setbranch(branch or 'default')
3570 repo.dirstate.setbranch(branch or 'default')
3571
3571
3572 files = set()
3572 files = set()
3573 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3573 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3574 eolmode=None, similarity=sim / 100.0)
3574 eolmode=None, similarity=sim / 100.0)
3575 files = list(files)
3575 files = list(files)
3576 if opts.get('no_commit'):
3576 if opts.get('no_commit'):
3577 if message:
3577 if message:
3578 msgs.append(message)
3578 msgs.append(message)
3579 else:
3579 else:
3580 if opts.get('exact') or p2:
3580 if opts.get('exact') or p2:
3581 # If you got here, you either use --force and know what
3581 # If you got here, you either use --force and know what
3582 # you are doing or used --exact or a merge patch while
3582 # you are doing or used --exact or a merge patch while
3583 # being updated to its first parent.
3583 # being updated to its first parent.
3584 m = None
3584 m = None
3585 else:
3585 else:
3586 m = scmutil.matchfiles(repo, files or [])
3586 m = scmutil.matchfiles(repo, files or [])
3587 n = repo.commit(message, opts.get('user') or user,
3587 n = repo.commit(message, opts.get('user') or user,
3588 opts.get('date') or date, match=m,
3588 opts.get('date') or date, match=m,
3589 editor=editor)
3589 editor=editor)
3590 checkexact(repo, n, nodeid)
3590 checkexact(repo, n, nodeid)
3591 else:
3591 else:
3592 if opts.get('exact') or opts.get('import_branch'):
3592 if opts.get('exact') or opts.get('import_branch'):
3593 branch = branch or 'default'
3593 branch = branch or 'default'
3594 else:
3594 else:
3595 branch = p1.branch()
3595 branch = p1.branch()
3596 store = patch.filestore()
3596 store = patch.filestore()
3597 try:
3597 try:
3598 files = set()
3598 files = set()
3599 try:
3599 try:
3600 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3600 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3601 files, eolmode=None)
3601 files, eolmode=None)
3602 except patch.PatchError, e:
3602 except patch.PatchError, e:
3603 raise util.Abort(str(e))
3603 raise util.Abort(str(e))
3604 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3604 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3605 message,
3605 message,
3606 opts.get('user') or user,
3606 opts.get('user') or user,
3607 opts.get('date') or date,
3607 opts.get('date') or date,
3608 branch, files, store,
3608 branch, files, store,
3609 editor=cmdutil.commiteditor)
3609 editor=cmdutil.commiteditor)
3610 repo.savecommitmessage(memctx.description())
3610 repo.savecommitmessage(memctx.description())
3611 n = memctx.commit()
3611 n = memctx.commit()
3612 checkexact(repo, n, nodeid)
3612 checkexact(repo, n, nodeid)
3613 finally:
3613 finally:
3614 store.close()
3614 store.close()
3615 if n:
3615 if n:
3616 # i18n: refers to a short changeset id
3616 # i18n: refers to a short changeset id
3617 msg = _('created %s') % short(n)
3617 msg = _('created %s') % short(n)
3618 return (msg, n)
3618 return (msg, n)
3619 finally:
3619 finally:
3620 os.unlink(tmpname)
3620 os.unlink(tmpname)
3621
3621
3622 try:
3622 try:
3623 try:
3623 try:
3624 wlock = repo.wlock()
3624 wlock = repo.wlock()
3625 if not opts.get('no_commit'):
3625 if not opts.get('no_commit'):
3626 lock = repo.lock()
3626 lock = repo.lock()
3627 tr = repo.transaction('import')
3627 tr = repo.transaction('import')
3628 parents = repo.parents()
3628 parents = repo.parents()
3629 for patchurl in patches:
3629 for patchurl in patches:
3630 if patchurl == '-':
3630 if patchurl == '-':
3631 ui.status(_('applying patch from stdin\n'))
3631 ui.status(_('applying patch from stdin\n'))
3632 patchfile = ui.fin
3632 patchfile = ui.fin
3633 patchurl = 'stdin' # for error message
3633 patchurl = 'stdin' # for error message
3634 else:
3634 else:
3635 patchurl = os.path.join(base, patchurl)
3635 patchurl = os.path.join(base, patchurl)
3636 ui.status(_('applying %s\n') % patchurl)
3636 ui.status(_('applying %s\n') % patchurl)
3637 patchfile = url.open(ui, patchurl)
3637 patchfile = url.open(ui, patchurl)
3638
3638
3639 haspatch = False
3639 haspatch = False
3640 for hunk in patch.split(patchfile):
3640 for hunk in patch.split(patchfile):
3641 (msg, node) = tryone(ui, hunk, parents)
3641 (msg, node) = tryone(ui, hunk, parents)
3642 if msg:
3642 if msg:
3643 haspatch = True
3643 haspatch = True
3644 ui.note(msg + '\n')
3644 ui.note(msg + '\n')
3645 if update or opts.get('exact'):
3645 if update or opts.get('exact'):
3646 parents = repo.parents()
3646 parents = repo.parents()
3647 else:
3647 else:
3648 parents = [repo[node]]
3648 parents = [repo[node]]
3649
3649
3650 if not haspatch:
3650 if not haspatch:
3651 raise util.Abort(_('%s: no diffs found') % patchurl)
3651 raise util.Abort(_('%s: no diffs found') % patchurl)
3652
3652
3653 if tr:
3653 if tr:
3654 tr.close()
3654 tr.close()
3655 if msgs:
3655 if msgs:
3656 repo.savecommitmessage('\n* * *\n'.join(msgs))
3656 repo.savecommitmessage('\n* * *\n'.join(msgs))
3657 except:
3657 except:
3658 # wlock.release() indirectly calls dirstate.write(): since
3658 # wlock.release() indirectly calls dirstate.write(): since
3659 # we're crashing, we do not want to change the working dir
3659 # we're crashing, we do not want to change the working dir
3660 # parent after all, so make sure it writes nothing
3660 # parent after all, so make sure it writes nothing
3661 repo.dirstate.invalidate()
3661 repo.dirstate.invalidate()
3662 raise
3662 raise
3663 finally:
3663 finally:
3664 if tr:
3664 if tr:
3665 tr.release()
3665 tr.release()
3666 release(lock, wlock)
3666 release(lock, wlock)
3667
3667
3668 @command('incoming|in',
3668 @command('incoming|in',
3669 [('f', 'force', None,
3669 [('f', 'force', None,
3670 _('run even if remote repository is unrelated')),
3670 _('run even if remote repository is unrelated')),
3671 ('n', 'newest-first', None, _('show newest record first')),
3671 ('n', 'newest-first', None, _('show newest record first')),
3672 ('', 'bundle', '',
3672 ('', 'bundle', '',
3673 _('file to store the bundles into'), _('FILE')),
3673 _('file to store the bundles into'), _('FILE')),
3674 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3674 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3675 ('B', 'bookmarks', False, _("compare bookmarks")),
3675 ('B', 'bookmarks', False, _("compare bookmarks")),
3676 ('b', 'branch', [],
3676 ('b', 'branch', [],
3677 _('a specific branch you would like to pull'), _('BRANCH')),
3677 _('a specific branch you would like to pull'), _('BRANCH')),
3678 ] + logopts + remoteopts + subrepoopts,
3678 ] + logopts + remoteopts + subrepoopts,
3679 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3679 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3680 def incoming(ui, repo, source="default", **opts):
3680 def incoming(ui, repo, source="default", **opts):
3681 """show new changesets found in source
3681 """show new changesets found in source
3682
3682
3683 Show new changesets found in the specified path/URL or the default
3683 Show new changesets found in the specified path/URL or the default
3684 pull location. These are the changesets that would have been pulled
3684 pull location. These are the changesets that would have been pulled
3685 if a pull at the time you issued this command.
3685 if a pull at the time you issued this command.
3686
3686
3687 For remote repository, using --bundle avoids downloading the
3687 For remote repository, using --bundle avoids downloading the
3688 changesets twice if the incoming is followed by a pull.
3688 changesets twice if the incoming is followed by a pull.
3689
3689
3690 See pull for valid source format details.
3690 See pull for valid source format details.
3691
3691
3692 Returns 0 if there are incoming changes, 1 otherwise.
3692 Returns 0 if there are incoming changes, 1 otherwise.
3693 """
3693 """
3694 if opts.get('bundle') and opts.get('subrepos'):
3694 if opts.get('bundle') and opts.get('subrepos'):
3695 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3695 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3696
3696
3697 if opts.get('bookmarks'):
3697 if opts.get('bookmarks'):
3698 source, branches = hg.parseurl(ui.expandpath(source),
3698 source, branches = hg.parseurl(ui.expandpath(source),
3699 opts.get('branch'))
3699 opts.get('branch'))
3700 other = hg.peer(repo, opts, source)
3700 other = hg.peer(repo, opts, source)
3701 if 'bookmarks' not in other.listkeys('namespaces'):
3701 if 'bookmarks' not in other.listkeys('namespaces'):
3702 ui.warn(_("remote doesn't support bookmarks\n"))
3702 ui.warn(_("remote doesn't support bookmarks\n"))
3703 return 0
3703 return 0
3704 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3704 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3705 return bookmarks.diff(ui, repo, other)
3705 return bookmarks.diff(ui, repo, other)
3706
3706
3707 repo._subtoppath = ui.expandpath(source)
3707 repo._subtoppath = ui.expandpath(source)
3708 try:
3708 try:
3709 return hg.incoming(ui, repo, source, opts)
3709 return hg.incoming(ui, repo, source, opts)
3710 finally:
3710 finally:
3711 del repo._subtoppath
3711 del repo._subtoppath
3712
3712
3713
3713
3714 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3714 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3715 def init(ui, dest=".", **opts):
3715 def init(ui, dest=".", **opts):
3716 """create a new repository in the given directory
3716 """create a new repository in the given directory
3717
3717
3718 Initialize a new repository in the given directory. If the given
3718 Initialize a new repository in the given directory. If the given
3719 directory does not exist, it will be created.
3719 directory does not exist, it will be created.
3720
3720
3721 If no directory is given, the current directory is used.
3721 If no directory is given, the current directory is used.
3722
3722
3723 It is possible to specify an ``ssh://`` URL as the destination.
3723 It is possible to specify an ``ssh://`` URL as the destination.
3724 See :hg:`help urls` for more information.
3724 See :hg:`help urls` for more information.
3725
3725
3726 Returns 0 on success.
3726 Returns 0 on success.
3727 """
3727 """
3728 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3728 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3729
3729
3730 @command('locate',
3730 @command('locate',
3731 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3731 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3732 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3732 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3733 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3733 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3734 ] + walkopts,
3734 ] + walkopts,
3735 _('[OPTION]... [PATTERN]...'))
3735 _('[OPTION]... [PATTERN]...'))
3736 def locate(ui, repo, *pats, **opts):
3736 def locate(ui, repo, *pats, **opts):
3737 """locate files matching specific patterns
3737 """locate files matching specific patterns
3738
3738
3739 Print files under Mercurial control in the working directory whose
3739 Print files under Mercurial control in the working directory whose
3740 names match the given patterns.
3740 names match the given patterns.
3741
3741
3742 By default, this command searches all directories in the working
3742 By default, this command searches all directories in the working
3743 directory. To search just the current directory and its
3743 directory. To search just the current directory and its
3744 subdirectories, use "--include .".
3744 subdirectories, use "--include .".
3745
3745
3746 If no patterns are given to match, this command prints the names
3746 If no patterns are given to match, this command prints the names
3747 of all files under Mercurial control in the working directory.
3747 of all files under Mercurial control in the working directory.
3748
3748
3749 If you want to feed the output of this command into the "xargs"
3749 If you want to feed the output of this command into the "xargs"
3750 command, use the -0 option to both this command and "xargs". This
3750 command, use the -0 option to both this command and "xargs". This
3751 will avoid the problem of "xargs" treating single filenames that
3751 will avoid the problem of "xargs" treating single filenames that
3752 contain whitespace as multiple filenames.
3752 contain whitespace as multiple filenames.
3753
3753
3754 Returns 0 if a match is found, 1 otherwise.
3754 Returns 0 if a match is found, 1 otherwise.
3755 """
3755 """
3756 end = opts.get('print0') and '\0' or '\n'
3756 end = opts.get('print0') and '\0' or '\n'
3757 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3757 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3758
3758
3759 ret = 1
3759 ret = 1
3760 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3760 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3761 m.bad = lambda x, y: False
3761 m.bad = lambda x, y: False
3762 for abs in repo[rev].walk(m):
3762 for abs in repo[rev].walk(m):
3763 if not rev and abs not in repo.dirstate:
3763 if not rev and abs not in repo.dirstate:
3764 continue
3764 continue
3765 if opts.get('fullpath'):
3765 if opts.get('fullpath'):
3766 ui.write(repo.wjoin(abs), end)
3766 ui.write(repo.wjoin(abs), end)
3767 else:
3767 else:
3768 ui.write(((pats and m.rel(abs)) or abs), end)
3768 ui.write(((pats and m.rel(abs)) or abs), end)
3769 ret = 0
3769 ret = 0
3770
3770
3771 return ret
3771 return ret
3772
3772
3773 @command('^log|history',
3773 @command('^log|history',
3774 [('f', 'follow', None,
3774 [('f', 'follow', None,
3775 _('follow changeset history, or file history across copies and renames')),
3775 _('follow changeset history, or file history across copies and renames')),
3776 ('', 'follow-first', None,
3776 ('', 'follow-first', None,
3777 _('only follow the first parent of merge changesets (DEPRECATED)')),
3777 _('only follow the first parent of merge changesets (DEPRECATED)')),
3778 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3778 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3779 ('C', 'copies', None, _('show copied files')),
3779 ('C', 'copies', None, _('show copied files')),
3780 ('k', 'keyword', [],
3780 ('k', 'keyword', [],
3781 _('do case-insensitive search for a given text'), _('TEXT')),
3781 _('do case-insensitive search for a given text'), _('TEXT')),
3782 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3782 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3783 ('', 'removed', None, _('include revisions where files were removed')),
3783 ('', 'removed', None, _('include revisions where files were removed')),
3784 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3784 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3785 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3785 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3786 ('', 'only-branch', [],
3786 ('', 'only-branch', [],
3787 _('show only changesets within the given named branch (DEPRECATED)'),
3787 _('show only changesets within the given named branch (DEPRECATED)'),
3788 _('BRANCH')),
3788 _('BRANCH')),
3789 ('b', 'branch', [],
3789 ('b', 'branch', [],
3790 _('show changesets within the given named branch'), _('BRANCH')),
3790 _('show changesets within the given named branch'), _('BRANCH')),
3791 ('P', 'prune', [],
3791 ('P', 'prune', [],
3792 _('do not display revision or any of its ancestors'), _('REV')),
3792 _('do not display revision or any of its ancestors'), _('REV')),
3793 ('', 'hidden', False, _('show hidden changesets (DEPRECATED)')),
3793 ('', 'hidden', False, _('show hidden changesets (DEPRECATED)')),
3794 ] + logopts + walkopts,
3794 ] + logopts + walkopts,
3795 _('[OPTION]... [FILE]'))
3795 _('[OPTION]... [FILE]'))
3796 def log(ui, repo, *pats, **opts):
3796 def log(ui, repo, *pats, **opts):
3797 """show revision history of entire repository or files
3797 """show revision history of entire repository or files
3798
3798
3799 Print the revision history of the specified files or the entire
3799 Print the revision history of the specified files or the entire
3800 project.
3800 project.
3801
3801
3802 If no revision range is specified, the default is ``tip:0`` unless
3802 If no revision range is specified, the default is ``tip:0`` unless
3803 --follow is set, in which case the working directory parent is
3803 --follow is set, in which case the working directory parent is
3804 used as the starting revision.
3804 used as the starting revision.
3805
3805
3806 File history is shown without following rename or copy history of
3806 File history is shown without following rename or copy history of
3807 files. Use -f/--follow with a filename to follow history across
3807 files. Use -f/--follow with a filename to follow history across
3808 renames and copies. --follow without a filename will only show
3808 renames and copies. --follow without a filename will only show
3809 ancestors or descendants of the starting revision.
3809 ancestors or descendants of the starting revision.
3810
3810
3811 By default this command prints revision number and changeset id,
3811 By default this command prints revision number and changeset id,
3812 tags, non-trivial parents, user, date and time, and a summary for
3812 tags, non-trivial parents, user, date and time, and a summary for
3813 each commit. When the -v/--verbose switch is used, the list of
3813 each commit. When the -v/--verbose switch is used, the list of
3814 changed files and full commit message are shown.
3814 changed files and full commit message are shown.
3815
3815
3816 .. note::
3816 .. note::
3817 log -p/--patch may generate unexpected diff output for merge
3817 log -p/--patch may generate unexpected diff output for merge
3818 changesets, as it will only compare the merge changeset against
3818 changesets, as it will only compare the merge changeset against
3819 its first parent. Also, only files different from BOTH parents
3819 its first parent. Also, only files different from BOTH parents
3820 will appear in files:.
3820 will appear in files:.
3821
3821
3822 .. note::
3822 .. note::
3823 for performance reasons, log FILE may omit duplicate changes
3823 for performance reasons, log FILE may omit duplicate changes
3824 made on branches and will not show deletions. To see all
3824 made on branches and will not show deletions. To see all
3825 changes including duplicates and deletions, use the --removed
3825 changes including duplicates and deletions, use the --removed
3826 switch.
3826 switch.
3827
3827
3828 .. container:: verbose
3828 .. container:: verbose
3829
3829
3830 Some examples:
3830 Some examples:
3831
3831
3832 - changesets with full descriptions and file lists::
3832 - changesets with full descriptions and file lists::
3833
3833
3834 hg log -v
3834 hg log -v
3835
3835
3836 - changesets ancestral to the working directory::
3836 - changesets ancestral to the working directory::
3837
3837
3838 hg log -f
3838 hg log -f
3839
3839
3840 - last 10 commits on the current branch::
3840 - last 10 commits on the current branch::
3841
3841
3842 hg log -l 10 -b .
3842 hg log -l 10 -b .
3843
3843
3844 - changesets showing all modifications of a file, including removals::
3844 - changesets showing all modifications of a file, including removals::
3845
3845
3846 hg log --removed file.c
3846 hg log --removed file.c
3847
3847
3848 - all changesets that touch a directory, with diffs, excluding merges::
3848 - all changesets that touch a directory, with diffs, excluding merges::
3849
3849
3850 hg log -Mp lib/
3850 hg log -Mp lib/
3851
3851
3852 - all revision numbers that match a keyword::
3852 - all revision numbers that match a keyword::
3853
3853
3854 hg log -k bug --template "{rev}\\n"
3854 hg log -k bug --template "{rev}\\n"
3855
3855
3856 - check if a given changeset is included is a tagged release::
3856 - check if a given changeset is included is a tagged release::
3857
3857
3858 hg log -r "a21ccf and ancestor(1.9)"
3858 hg log -r "a21ccf and ancestor(1.9)"
3859
3859
3860 - find all changesets by some user in a date range::
3860 - find all changesets by some user in a date range::
3861
3861
3862 hg log -k alice -d "may 2008 to jul 2008"
3862 hg log -k alice -d "may 2008 to jul 2008"
3863
3863
3864 - summary of all changesets after the last tag::
3864 - summary of all changesets after the last tag::
3865
3865
3866 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3866 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3867
3867
3868 See :hg:`help dates` for a list of formats valid for -d/--date.
3868 See :hg:`help dates` for a list of formats valid for -d/--date.
3869
3869
3870 See :hg:`help revisions` and :hg:`help revsets` for more about
3870 See :hg:`help revisions` and :hg:`help revsets` for more about
3871 specifying revisions.
3871 specifying revisions.
3872
3872
3873 Returns 0 on success.
3873 Returns 0 on success.
3874 """
3874 """
3875
3875
3876 matchfn = scmutil.match(repo[None], pats, opts)
3876 matchfn = scmutil.match(repo[None], pats, opts)
3877 limit = cmdutil.loglimit(opts)
3877 limit = cmdutil.loglimit(opts)
3878 count = 0
3878 count = 0
3879
3879
3880 getrenamed, endrev = None, None
3880 getrenamed, endrev = None, None
3881 if opts.get('copies'):
3881 if opts.get('copies'):
3882 if opts.get('rev'):
3882 if opts.get('rev'):
3883 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3883 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3884 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3884 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3885
3885
3886 df = False
3886 df = False
3887 if opts["date"]:
3887 if opts["date"]:
3888 df = util.matchdate(opts["date"])
3888 df = util.matchdate(opts["date"])
3889
3889
3890 branches = opts.get('branch', []) + opts.get('only_branch', [])
3890 branches = opts.get('branch', []) + opts.get('only_branch', [])
3891 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3891 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3892
3892
3893 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3893 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3894 def prep(ctx, fns):
3894 def prep(ctx, fns):
3895 rev = ctx.rev()
3895 rev = ctx.rev()
3896 parents = [p for p in repo.changelog.parentrevs(rev)
3896 parents = [p for p in repo.changelog.parentrevs(rev)
3897 if p != nullrev]
3897 if p != nullrev]
3898 if opts.get('no_merges') and len(parents) == 2:
3898 if opts.get('no_merges') and len(parents) == 2:
3899 return
3899 return
3900 if opts.get('only_merges') and len(parents) != 2:
3900 if opts.get('only_merges') and len(parents) != 2:
3901 return
3901 return
3902 if opts.get('branch') and ctx.branch() not in opts['branch']:
3902 if opts.get('branch') and ctx.branch() not in opts['branch']:
3903 return
3903 return
3904 if not opts.get('hidden') and ctx.hidden():
3904 if not opts.get('hidden') and ctx.hidden():
3905 return
3905 return
3906 if df and not df(ctx.date()[0]):
3906 if df and not df(ctx.date()[0]):
3907 return
3907 return
3908
3908
3909 lower = encoding.lower
3909 lower = encoding.lower
3910 if opts.get('user'):
3910 if opts.get('user'):
3911 luser = lower(ctx.user())
3911 luser = lower(ctx.user())
3912 for k in [lower(x) for x in opts['user']]:
3912 for k in [lower(x) for x in opts['user']]:
3913 if (k in luser):
3913 if (k in luser):
3914 break
3914 break
3915 else:
3915 else:
3916 return
3916 return
3917 if opts.get('keyword'):
3917 if opts.get('keyword'):
3918 luser = lower(ctx.user())
3918 luser = lower(ctx.user())
3919 ldesc = lower(ctx.description())
3919 ldesc = lower(ctx.description())
3920 lfiles = lower(" ".join(ctx.files()))
3920 lfiles = lower(" ".join(ctx.files()))
3921 for k in [lower(x) for x in opts['keyword']]:
3921 for k in [lower(x) for x in opts['keyword']]:
3922 if (k in luser or k in ldesc or k in lfiles):
3922 if (k in luser or k in ldesc or k in lfiles):
3923 break
3923 break
3924 else:
3924 else:
3925 return
3925 return
3926
3926
3927 copies = None
3927 copies = None
3928 if getrenamed is not None and rev:
3928 if getrenamed is not None and rev:
3929 copies = []
3929 copies = []
3930 for fn in ctx.files():
3930 for fn in ctx.files():
3931 rename = getrenamed(fn, rev)
3931 rename = getrenamed(fn, rev)
3932 if rename:
3932 if rename:
3933 copies.append((fn, rename[0]))
3933 copies.append((fn, rename[0]))
3934
3934
3935 revmatchfn = None
3935 revmatchfn = None
3936 if opts.get('patch') or opts.get('stat'):
3936 if opts.get('patch') or opts.get('stat'):
3937 if opts.get('follow') or opts.get('follow_first'):
3937 if opts.get('follow') or opts.get('follow_first'):
3938 # note: this might be wrong when following through merges
3938 # note: this might be wrong when following through merges
3939 revmatchfn = scmutil.match(repo[None], fns, default='path')
3939 revmatchfn = scmutil.match(repo[None], fns, default='path')
3940 else:
3940 else:
3941 revmatchfn = matchfn
3941 revmatchfn = matchfn
3942
3942
3943 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3943 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3944
3944
3945 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3945 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3946 if count == limit:
3946 if count == limit:
3947 break
3947 break
3948 if displayer.flush(ctx.rev()):
3948 if displayer.flush(ctx.rev()):
3949 count += 1
3949 count += 1
3950 displayer.close()
3950 displayer.close()
3951
3951
3952 @command('manifest',
3952 @command('manifest',
3953 [('r', 'rev', '', _('revision to display'), _('REV')),
3953 [('r', 'rev', '', _('revision to display'), _('REV')),
3954 ('', 'all', False, _("list files from all revisions"))],
3954 ('', 'all', False, _("list files from all revisions"))],
3955 _('[-r REV]'))
3955 _('[-r REV]'))
3956 def manifest(ui, repo, node=None, rev=None, **opts):
3956 def manifest(ui, repo, node=None, rev=None, **opts):
3957 """output the current or given revision of the project manifest
3957 """output the current or given revision of the project manifest
3958
3958
3959 Print a list of version controlled files for the given revision.
3959 Print a list of version controlled files for the given revision.
3960 If no revision is given, the first parent of the working directory
3960 If no revision is given, the first parent of the working directory
3961 is used, or the null revision if no revision is checked out.
3961 is used, or the null revision if no revision is checked out.
3962
3962
3963 With -v, print file permissions, symlink and executable bits.
3963 With -v, print file permissions, symlink and executable bits.
3964 With --debug, print file revision hashes.
3964 With --debug, print file revision hashes.
3965
3965
3966 If option --all is specified, the list of all files from all revisions
3966 If option --all is specified, the list of all files from all revisions
3967 is printed. This includes deleted and renamed files.
3967 is printed. This includes deleted and renamed files.
3968
3968
3969 Returns 0 on success.
3969 Returns 0 on success.
3970 """
3970 """
3971 if opts.get('all'):
3971 if opts.get('all'):
3972 if rev or node:
3972 if rev or node:
3973 raise util.Abort(_("can't specify a revision with --all"))
3973 raise util.Abort(_("can't specify a revision with --all"))
3974
3974
3975 res = []
3975 res = []
3976 prefix = "data/"
3976 prefix = "data/"
3977 suffix = ".i"
3977 suffix = ".i"
3978 plen = len(prefix)
3978 plen = len(prefix)
3979 slen = len(suffix)
3979 slen = len(suffix)
3980 lock = repo.lock()
3980 lock = repo.lock()
3981 try:
3981 try:
3982 for fn, b, size in repo.store.datafiles():
3982 for fn, b, size in repo.store.datafiles():
3983 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3983 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3984 res.append(fn[plen:-slen])
3984 res.append(fn[plen:-slen])
3985 finally:
3985 finally:
3986 lock.release()
3986 lock.release()
3987 for f in sorted(res):
3987 for f in sorted(res):
3988 ui.write("%s\n" % f)
3988 ui.write("%s\n" % f)
3989 return
3989 return
3990
3990
3991 if rev and node:
3991 if rev and node:
3992 raise util.Abort(_("please specify just one revision"))
3992 raise util.Abort(_("please specify just one revision"))
3993
3993
3994 if not node:
3994 if not node:
3995 node = rev
3995 node = rev
3996
3996
3997 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3997 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3998 ctx = scmutil.revsingle(repo, node)
3998 ctx = scmutil.revsingle(repo, node)
3999 for f in ctx:
3999 for f in ctx:
4000 if ui.debugflag:
4000 if ui.debugflag:
4001 ui.write("%40s " % hex(ctx.manifest()[f]))
4001 ui.write("%40s " % hex(ctx.manifest()[f]))
4002 if ui.verbose:
4002 if ui.verbose:
4003 ui.write(decor[ctx.flags(f)])
4003 ui.write(decor[ctx.flags(f)])
4004 ui.write("%s\n" % f)
4004 ui.write("%s\n" % f)
4005
4005
4006 @command('^merge',
4006 @command('^merge',
4007 [('f', 'force', None, _('force a merge with outstanding changes')),
4007 [('f', 'force', None, _('force a merge with outstanding changes')),
4008 ('r', 'rev', '', _('revision to merge'), _('REV')),
4008 ('r', 'rev', '', _('revision to merge'), _('REV')),
4009 ('P', 'preview', None,
4009 ('P', 'preview', None,
4010 _('review revisions to merge (no merge is performed)'))
4010 _('review revisions to merge (no merge is performed)'))
4011 ] + mergetoolopts,
4011 ] + mergetoolopts,
4012 _('[-P] [-f] [[-r] REV]'))
4012 _('[-P] [-f] [[-r] REV]'))
4013 def merge(ui, repo, node=None, **opts):
4013 def merge(ui, repo, node=None, **opts):
4014 """merge working directory with another revision
4014 """merge working directory with another revision
4015
4015
4016 The current working directory is updated with all changes made in
4016 The current working directory is updated with all changes made in
4017 the requested revision since the last common predecessor revision.
4017 the requested revision since the last common predecessor revision.
4018
4018
4019 Files that changed between either parent are marked as changed for
4019 Files that changed between either parent are marked as changed for
4020 the next commit and a commit must be performed before any further
4020 the next commit and a commit must be performed before any further
4021 updates to the repository are allowed. The next commit will have
4021 updates to the repository are allowed. The next commit will have
4022 two parents.
4022 two parents.
4023
4023
4024 ``--tool`` can be used to specify the merge tool used for file
4024 ``--tool`` can be used to specify the merge tool used for file
4025 merges. It overrides the HGMERGE environment variable and your
4025 merges. It overrides the HGMERGE environment variable and your
4026 configuration files. See :hg:`help merge-tools` for options.
4026 configuration files. See :hg:`help merge-tools` for options.
4027
4027
4028 If no revision is specified, the working directory's parent is a
4028 If no revision is specified, the working directory's parent is a
4029 head revision, and the current branch contains exactly one other
4029 head revision, and the current branch contains exactly one other
4030 head, the other head is merged with by default. Otherwise, an
4030 head, the other head is merged with by default. Otherwise, an
4031 explicit revision with which to merge with must be provided.
4031 explicit revision with which to merge with must be provided.
4032
4032
4033 :hg:`resolve` must be used to resolve unresolved files.
4033 :hg:`resolve` must be used to resolve unresolved files.
4034
4034
4035 To undo an uncommitted merge, use :hg:`update --clean .` which
4035 To undo an uncommitted merge, use :hg:`update --clean .` which
4036 will check out a clean copy of the original merge parent, losing
4036 will check out a clean copy of the original merge parent, losing
4037 all changes.
4037 all changes.
4038
4038
4039 Returns 0 on success, 1 if there are unresolved files.
4039 Returns 0 on success, 1 if there are unresolved files.
4040 """
4040 """
4041
4041
4042 if opts.get('rev') and node:
4042 if opts.get('rev') and node:
4043 raise util.Abort(_("please specify just one revision"))
4043 raise util.Abort(_("please specify just one revision"))
4044 if not node:
4044 if not node:
4045 node = opts.get('rev')
4045 node = opts.get('rev')
4046
4046
4047 if not node:
4047 if not node:
4048 branch = repo[None].branch()
4048 branch = repo[None].branch()
4049 bheads = repo.branchheads(branch)
4049 bheads = repo.branchheads(branch)
4050 if len(bheads) > 2:
4050 if len(bheads) > 2:
4051 raise util.Abort(_("branch '%s' has %d heads - "
4051 raise util.Abort(_("branch '%s' has %d heads - "
4052 "please merge with an explicit rev")
4052 "please merge with an explicit rev")
4053 % (branch, len(bheads)),
4053 % (branch, len(bheads)),
4054 hint=_("run 'hg heads .' to see heads"))
4054 hint=_("run 'hg heads .' to see heads"))
4055
4055
4056 parent = repo.dirstate.p1()
4056 parent = repo.dirstate.p1()
4057 if len(bheads) == 1:
4057 if len(bheads) == 1:
4058 if len(repo.heads()) > 1:
4058 if len(repo.heads()) > 1:
4059 raise util.Abort(_("branch '%s' has one head - "
4059 raise util.Abort(_("branch '%s' has one head - "
4060 "please merge with an explicit rev")
4060 "please merge with an explicit rev")
4061 % branch,
4061 % branch,
4062 hint=_("run 'hg heads' to see all heads"))
4062 hint=_("run 'hg heads' to see all heads"))
4063 msg, hint = _('nothing to merge'), None
4063 msg, hint = _('nothing to merge'), None
4064 if parent != repo.lookup(branch):
4064 if parent != repo.lookup(branch):
4065 hint = _("use 'hg update' instead")
4065 hint = _("use 'hg update' instead")
4066 raise util.Abort(msg, hint=hint)
4066 raise util.Abort(msg, hint=hint)
4067
4067
4068 if parent not in bheads:
4068 if parent not in bheads:
4069 raise util.Abort(_('working directory not at a head revision'),
4069 raise util.Abort(_('working directory not at a head revision'),
4070 hint=_("use 'hg update' or merge with an "
4070 hint=_("use 'hg update' or merge with an "
4071 "explicit revision"))
4071 "explicit revision"))
4072 node = parent == bheads[0] and bheads[-1] or bheads[0]
4072 node = parent == bheads[0] and bheads[-1] or bheads[0]
4073 else:
4073 else:
4074 node = scmutil.revsingle(repo, node).node()
4074 node = scmutil.revsingle(repo, node).node()
4075
4075
4076 if opts.get('preview'):
4076 if opts.get('preview'):
4077 # find nodes that are ancestors of p2 but not of p1
4077 # find nodes that are ancestors of p2 but not of p1
4078 p1 = repo.lookup('.')
4078 p1 = repo.lookup('.')
4079 p2 = repo.lookup(node)
4079 p2 = repo.lookup(node)
4080 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4080 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4081
4081
4082 displayer = cmdutil.show_changeset(ui, repo, opts)
4082 displayer = cmdutil.show_changeset(ui, repo, opts)
4083 for node in nodes:
4083 for node in nodes:
4084 displayer.show(repo[node])
4084 displayer.show(repo[node])
4085 displayer.close()
4085 displayer.close()
4086 return 0
4086 return 0
4087
4087
4088 try:
4088 try:
4089 # ui.forcemerge is an internal variable, do not document
4089 # ui.forcemerge is an internal variable, do not document
4090 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4090 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4091 return hg.merge(repo, node, force=opts.get('force'))
4091 return hg.merge(repo, node, force=opts.get('force'))
4092 finally:
4092 finally:
4093 ui.setconfig('ui', 'forcemerge', '')
4093 ui.setconfig('ui', 'forcemerge', '')
4094
4094
4095 @command('outgoing|out',
4095 @command('outgoing|out',
4096 [('f', 'force', None, _('run even when the destination is unrelated')),
4096 [('f', 'force', None, _('run even when the destination is unrelated')),
4097 ('r', 'rev', [],
4097 ('r', 'rev', [],
4098 _('a changeset intended to be included in the destination'), _('REV')),
4098 _('a changeset intended to be included in the destination'), _('REV')),
4099 ('n', 'newest-first', None, _('show newest record first')),
4099 ('n', 'newest-first', None, _('show newest record first')),
4100 ('B', 'bookmarks', False, _('compare bookmarks')),
4100 ('B', 'bookmarks', False, _('compare bookmarks')),
4101 ('b', 'branch', [], _('a specific branch you would like to push'),
4101 ('b', 'branch', [], _('a specific branch you would like to push'),
4102 _('BRANCH')),
4102 _('BRANCH')),
4103 ] + logopts + remoteopts + subrepoopts,
4103 ] + logopts + remoteopts + subrepoopts,
4104 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4104 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4105 def outgoing(ui, repo, dest=None, **opts):
4105 def outgoing(ui, repo, dest=None, **opts):
4106 """show changesets not found in the destination
4106 """show changesets not found in the destination
4107
4107
4108 Show changesets not found in the specified destination repository
4108 Show changesets not found in the specified destination repository
4109 or the default push location. These are the changesets that would
4109 or the default push location. These are the changesets that would
4110 be pushed if a push was requested.
4110 be pushed if a push was requested.
4111
4111
4112 See pull for details of valid destination formats.
4112 See pull for details of valid destination formats.
4113
4113
4114 Returns 0 if there are outgoing changes, 1 otherwise.
4114 Returns 0 if there are outgoing changes, 1 otherwise.
4115 """
4115 """
4116
4116
4117 if opts.get('bookmarks'):
4117 if opts.get('bookmarks'):
4118 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4118 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4119 dest, branches = hg.parseurl(dest, opts.get('branch'))
4119 dest, branches = hg.parseurl(dest, opts.get('branch'))
4120 other = hg.peer(repo, opts, dest)
4120 other = hg.peer(repo, opts, dest)
4121 if 'bookmarks' not in other.listkeys('namespaces'):
4121 if 'bookmarks' not in other.listkeys('namespaces'):
4122 ui.warn(_("remote doesn't support bookmarks\n"))
4122 ui.warn(_("remote doesn't support bookmarks\n"))
4123 return 0
4123 return 0
4124 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4124 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4125 return bookmarks.diff(ui, other, repo)
4125 return bookmarks.diff(ui, other, repo)
4126
4126
4127 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4127 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4128 try:
4128 try:
4129 return hg.outgoing(ui, repo, dest, opts)
4129 return hg.outgoing(ui, repo, dest, opts)
4130 finally:
4130 finally:
4131 del repo._subtoppath
4131 del repo._subtoppath
4132
4132
4133 @command('parents',
4133 @command('parents',
4134 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4134 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4135 ] + templateopts,
4135 ] + templateopts,
4136 _('[-r REV] [FILE]'))
4136 _('[-r REV] [FILE]'))
4137 def parents(ui, repo, file_=None, **opts):
4137 def parents(ui, repo, file_=None, **opts):
4138 """show the parents of the working directory or revision
4138 """show the parents of the working directory or revision
4139
4139
4140 Print the working directory's parent revisions. If a revision is
4140 Print the working directory's parent revisions. If a revision is
4141 given via -r/--rev, the parent of that revision will be printed.
4141 given via -r/--rev, the parent of that revision will be printed.
4142 If a file argument is given, the revision in which the file was
4142 If a file argument is given, the revision in which the file was
4143 last changed (before the working directory revision or the
4143 last changed (before the working directory revision or the
4144 argument to --rev if given) is printed.
4144 argument to --rev if given) is printed.
4145
4145
4146 Returns 0 on success.
4146 Returns 0 on success.
4147 """
4147 """
4148
4148
4149 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4149 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4150
4150
4151 if file_:
4151 if file_:
4152 m = scmutil.match(ctx, (file_,), opts)
4152 m = scmutil.match(ctx, (file_,), opts)
4153 if m.anypats() or len(m.files()) != 1:
4153 if m.anypats() or len(m.files()) != 1:
4154 raise util.Abort(_('can only specify an explicit filename'))
4154 raise util.Abort(_('can only specify an explicit filename'))
4155 file_ = m.files()[0]
4155 file_ = m.files()[0]
4156 filenodes = []
4156 filenodes = []
4157 for cp in ctx.parents():
4157 for cp in ctx.parents():
4158 if not cp:
4158 if not cp:
4159 continue
4159 continue
4160 try:
4160 try:
4161 filenodes.append(cp.filenode(file_))
4161 filenodes.append(cp.filenode(file_))
4162 except error.LookupError:
4162 except error.LookupError:
4163 pass
4163 pass
4164 if not filenodes:
4164 if not filenodes:
4165 raise util.Abort(_("'%s' not found in manifest!") % file_)
4165 raise util.Abort(_("'%s' not found in manifest!") % file_)
4166 fl = repo.file(file_)
4166 fl = repo.file(file_)
4167 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
4167 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
4168 else:
4168 else:
4169 p = [cp.node() for cp in ctx.parents()]
4169 p = [cp.node() for cp in ctx.parents()]
4170
4170
4171 displayer = cmdutil.show_changeset(ui, repo, opts)
4171 displayer = cmdutil.show_changeset(ui, repo, opts)
4172 for n in p:
4172 for n in p:
4173 if n != nullid:
4173 if n != nullid:
4174 displayer.show(repo[n])
4174 displayer.show(repo[n])
4175 displayer.close()
4175 displayer.close()
4176
4176
4177 @command('paths', [], _('[NAME]'))
4177 @command('paths', [], _('[NAME]'))
4178 def paths(ui, repo, search=None):
4178 def paths(ui, repo, search=None):
4179 """show aliases for remote repositories
4179 """show aliases for remote repositories
4180
4180
4181 Show definition of symbolic path name NAME. If no name is given,
4181 Show definition of symbolic path name NAME. If no name is given,
4182 show definition of all available names.
4182 show definition of all available names.
4183
4183
4184 Option -q/--quiet suppresses all output when searching for NAME
4184 Option -q/--quiet suppresses all output when searching for NAME
4185 and shows only the path names when listing all definitions.
4185 and shows only the path names when listing all definitions.
4186
4186
4187 Path names are defined in the [paths] section of your
4187 Path names are defined in the [paths] section of your
4188 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4188 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4189 repository, ``.hg/hgrc`` is used, too.
4189 repository, ``.hg/hgrc`` is used, too.
4190
4190
4191 The path names ``default`` and ``default-push`` have a special
4191 The path names ``default`` and ``default-push`` have a special
4192 meaning. When performing a push or pull operation, they are used
4192 meaning. When performing a push or pull operation, they are used
4193 as fallbacks if no location is specified on the command-line.
4193 as fallbacks if no location is specified on the command-line.
4194 When ``default-push`` is set, it will be used for push and
4194 When ``default-push`` is set, it will be used for push and
4195 ``default`` will be used for pull; otherwise ``default`` is used
4195 ``default`` will be used for pull; otherwise ``default`` is used
4196 as the fallback for both. When cloning a repository, the clone
4196 as the fallback for both. When cloning a repository, the clone
4197 source is written as ``default`` in ``.hg/hgrc``. Note that
4197 source is written as ``default`` in ``.hg/hgrc``. Note that
4198 ``default`` and ``default-push`` apply to all inbound (e.g.
4198 ``default`` and ``default-push`` apply to all inbound (e.g.
4199 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4199 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4200 :hg:`bundle`) operations.
4200 :hg:`bundle`) operations.
4201
4201
4202 See :hg:`help urls` for more information.
4202 See :hg:`help urls` for more information.
4203
4203
4204 Returns 0 on success.
4204 Returns 0 on success.
4205 """
4205 """
4206 if search:
4206 if search:
4207 for name, path in ui.configitems("paths"):
4207 for name, path in ui.configitems("paths"):
4208 if name == search:
4208 if name == search:
4209 ui.status("%s\n" % util.hidepassword(path))
4209 ui.status("%s\n" % util.hidepassword(path))
4210 return
4210 return
4211 if not ui.quiet:
4211 if not ui.quiet:
4212 ui.warn(_("not found!\n"))
4212 ui.warn(_("not found!\n"))
4213 return 1
4213 return 1
4214 else:
4214 else:
4215 for name, path in ui.configitems("paths"):
4215 for name, path in ui.configitems("paths"):
4216 if ui.quiet:
4216 if ui.quiet:
4217 ui.write("%s\n" % name)
4217 ui.write("%s\n" % name)
4218 else:
4218 else:
4219 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4219 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4220
4220
4221 @command('^phase',
4221 @command('^phase',
4222 [('p', 'public', False, _('set changeset phase to public')),
4222 [('p', 'public', False, _('set changeset phase to public')),
4223 ('d', 'draft', False, _('set changeset phase to draft')),
4223 ('d', 'draft', False, _('set changeset phase to draft')),
4224 ('s', 'secret', False, _('set changeset phase to secret')),
4224 ('s', 'secret', False, _('set changeset phase to secret')),
4225 ('f', 'force', False, _('allow to move boundary backward')),
4225 ('f', 'force', False, _('allow to move boundary backward')),
4226 ('r', 'rev', [], _('target revision'), _('REV')),
4226 ('r', 'rev', [], _('target revision'), _('REV')),
4227 ],
4227 ],
4228 _('[-p|-d|-s] [-f] [-r] REV...'))
4228 _('[-p|-d|-s] [-f] [-r] REV...'))
4229 def phase(ui, repo, *revs, **opts):
4229 def phase(ui, repo, *revs, **opts):
4230 """set or show the current phase name
4230 """set or show the current phase name
4231
4231
4232 With no argument, show the phase name of specified revisions.
4232 With no argument, show the phase name of specified revisions.
4233
4233
4234 With one of -p/--public, -d/--draft or -s/--secret, change the
4234 With one of -p/--public, -d/--draft or -s/--secret, change the
4235 phase value of the specified revisions.
4235 phase value of the specified revisions.
4236
4236
4237 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4237 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4238 lower phase to an higher phase. Phases are ordered as follows::
4238 lower phase to an higher phase. Phases are ordered as follows::
4239
4239
4240 public < draft < secret
4240 public < draft < secret
4241
4241
4242 Return 0 on success, 1 if no phases were changed or some could not
4242 Return 0 on success, 1 if no phases were changed or some could not
4243 be changed.
4243 be changed.
4244 """
4244 """
4245 # search for a unique phase argument
4245 # search for a unique phase argument
4246 targetphase = None
4246 targetphase = None
4247 for idx, name in enumerate(phases.phasenames):
4247 for idx, name in enumerate(phases.phasenames):
4248 if opts[name]:
4248 if opts[name]:
4249 if targetphase is not None:
4249 if targetphase is not None:
4250 raise util.Abort(_('only one phase can be specified'))
4250 raise util.Abort(_('only one phase can be specified'))
4251 targetphase = idx
4251 targetphase = idx
4252
4252
4253 # look for specified revision
4253 # look for specified revision
4254 revs = list(revs)
4254 revs = list(revs)
4255 revs.extend(opts['rev'])
4255 revs.extend(opts['rev'])
4256 if not revs:
4256 if not revs:
4257 raise util.Abort(_('no revisions specified'))
4257 raise util.Abort(_('no revisions specified'))
4258
4258
4259 revs = scmutil.revrange(repo, revs)
4259 revs = scmutil.revrange(repo, revs)
4260
4260
4261 lock = None
4261 lock = None
4262 ret = 0
4262 ret = 0
4263 if targetphase is None:
4263 if targetphase is None:
4264 # display
4264 # display
4265 for r in revs:
4265 for r in revs:
4266 ctx = repo[r]
4266 ctx = repo[r]
4267 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4267 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4268 else:
4268 else:
4269 lock = repo.lock()
4269 lock = repo.lock()
4270 try:
4270 try:
4271 # set phase
4271 # set phase
4272 nodes = [ctx.node() for ctx in repo.set('%ld', revs)]
4272 nodes = [ctx.node() for ctx in repo.set('%ld', revs)]
4273 if not nodes:
4273 if not nodes:
4274 raise util.Abort(_('empty revision set'))
4274 raise util.Abort(_('empty revision set'))
4275 olddata = repo._phaserev[:]
4275 olddata = repo._phaserev[:]
4276 phases.advanceboundary(repo, targetphase, nodes)
4276 phases.advanceboundary(repo, targetphase, nodes)
4277 if opts['force']:
4277 if opts['force']:
4278 phases.retractboundary(repo, targetphase, nodes)
4278 phases.retractboundary(repo, targetphase, nodes)
4279 finally:
4279 finally:
4280 lock.release()
4280 lock.release()
4281 if olddata is not None:
4281 if olddata is not None:
4282 changes = 0
4282 changes = 0
4283 newdata = repo._phaserev
4283 newdata = repo._phaserev
4284 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4284 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4285 rejected = [n for n in nodes
4285 rejected = [n for n in nodes
4286 if newdata[repo[n].rev()] < targetphase]
4286 if newdata[repo[n].rev()] < targetphase]
4287 if rejected:
4287 if rejected:
4288 ui.warn(_('cannot move %i changesets to a more permissive '
4288 ui.warn(_('cannot move %i changesets to a more permissive '
4289 'phase, use --force\n') % len(rejected))
4289 'phase, use --force\n') % len(rejected))
4290 ret = 1
4290 ret = 1
4291 if changes:
4291 if changes:
4292 msg = _('phase changed for %i changesets\n') % changes
4292 msg = _('phase changed for %i changesets\n') % changes
4293 if ret:
4293 if ret:
4294 ui.status(msg)
4294 ui.status(msg)
4295 else:
4295 else:
4296 ui.note(msg)
4296 ui.note(msg)
4297 else:
4297 else:
4298 ui.warn(_('no phases changed\n'))
4298 ui.warn(_('no phases changed\n'))
4299 ret = 1
4299 ret = 1
4300 return ret
4300 return ret
4301
4301
4302 def postincoming(ui, repo, modheads, optupdate, checkout):
4302 def postincoming(ui, repo, modheads, optupdate, checkout):
4303 if modheads == 0:
4303 if modheads == 0:
4304 return
4304 return
4305 if optupdate:
4305 if optupdate:
4306 movemarkfrom = repo['.'].node()
4306 movemarkfrom = repo['.'].node()
4307 try:
4307 try:
4308 ret = hg.update(repo, checkout)
4308 ret = hg.update(repo, checkout)
4309 except util.Abort, inst:
4309 except util.Abort, inst:
4310 ui.warn(_("not updating: %s\n") % str(inst))
4310 ui.warn(_("not updating: %s\n") % str(inst))
4311 return 0
4311 return 0
4312 if not ret and not checkout:
4312 if not ret and not checkout:
4313 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4313 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4314 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4314 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4315 return ret
4315 return ret
4316 if modheads > 1:
4316 if modheads > 1:
4317 currentbranchheads = len(repo.branchheads())
4317 currentbranchheads = len(repo.branchheads())
4318 if currentbranchheads == modheads:
4318 if currentbranchheads == modheads:
4319 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4319 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4320 elif currentbranchheads > 1:
4320 elif currentbranchheads > 1:
4321 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
4321 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
4322 else:
4322 else:
4323 ui.status(_("(run 'hg heads' to see heads)\n"))
4323 ui.status(_("(run 'hg heads' to see heads)\n"))
4324 else:
4324 else:
4325 ui.status(_("(run 'hg update' to get a working copy)\n"))
4325 ui.status(_("(run 'hg update' to get a working copy)\n"))
4326
4326
4327 @command('^pull',
4327 @command('^pull',
4328 [('u', 'update', None,
4328 [('u', 'update', None,
4329 _('update to new branch head if changesets were pulled')),
4329 _('update to new branch head if changesets were pulled')),
4330 ('f', 'force', None, _('run even when remote repository is unrelated')),
4330 ('f', 'force', None, _('run even when remote repository is unrelated')),
4331 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4331 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4332 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4332 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4333 ('b', 'branch', [], _('a specific branch you would like to pull'),
4333 ('b', 'branch', [], _('a specific branch you would like to pull'),
4334 _('BRANCH')),
4334 _('BRANCH')),
4335 ] + remoteopts,
4335 ] + remoteopts,
4336 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4336 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4337 def pull(ui, repo, source="default", **opts):
4337 def pull(ui, repo, source="default", **opts):
4338 """pull changes from the specified source
4338 """pull changes from the specified source
4339
4339
4340 Pull changes from a remote repository to a local one.
4340 Pull changes from a remote repository to a local one.
4341
4341
4342 This finds all changes from the repository at the specified path
4342 This finds all changes from the repository at the specified path
4343 or URL and adds them to a local repository (the current one unless
4343 or URL and adds them to a local repository (the current one unless
4344 -R is specified). By default, this does not update the copy of the
4344 -R is specified). By default, this does not update the copy of the
4345 project in the working directory.
4345 project in the working directory.
4346
4346
4347 Use :hg:`incoming` if you want to see what would have been added
4347 Use :hg:`incoming` if you want to see what would have been added
4348 by a pull at the time you issued this command. If you then decide
4348 by a pull at the time you issued this command. If you then decide
4349 to add those changes to the repository, you should use :hg:`pull
4349 to add those changes to the repository, you should use :hg:`pull
4350 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4350 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4351
4351
4352 If SOURCE is omitted, the 'default' path will be used.
4352 If SOURCE is omitted, the 'default' path will be used.
4353 See :hg:`help urls` for more information.
4353 See :hg:`help urls` for more information.
4354
4354
4355 Returns 0 on success, 1 if an update had unresolved files.
4355 Returns 0 on success, 1 if an update had unresolved files.
4356 """
4356 """
4357 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4357 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4358 other = hg.peer(repo, opts, source)
4358 other = hg.peer(repo, opts, source)
4359 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4359 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4360 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4360 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4361
4361
4362 if opts.get('bookmark'):
4362 if opts.get('bookmark'):
4363 if not revs:
4363 if not revs:
4364 revs = []
4364 revs = []
4365 rb = other.listkeys('bookmarks')
4365 rb = other.listkeys('bookmarks')
4366 for b in opts['bookmark']:
4366 for b in opts['bookmark']:
4367 if b not in rb:
4367 if b not in rb:
4368 raise util.Abort(_('remote bookmark %s not found!') % b)
4368 raise util.Abort(_('remote bookmark %s not found!') % b)
4369 revs.append(rb[b])
4369 revs.append(rb[b])
4370
4370
4371 if revs:
4371 if revs:
4372 try:
4372 try:
4373 revs = [other.lookup(rev) for rev in revs]
4373 revs = [other.lookup(rev) for rev in revs]
4374 except error.CapabilityError:
4374 except error.CapabilityError:
4375 err = _("other repository doesn't support revision lookup, "
4375 err = _("other repository doesn't support revision lookup, "
4376 "so a rev cannot be specified.")
4376 "so a rev cannot be specified.")
4377 raise util.Abort(err)
4377 raise util.Abort(err)
4378
4378
4379 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4379 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4380 bookmarks.updatefromremote(ui, repo, other, source)
4380 bookmarks.updatefromremote(ui, repo, other, source)
4381 if checkout:
4381 if checkout:
4382 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4382 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4383 repo._subtoppath = source
4383 repo._subtoppath = source
4384 try:
4384 try:
4385 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4385 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4386
4386
4387 finally:
4387 finally:
4388 del repo._subtoppath
4388 del repo._subtoppath
4389
4389
4390 # update specified bookmarks
4390 # update specified bookmarks
4391 if opts.get('bookmark'):
4391 if opts.get('bookmark'):
4392 for b in opts['bookmark']:
4392 for b in opts['bookmark']:
4393 # explicit pull overrides local bookmark if any
4393 # explicit pull overrides local bookmark if any
4394 ui.status(_("importing bookmark %s\n") % b)
4394 ui.status(_("importing bookmark %s\n") % b)
4395 repo._bookmarks[b] = repo[rb[b]].node()
4395 repo._bookmarks[b] = repo[rb[b]].node()
4396 bookmarks.write(repo)
4396 bookmarks.write(repo)
4397
4397
4398 return ret
4398 return ret
4399
4399
4400 @command('^push',
4400 @command('^push',
4401 [('f', 'force', None, _('force push')),
4401 [('f', 'force', None, _('force push')),
4402 ('r', 'rev', [],
4402 ('r', 'rev', [],
4403 _('a changeset intended to be included in the destination'),
4403 _('a changeset intended to be included in the destination'),
4404 _('REV')),
4404 _('REV')),
4405 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4405 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4406 ('b', 'branch', [],
4406 ('b', 'branch', [],
4407 _('a specific branch you would like to push'), _('BRANCH')),
4407 _('a specific branch you would like to push'), _('BRANCH')),
4408 ('', 'new-branch', False, _('allow pushing a new branch')),
4408 ('', 'new-branch', False, _('allow pushing a new branch')),
4409 ] + remoteopts,
4409 ] + remoteopts,
4410 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4410 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4411 def push(ui, repo, dest=None, **opts):
4411 def push(ui, repo, dest=None, **opts):
4412 """push changes to the specified destination
4412 """push changes to the specified destination
4413
4413
4414 Push changesets from the local repository to the specified
4414 Push changesets from the local repository to the specified
4415 destination.
4415 destination.
4416
4416
4417 This operation is symmetrical to pull: it is identical to a pull
4417 This operation is symmetrical to pull: it is identical to a pull
4418 in the destination repository from the current one.
4418 in the destination repository from the current one.
4419
4419
4420 By default, push will not allow creation of new heads at the
4420 By default, push will not allow creation of new heads at the
4421 destination, since multiple heads would make it unclear which head
4421 destination, since multiple heads would make it unclear which head
4422 to use. In this situation, it is recommended to pull and merge
4422 to use. In this situation, it is recommended to pull and merge
4423 before pushing.
4423 before pushing.
4424
4424
4425 Use --new-branch if you want to allow push to create a new named
4425 Use --new-branch if you want to allow push to create a new named
4426 branch that is not present at the destination. This allows you to
4426 branch that is not present at the destination. This allows you to
4427 only create a new branch without forcing other changes.
4427 only create a new branch without forcing other changes.
4428
4428
4429 Use -f/--force to override the default behavior and push all
4429 Use -f/--force to override the default behavior and push all
4430 changesets on all branches.
4430 changesets on all branches.
4431
4431
4432 If -r/--rev is used, the specified revision and all its ancestors
4432 If -r/--rev is used, the specified revision and all its ancestors
4433 will be pushed to the remote repository.
4433 will be pushed to the remote repository.
4434
4434
4435 Please see :hg:`help urls` for important details about ``ssh://``
4435 Please see :hg:`help urls` for important details about ``ssh://``
4436 URLs. If DESTINATION is omitted, a default path will be used.
4436 URLs. If DESTINATION is omitted, a default path will be used.
4437
4437
4438 Returns 0 if push was successful, 1 if nothing to push.
4438 Returns 0 if push was successful, 1 if nothing to push.
4439 """
4439 """
4440
4440
4441 if opts.get('bookmark'):
4441 if opts.get('bookmark'):
4442 for b in opts['bookmark']:
4442 for b in opts['bookmark']:
4443 # translate -B options to -r so changesets get pushed
4443 # translate -B options to -r so changesets get pushed
4444 if b in repo._bookmarks:
4444 if b in repo._bookmarks:
4445 opts.setdefault('rev', []).append(b)
4445 opts.setdefault('rev', []).append(b)
4446 else:
4446 else:
4447 # if we try to push a deleted bookmark, translate it to null
4447 # if we try to push a deleted bookmark, translate it to null
4448 # this lets simultaneous -r, -b options continue working
4448 # this lets simultaneous -r, -b options continue working
4449 opts.setdefault('rev', []).append("null")
4449 opts.setdefault('rev', []).append("null")
4450
4450
4451 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4451 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4452 dest, branches = hg.parseurl(dest, opts.get('branch'))
4452 dest, branches = hg.parseurl(dest, opts.get('branch'))
4453 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4453 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4454 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4454 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4455 other = hg.peer(repo, opts, dest)
4455 other = hg.peer(repo, opts, dest)
4456 if revs:
4456 if revs:
4457 revs = [repo.lookup(rev) for rev in revs]
4457 revs = [repo.lookup(rev) for rev in revs]
4458
4458
4459 repo._subtoppath = dest
4459 repo._subtoppath = dest
4460 try:
4460 try:
4461 # push subrepos depth-first for coherent ordering
4461 # push subrepos depth-first for coherent ordering
4462 c = repo['']
4462 c = repo['']
4463 subs = c.substate # only repos that are committed
4463 subs = c.substate # only repos that are committed
4464 for s in sorted(subs):
4464 for s in sorted(subs):
4465 if c.sub(s).push(opts) == 0:
4465 if c.sub(s).push(opts) == 0:
4466 return False
4466 return False
4467 finally:
4467 finally:
4468 del repo._subtoppath
4468 del repo._subtoppath
4469 result = repo.push(other, opts.get('force'), revs=revs,
4469 result = repo.push(other, opts.get('force'), revs=revs,
4470 newbranch=opts.get('new_branch'))
4470 newbranch=opts.get('new_branch'))
4471
4471
4472 result = not result
4472 result = not result
4473
4473
4474 if opts.get('bookmark'):
4474 if opts.get('bookmark'):
4475 rb = other.listkeys('bookmarks')
4475 rb = other.listkeys('bookmarks')
4476 for b in opts['bookmark']:
4476 for b in opts['bookmark']:
4477 # explicit push overrides remote bookmark if any
4477 # explicit push overrides remote bookmark if any
4478 if b in repo._bookmarks:
4478 if b in repo._bookmarks:
4479 ui.status(_("exporting bookmark %s\n") % b)
4479 ui.status(_("exporting bookmark %s\n") % b)
4480 new = repo[b].hex()
4480 new = repo[b].hex()
4481 elif b in rb:
4481 elif b in rb:
4482 ui.status(_("deleting remote bookmark %s\n") % b)
4482 ui.status(_("deleting remote bookmark %s\n") % b)
4483 new = '' # delete
4483 new = '' # delete
4484 else:
4484 else:
4485 ui.warn(_('bookmark %s does not exist on the local '
4485 ui.warn(_('bookmark %s does not exist on the local '
4486 'or remote repository!\n') % b)
4486 'or remote repository!\n') % b)
4487 return 2
4487 return 2
4488 old = rb.get(b, '')
4488 old = rb.get(b, '')
4489 r = other.pushkey('bookmarks', b, old, new)
4489 r = other.pushkey('bookmarks', b, old, new)
4490 if not r:
4490 if not r:
4491 ui.warn(_('updating bookmark %s failed!\n') % b)
4491 ui.warn(_('updating bookmark %s failed!\n') % b)
4492 if not result:
4492 if not result:
4493 result = 2
4493 result = 2
4494
4494
4495 return result
4495 return result
4496
4496
4497 @command('recover', [])
4497 @command('recover', [])
4498 def recover(ui, repo):
4498 def recover(ui, repo):
4499 """roll back an interrupted transaction
4499 """roll back an interrupted transaction
4500
4500
4501 Recover from an interrupted commit or pull.
4501 Recover from an interrupted commit or pull.
4502
4502
4503 This command tries to fix the repository status after an
4503 This command tries to fix the repository status after an
4504 interrupted operation. It should only be necessary when Mercurial
4504 interrupted operation. It should only be necessary when Mercurial
4505 suggests it.
4505 suggests it.
4506
4506
4507 Returns 0 if successful, 1 if nothing to recover or verify fails.
4507 Returns 0 if successful, 1 if nothing to recover or verify fails.
4508 """
4508 """
4509 if repo.recover():
4509 if repo.recover():
4510 return hg.verify(repo)
4510 return hg.verify(repo)
4511 return 1
4511 return 1
4512
4512
4513 @command('^remove|rm',
4513 @command('^remove|rm',
4514 [('A', 'after', None, _('record delete for missing files')),
4514 [('A', 'after', None, _('record delete for missing files')),
4515 ('f', 'force', None,
4515 ('f', 'force', None,
4516 _('remove (and delete) file even if added or modified')),
4516 _('remove (and delete) file even if added or modified')),
4517 ] + walkopts,
4517 ] + walkopts,
4518 _('[OPTION]... FILE...'))
4518 _('[OPTION]... FILE...'))
4519 def remove(ui, repo, *pats, **opts):
4519 def remove(ui, repo, *pats, **opts):
4520 """remove the specified files on the next commit
4520 """remove the specified files on the next commit
4521
4521
4522 Schedule the indicated files for removal from the current branch.
4522 Schedule the indicated files for removal from the current branch.
4523
4523
4524 This command schedules the files to be removed at the next commit.
4524 This command schedules the files to be removed at the next commit.
4525 To undo a remove before that, see :hg:`revert`. To undo added
4525 To undo a remove before that, see :hg:`revert`. To undo added
4526 files, see :hg:`forget`.
4526 files, see :hg:`forget`.
4527
4527
4528 .. container:: verbose
4528 .. container:: verbose
4529
4529
4530 -A/--after can be used to remove only files that have already
4530 -A/--after can be used to remove only files that have already
4531 been deleted, -f/--force can be used to force deletion, and -Af
4531 been deleted, -f/--force can be used to force deletion, and -Af
4532 can be used to remove files from the next revision without
4532 can be used to remove files from the next revision without
4533 deleting them from the working directory.
4533 deleting them from the working directory.
4534
4534
4535 The following table details the behavior of remove for different
4535 The following table details the behavior of remove for different
4536 file states (columns) and option combinations (rows). The file
4536 file states (columns) and option combinations (rows). The file
4537 states are Added [A], Clean [C], Modified [M] and Missing [!]
4537 states are Added [A], Clean [C], Modified [M] and Missing [!]
4538 (as reported by :hg:`status`). The actions are Warn, Remove
4538 (as reported by :hg:`status`). The actions are Warn, Remove
4539 (from branch) and Delete (from disk):
4539 (from branch) and Delete (from disk):
4540
4540
4541 ======= == == == ==
4541 ======= == == == ==
4542 A C M !
4542 A C M !
4543 ======= == == == ==
4543 ======= == == == ==
4544 none W RD W R
4544 none W RD W R
4545 -f R RD RD R
4545 -f R RD RD R
4546 -A W W W R
4546 -A W W W R
4547 -Af R R R R
4547 -Af R R R R
4548 ======= == == == ==
4548 ======= == == == ==
4549
4549
4550 Note that remove never deletes files in Added [A] state from the
4550 Note that remove never deletes files in Added [A] state from the
4551 working directory, not even if option --force is specified.
4551 working directory, not even if option --force is specified.
4552
4552
4553 Returns 0 on success, 1 if any warnings encountered.
4553 Returns 0 on success, 1 if any warnings encountered.
4554 """
4554 """
4555
4555
4556 ret = 0
4556 ret = 0
4557 after, force = opts.get('after'), opts.get('force')
4557 after, force = opts.get('after'), opts.get('force')
4558 if not pats and not after:
4558 if not pats and not after:
4559 raise util.Abort(_('no files specified'))
4559 raise util.Abort(_('no files specified'))
4560
4560
4561 m = scmutil.match(repo[None], pats, opts)
4561 m = scmutil.match(repo[None], pats, opts)
4562 s = repo.status(match=m, clean=True)
4562 s = repo.status(match=m, clean=True)
4563 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4563 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4564
4564
4565 for f in m.files():
4565 for f in m.files():
4566 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
4566 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
4567 if os.path.exists(m.rel(f)):
4567 if os.path.exists(m.rel(f)):
4568 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4568 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4569 ret = 1
4569 ret = 1
4570
4570
4571 if force:
4571 if force:
4572 list = modified + deleted + clean + added
4572 list = modified + deleted + clean + added
4573 elif after:
4573 elif after:
4574 list = deleted
4574 list = deleted
4575 for f in modified + added + clean:
4575 for f in modified + added + clean:
4576 ui.warn(_('not removing %s: file still exists (use -f'
4576 ui.warn(_('not removing %s: file still exists (use -f'
4577 ' to force removal)\n') % m.rel(f))
4577 ' to force removal)\n') % m.rel(f))
4578 ret = 1
4578 ret = 1
4579 else:
4579 else:
4580 list = deleted + clean
4580 list = deleted + clean
4581 for f in modified:
4581 for f in modified:
4582 ui.warn(_('not removing %s: file is modified (use -f'
4582 ui.warn(_('not removing %s: file is modified (use -f'
4583 ' to force removal)\n') % m.rel(f))
4583 ' to force removal)\n') % m.rel(f))
4584 ret = 1
4584 ret = 1
4585 for f in added:
4585 for f in added:
4586 ui.warn(_('not removing %s: file has been marked for add'
4586 ui.warn(_('not removing %s: file has been marked for add'
4587 ' (use forget to undo)\n') % m.rel(f))
4587 ' (use forget to undo)\n') % m.rel(f))
4588 ret = 1
4588 ret = 1
4589
4589
4590 for f in sorted(list):
4590 for f in sorted(list):
4591 if ui.verbose or not m.exact(f):
4591 if ui.verbose or not m.exact(f):
4592 ui.status(_('removing %s\n') % m.rel(f))
4592 ui.status(_('removing %s\n') % m.rel(f))
4593
4593
4594 wlock = repo.wlock()
4594 wlock = repo.wlock()
4595 try:
4595 try:
4596 if not after:
4596 if not after:
4597 for f in list:
4597 for f in list:
4598 if f in added:
4598 if f in added:
4599 continue # we never unlink added files on remove
4599 continue # we never unlink added files on remove
4600 try:
4600 try:
4601 util.unlinkpath(repo.wjoin(f))
4601 util.unlinkpath(repo.wjoin(f))
4602 except OSError, inst:
4602 except OSError, inst:
4603 if inst.errno != errno.ENOENT:
4603 if inst.errno != errno.ENOENT:
4604 raise
4604 raise
4605 repo[None].forget(list)
4605 repo[None].forget(list)
4606 finally:
4606 finally:
4607 wlock.release()
4607 wlock.release()
4608
4608
4609 return ret
4609 return ret
4610
4610
4611 @command('rename|move|mv',
4611 @command('rename|move|mv',
4612 [('A', 'after', None, _('record a rename that has already occurred')),
4612 [('A', 'after', None, _('record a rename that has already occurred')),
4613 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4613 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4614 ] + walkopts + dryrunopts,
4614 ] + walkopts + dryrunopts,
4615 _('[OPTION]... SOURCE... DEST'))
4615 _('[OPTION]... SOURCE... DEST'))
4616 def rename(ui, repo, *pats, **opts):
4616 def rename(ui, repo, *pats, **opts):
4617 """rename files; equivalent of copy + remove
4617 """rename files; equivalent of copy + remove
4618
4618
4619 Mark dest as copies of sources; mark sources for deletion. If dest
4619 Mark dest as copies of sources; mark sources for deletion. If dest
4620 is a directory, copies are put in that directory. If dest is a
4620 is a directory, copies are put in that directory. If dest is a
4621 file, there can only be one source.
4621 file, there can only be one source.
4622
4622
4623 By default, this command copies the contents of files as they
4623 By default, this command copies the contents of files as they
4624 exist in the working directory. If invoked with -A/--after, the
4624 exist in the working directory. If invoked with -A/--after, the
4625 operation is recorded, but no copying is performed.
4625 operation is recorded, but no copying is performed.
4626
4626
4627 This command takes effect at the next commit. To undo a rename
4627 This command takes effect at the next commit. To undo a rename
4628 before that, see :hg:`revert`.
4628 before that, see :hg:`revert`.
4629
4629
4630 Returns 0 on success, 1 if errors are encountered.
4630 Returns 0 on success, 1 if errors are encountered.
4631 """
4631 """
4632 wlock = repo.wlock(False)
4632 wlock = repo.wlock(False)
4633 try:
4633 try:
4634 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4634 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4635 finally:
4635 finally:
4636 wlock.release()
4636 wlock.release()
4637
4637
4638 @command('resolve',
4638 @command('resolve',
4639 [('a', 'all', None, _('select all unresolved files')),
4639 [('a', 'all', None, _('select all unresolved files')),
4640 ('l', 'list', None, _('list state of files needing merge')),
4640 ('l', 'list', None, _('list state of files needing merge')),
4641 ('m', 'mark', None, _('mark files as resolved')),
4641 ('m', 'mark', None, _('mark files as resolved')),
4642 ('u', 'unmark', None, _('mark files as unresolved')),
4642 ('u', 'unmark', None, _('mark files as unresolved')),
4643 ('n', 'no-status', None, _('hide status prefix'))]
4643 ('n', 'no-status', None, _('hide status prefix'))]
4644 + mergetoolopts + walkopts,
4644 + mergetoolopts + walkopts,
4645 _('[OPTION]... [FILE]...'))
4645 _('[OPTION]... [FILE]...'))
4646 def resolve(ui, repo, *pats, **opts):
4646 def resolve(ui, repo, *pats, **opts):
4647 """redo merges or set/view the merge status of files
4647 """redo merges or set/view the merge status of files
4648
4648
4649 Merges with unresolved conflicts are often the result of
4649 Merges with unresolved conflicts are often the result of
4650 non-interactive merging using the ``internal:merge`` configuration
4650 non-interactive merging using the ``internal:merge`` configuration
4651 setting, or a command-line merge tool like ``diff3``. The resolve
4651 setting, or a command-line merge tool like ``diff3``. The resolve
4652 command is used to manage the files involved in a merge, after
4652 command is used to manage the files involved in a merge, after
4653 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4653 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4654 working directory must have two parents). See :hg:`help
4654 working directory must have two parents). See :hg:`help
4655 merge-tools` for information on configuring merge tools.
4655 merge-tools` for information on configuring merge tools.
4656
4656
4657 The resolve command can be used in the following ways:
4657 The resolve command can be used in the following ways:
4658
4658
4659 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4659 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4660 files, discarding any previous merge attempts. Re-merging is not
4660 files, discarding any previous merge attempts. Re-merging is not
4661 performed for files already marked as resolved. Use ``--all/-a``
4661 performed for files already marked as resolved. Use ``--all/-a``
4662 to select all unresolved files. ``--tool`` can be used to specify
4662 to select all unresolved files. ``--tool`` can be used to specify
4663 the merge tool used for the given files. It overrides the HGMERGE
4663 the merge tool used for the given files. It overrides the HGMERGE
4664 environment variable and your configuration files. Previous file
4664 environment variable and your configuration files. Previous file
4665 contents are saved with a ``.orig`` suffix.
4665 contents are saved with a ``.orig`` suffix.
4666
4666
4667 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4667 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4668 (e.g. after having manually fixed-up the files). The default is
4668 (e.g. after having manually fixed-up the files). The default is
4669 to mark all unresolved files.
4669 to mark all unresolved files.
4670
4670
4671 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4671 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4672 default is to mark all resolved files.
4672 default is to mark all resolved files.
4673
4673
4674 - :hg:`resolve -l`: list files which had or still have conflicts.
4674 - :hg:`resolve -l`: list files which had or still have conflicts.
4675 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4675 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4676
4676
4677 Note that Mercurial will not let you commit files with unresolved
4677 Note that Mercurial will not let you commit files with unresolved
4678 merge conflicts. You must use :hg:`resolve -m ...` before you can
4678 merge conflicts. You must use :hg:`resolve -m ...` before you can
4679 commit after a conflicting merge.
4679 commit after a conflicting merge.
4680
4680
4681 Returns 0 on success, 1 if any files fail a resolve attempt.
4681 Returns 0 on success, 1 if any files fail a resolve attempt.
4682 """
4682 """
4683
4683
4684 all, mark, unmark, show, nostatus = \
4684 all, mark, unmark, show, nostatus = \
4685 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4685 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4686
4686
4687 if (show and (mark or unmark)) or (mark and unmark):
4687 if (show and (mark or unmark)) or (mark and unmark):
4688 raise util.Abort(_("too many options specified"))
4688 raise util.Abort(_("too many options specified"))
4689 if pats and all:
4689 if pats and all:
4690 raise util.Abort(_("can't specify --all and patterns"))
4690 raise util.Abort(_("can't specify --all and patterns"))
4691 if not (all or pats or show or mark or unmark):
4691 if not (all or pats or show or mark or unmark):
4692 raise util.Abort(_('no files or directories specified; '
4692 raise util.Abort(_('no files or directories specified; '
4693 'use --all to remerge all files'))
4693 'use --all to remerge all files'))
4694
4694
4695 ms = mergemod.mergestate(repo)
4695 ms = mergemod.mergestate(repo)
4696 m = scmutil.match(repo[None], pats, opts)
4696 m = scmutil.match(repo[None], pats, opts)
4697 ret = 0
4697 ret = 0
4698
4698
4699 for f in ms:
4699 for f in ms:
4700 if m(f):
4700 if m(f):
4701 if show:
4701 if show:
4702 if nostatus:
4702 if nostatus:
4703 ui.write("%s\n" % f)
4703 ui.write("%s\n" % f)
4704 else:
4704 else:
4705 ui.write("%s %s\n" % (ms[f].upper(), f),
4705 ui.write("%s %s\n" % (ms[f].upper(), f),
4706 label='resolve.' +
4706 label='resolve.' +
4707 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4707 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4708 elif mark:
4708 elif mark:
4709 ms.mark(f, "r")
4709 ms.mark(f, "r")
4710 elif unmark:
4710 elif unmark:
4711 ms.mark(f, "u")
4711 ms.mark(f, "u")
4712 else:
4712 else:
4713 wctx = repo[None]
4713 wctx = repo[None]
4714 mctx = wctx.parents()[-1]
4714 mctx = wctx.parents()[-1]
4715
4715
4716 # backup pre-resolve (merge uses .orig for its own purposes)
4716 # backup pre-resolve (merge uses .orig for its own purposes)
4717 a = repo.wjoin(f)
4717 a = repo.wjoin(f)
4718 util.copyfile(a, a + ".resolve")
4718 util.copyfile(a, a + ".resolve")
4719
4719
4720 try:
4720 try:
4721 # resolve file
4721 # resolve file
4722 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4722 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4723 if ms.resolve(f, wctx, mctx):
4723 if ms.resolve(f, wctx, mctx):
4724 ret = 1
4724 ret = 1
4725 finally:
4725 finally:
4726 ui.setconfig('ui', 'forcemerge', '')
4726 ui.setconfig('ui', 'forcemerge', '')
4727
4727
4728 # replace filemerge's .orig file with our resolve file
4728 # replace filemerge's .orig file with our resolve file
4729 util.rename(a + ".resolve", a + ".orig")
4729 util.rename(a + ".resolve", a + ".orig")
4730
4730
4731 ms.commit()
4731 ms.commit()
4732 return ret
4732 return ret
4733
4733
4734 @command('revert',
4734 @command('revert',
4735 [('a', 'all', None, _('revert all changes when no arguments given')),
4735 [('a', 'all', None, _('revert all changes when no arguments given')),
4736 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4736 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4737 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4737 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4738 ('C', 'no-backup', None, _('do not save backup copies of files')),
4738 ('C', 'no-backup', None, _('do not save backup copies of files')),
4739 ] + walkopts + dryrunopts,
4739 ] + walkopts + dryrunopts,
4740 _('[OPTION]... [-r REV] [NAME]...'))
4740 _('[OPTION]... [-r REV] [NAME]...'))
4741 def revert(ui, repo, *pats, **opts):
4741 def revert(ui, repo, *pats, **opts):
4742 """restore files to their checkout state
4742 """restore files to their checkout state
4743
4743
4744 .. note::
4744 .. note::
4745 To check out earlier revisions, you should use :hg:`update REV`.
4745 To check out earlier revisions, you should use :hg:`update REV`.
4746 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4746 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4747
4747
4748 With no revision specified, revert the specified files or directories
4748 With no revision specified, revert the specified files or directories
4749 to the contents they had in the parent of the working directory.
4749 to the contents they had in the parent of the working directory.
4750 This restores the contents of files to an unmodified
4750 This restores the contents of files to an unmodified
4751 state and unschedules adds, removes, copies, and renames. If the
4751 state and unschedules adds, removes, copies, and renames. If the
4752 working directory has two parents, you must explicitly specify a
4752 working directory has two parents, you must explicitly specify a
4753 revision.
4753 revision.
4754
4754
4755 Using the -r/--rev or -d/--date options, revert the given files or
4755 Using the -r/--rev or -d/--date options, revert the given files or
4756 directories to their states as of a specific revision. Because
4756 directories to their states as of a specific revision. Because
4757 revert does not change the working directory parents, this will
4757 revert does not change the working directory parents, this will
4758 cause these files to appear modified. This can be helpful to "back
4758 cause these files to appear modified. This can be helpful to "back
4759 out" some or all of an earlier change. See :hg:`backout` for a
4759 out" some or all of an earlier change. See :hg:`backout` for a
4760 related method.
4760 related method.
4761
4761
4762 Modified files are saved with a .orig suffix before reverting.
4762 Modified files are saved with a .orig suffix before reverting.
4763 To disable these backups, use --no-backup.
4763 To disable these backups, use --no-backup.
4764
4764
4765 See :hg:`help dates` for a list of formats valid for -d/--date.
4765 See :hg:`help dates` for a list of formats valid for -d/--date.
4766
4766
4767 Returns 0 on success.
4767 Returns 0 on success.
4768 """
4768 """
4769
4769
4770 if opts.get("date"):
4770 if opts.get("date"):
4771 if opts.get("rev"):
4771 if opts.get("rev"):
4772 raise util.Abort(_("you can't specify a revision and a date"))
4772 raise util.Abort(_("you can't specify a revision and a date"))
4773 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4773 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4774
4774
4775 parent, p2 = repo.dirstate.parents()
4775 parent, p2 = repo.dirstate.parents()
4776 if not opts.get('rev') and p2 != nullid:
4776 if not opts.get('rev') and p2 != nullid:
4777 # revert after merge is a trap for new users (issue2915)
4777 # revert after merge is a trap for new users (issue2915)
4778 raise util.Abort(_('uncommitted merge with no revision specified'),
4778 raise util.Abort(_('uncommitted merge with no revision specified'),
4779 hint=_('use "hg update" or see "hg help revert"'))
4779 hint=_('use "hg update" or see "hg help revert"'))
4780
4780
4781 ctx = scmutil.revsingle(repo, opts.get('rev'))
4781 ctx = scmutil.revsingle(repo, opts.get('rev'))
4782
4782
4783 if not pats and not opts.get('all'):
4783 if not pats and not opts.get('all'):
4784 msg = _("no files or directories specified")
4784 msg = _("no files or directories specified")
4785 if p2 != nullid:
4785 if p2 != nullid:
4786 hint = _("uncommitted merge, use --all to discard all changes,"
4786 hint = _("uncommitted merge, use --all to discard all changes,"
4787 " or 'hg update -C .' to abort the merge")
4787 " or 'hg update -C .' to abort the merge")
4788 raise util.Abort(msg, hint=hint)
4788 raise util.Abort(msg, hint=hint)
4789 dirty = util.any(repo.status())
4789 dirty = util.any(repo.status())
4790 node = ctx.node()
4790 node = ctx.node()
4791 if node != parent:
4791 if node != parent:
4792 if dirty:
4792 if dirty:
4793 hint = _("uncommitted changes, use --all to discard all"
4793 hint = _("uncommitted changes, use --all to discard all"
4794 " changes, or 'hg update %s' to update") % ctx.rev()
4794 " changes, or 'hg update %s' to update") % ctx.rev()
4795 else:
4795 else:
4796 hint = _("use --all to revert all files,"
4796 hint = _("use --all to revert all files,"
4797 " or 'hg update %s' to update") % ctx.rev()
4797 " or 'hg update %s' to update") % ctx.rev()
4798 elif dirty:
4798 elif dirty:
4799 hint = _("uncommitted changes, use --all to discard all changes")
4799 hint = _("uncommitted changes, use --all to discard all changes")
4800 else:
4800 else:
4801 hint = _("use --all to revert all files")
4801 hint = _("use --all to revert all files")
4802 raise util.Abort(msg, hint=hint)
4802 raise util.Abort(msg, hint=hint)
4803
4803
4804 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
4804 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
4805
4805
4806 @command('rollback', dryrunopts +
4806 @command('rollback', dryrunopts +
4807 [('f', 'force', False, _('ignore safety measures'))])
4807 [('f', 'force', False, _('ignore safety measures'))])
4808 def rollback(ui, repo, **opts):
4808 def rollback(ui, repo, **opts):
4809 """roll back the last transaction (dangerous)
4809 """roll back the last transaction (dangerous)
4810
4810
4811 This command should be used with care. There is only one level of
4811 This command should be used with care. There is only one level of
4812 rollback, and there is no way to undo a rollback. It will also
4812 rollback, and there is no way to undo a rollback. It will also
4813 restore the dirstate at the time of the last transaction, losing
4813 restore the dirstate at the time of the last transaction, losing
4814 any dirstate changes since that time. This command does not alter
4814 any dirstate changes since that time. This command does not alter
4815 the working directory.
4815 the working directory.
4816
4816
4817 Transactions are used to encapsulate the effects of all commands
4817 Transactions are used to encapsulate the effects of all commands
4818 that create new changesets or propagate existing changesets into a
4818 that create new changesets or propagate existing changesets into a
4819 repository. For example, the following commands are transactional,
4819 repository. For example, the following commands are transactional,
4820 and their effects can be rolled back:
4820 and their effects can be rolled back:
4821
4821
4822 - commit
4822 - commit
4823 - import
4823 - import
4824 - pull
4824 - pull
4825 - push (with this repository as the destination)
4825 - push (with this repository as the destination)
4826 - unbundle
4826 - unbundle
4827
4827
4828 To avoid permanent data loss, rollback will refuse to rollback a
4828 To avoid permanent data loss, rollback will refuse to rollback a
4829 commit transaction if it isn't checked out. Use --force to
4829 commit transaction if it isn't checked out. Use --force to
4830 override this protection.
4830 override this protection.
4831
4831
4832 This command is not intended for use on public repositories. Once
4832 This command is not intended for use on public repositories. Once
4833 changes are visible for pull by other users, rolling a transaction
4833 changes are visible for pull by other users, rolling a transaction
4834 back locally is ineffective (someone else may already have pulled
4834 back locally is ineffective (someone else may already have pulled
4835 the changes). Furthermore, a race is possible with readers of the
4835 the changes). Furthermore, a race is possible with readers of the
4836 repository; for example an in-progress pull from the repository
4836 repository; for example an in-progress pull from the repository
4837 may fail if a rollback is performed.
4837 may fail if a rollback is performed.
4838
4838
4839 Returns 0 on success, 1 if no rollback data is available.
4839 Returns 0 on success, 1 if no rollback data is available.
4840 """
4840 """
4841 return repo.rollback(dryrun=opts.get('dry_run'),
4841 return repo.rollback(dryrun=opts.get('dry_run'),
4842 force=opts.get('force'))
4842 force=opts.get('force'))
4843
4843
4844 @command('root', [])
4844 @command('root', [])
4845 def root(ui, repo):
4845 def root(ui, repo):
4846 """print the root (top) of the current working directory
4846 """print the root (top) of the current working directory
4847
4847
4848 Print the root directory of the current repository.
4848 Print the root directory of the current repository.
4849
4849
4850 Returns 0 on success.
4850 Returns 0 on success.
4851 """
4851 """
4852 ui.write(repo.root + "\n")
4852 ui.write(repo.root + "\n")
4853
4853
4854 @command('^serve',
4854 @command('^serve',
4855 [('A', 'accesslog', '', _('name of access log file to write to'),
4855 [('A', 'accesslog', '', _('name of access log file to write to'),
4856 _('FILE')),
4856 _('FILE')),
4857 ('d', 'daemon', None, _('run server in background')),
4857 ('d', 'daemon', None, _('run server in background')),
4858 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4858 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4859 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4859 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4860 # use string type, then we can check if something was passed
4860 # use string type, then we can check if something was passed
4861 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4861 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4862 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4862 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4863 _('ADDR')),
4863 _('ADDR')),
4864 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4864 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4865 _('PREFIX')),
4865 _('PREFIX')),
4866 ('n', 'name', '',
4866 ('n', 'name', '',
4867 _('name to show in web pages (default: working directory)'), _('NAME')),
4867 _('name to show in web pages (default: working directory)'), _('NAME')),
4868 ('', 'web-conf', '',
4868 ('', 'web-conf', '',
4869 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4869 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4870 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4870 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4871 _('FILE')),
4871 _('FILE')),
4872 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4872 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4873 ('', 'stdio', None, _('for remote clients')),
4873 ('', 'stdio', None, _('for remote clients')),
4874 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
4874 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
4875 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4875 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4876 ('', 'style', '', _('template style to use'), _('STYLE')),
4876 ('', 'style', '', _('template style to use'), _('STYLE')),
4877 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4877 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4878 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4878 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4879 _('[OPTION]...'))
4879 _('[OPTION]...'))
4880 def serve(ui, repo, **opts):
4880 def serve(ui, repo, **opts):
4881 """start stand-alone webserver
4881 """start stand-alone webserver
4882
4882
4883 Start a local HTTP repository browser and pull server. You can use
4883 Start a local HTTP repository browser and pull server. You can use
4884 this for ad-hoc sharing and browsing of repositories. It is
4884 this for ad-hoc sharing and browsing of repositories. It is
4885 recommended to use a real web server to serve a repository for
4885 recommended to use a real web server to serve a repository for
4886 longer periods of time.
4886 longer periods of time.
4887
4887
4888 Please note that the server does not implement access control.
4888 Please note that the server does not implement access control.
4889 This means that, by default, anybody can read from the server and
4889 This means that, by default, anybody can read from the server and
4890 nobody can write to it by default. Set the ``web.allow_push``
4890 nobody can write to it by default. Set the ``web.allow_push``
4891 option to ``*`` to allow everybody to push to the server. You
4891 option to ``*`` to allow everybody to push to the server. You
4892 should use a real web server if you need to authenticate users.
4892 should use a real web server if you need to authenticate users.
4893
4893
4894 By default, the server logs accesses to stdout and errors to
4894 By default, the server logs accesses to stdout and errors to
4895 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4895 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4896 files.
4896 files.
4897
4897
4898 To have the server choose a free port number to listen on, specify
4898 To have the server choose a free port number to listen on, specify
4899 a port number of 0; in this case, the server will print the port
4899 a port number of 0; in this case, the server will print the port
4900 number it uses.
4900 number it uses.
4901
4901
4902 Returns 0 on success.
4902 Returns 0 on success.
4903 """
4903 """
4904
4904
4905 if opts["stdio"] and opts["cmdserver"]:
4905 if opts["stdio"] and opts["cmdserver"]:
4906 raise util.Abort(_("cannot use --stdio with --cmdserver"))
4906 raise util.Abort(_("cannot use --stdio with --cmdserver"))
4907
4907
4908 def checkrepo():
4908 def checkrepo():
4909 if repo is None:
4909 if repo is None:
4910 raise error.RepoError(_("There is no Mercurial repository here"
4910 raise error.RepoError(_("There is no Mercurial repository here"
4911 " (.hg not found)"))
4911 " (.hg not found)"))
4912
4912
4913 if opts["stdio"]:
4913 if opts["stdio"]:
4914 checkrepo()
4914 checkrepo()
4915 s = sshserver.sshserver(ui, repo)
4915 s = sshserver.sshserver(ui, repo)
4916 s.serve_forever()
4916 s.serve_forever()
4917
4917
4918 if opts["cmdserver"]:
4918 if opts["cmdserver"]:
4919 checkrepo()
4919 checkrepo()
4920 s = commandserver.server(ui, repo, opts["cmdserver"])
4920 s = commandserver.server(ui, repo, opts["cmdserver"])
4921 return s.serve()
4921 return s.serve()
4922
4922
4923 # this way we can check if something was given in the command-line
4923 # this way we can check if something was given in the command-line
4924 if opts.get('port'):
4924 if opts.get('port'):
4925 opts['port'] = util.getport(opts.get('port'))
4925 opts['port'] = util.getport(opts.get('port'))
4926
4926
4927 baseui = repo and repo.baseui or ui
4927 baseui = repo and repo.baseui or ui
4928 optlist = ("name templates style address port prefix ipv6"
4928 optlist = ("name templates style address port prefix ipv6"
4929 " accesslog errorlog certificate encoding")
4929 " accesslog errorlog certificate encoding")
4930 for o in optlist.split():
4930 for o in optlist.split():
4931 val = opts.get(o, '')
4931 val = opts.get(o, '')
4932 if val in (None, ''): # should check against default options instead
4932 if val in (None, ''): # should check against default options instead
4933 continue
4933 continue
4934 baseui.setconfig("web", o, val)
4934 baseui.setconfig("web", o, val)
4935 if repo and repo.ui != baseui:
4935 if repo and repo.ui != baseui:
4936 repo.ui.setconfig("web", o, val)
4936 repo.ui.setconfig("web", o, val)
4937
4937
4938 o = opts.get('web_conf') or opts.get('webdir_conf')
4938 o = opts.get('web_conf') or opts.get('webdir_conf')
4939 if not o:
4939 if not o:
4940 if not repo:
4940 if not repo:
4941 raise error.RepoError(_("There is no Mercurial repository"
4941 raise error.RepoError(_("There is no Mercurial repository"
4942 " here (.hg not found)"))
4942 " here (.hg not found)"))
4943 o = repo.root
4943 o = repo.root
4944
4944
4945 app = hgweb.hgweb(o, baseui=ui)
4945 app = hgweb.hgweb(o, baseui=ui)
4946
4946
4947 class service(object):
4947 class service(object):
4948 def init(self):
4948 def init(self):
4949 util.setsignalhandler()
4949 util.setsignalhandler()
4950 self.httpd = hgweb.server.create_server(ui, app)
4950 self.httpd = hgweb.server.create_server(ui, app)
4951
4951
4952 if opts['port'] and not ui.verbose:
4952 if opts['port'] and not ui.verbose:
4953 return
4953 return
4954
4954
4955 if self.httpd.prefix:
4955 if self.httpd.prefix:
4956 prefix = self.httpd.prefix.strip('/') + '/'
4956 prefix = self.httpd.prefix.strip('/') + '/'
4957 else:
4957 else:
4958 prefix = ''
4958 prefix = ''
4959
4959
4960 port = ':%d' % self.httpd.port
4960 port = ':%d' % self.httpd.port
4961 if port == ':80':
4961 if port == ':80':
4962 port = ''
4962 port = ''
4963
4963
4964 bindaddr = self.httpd.addr
4964 bindaddr = self.httpd.addr
4965 if bindaddr == '0.0.0.0':
4965 if bindaddr == '0.0.0.0':
4966 bindaddr = '*'
4966 bindaddr = '*'
4967 elif ':' in bindaddr: # IPv6
4967 elif ':' in bindaddr: # IPv6
4968 bindaddr = '[%s]' % bindaddr
4968 bindaddr = '[%s]' % bindaddr
4969
4969
4970 fqaddr = self.httpd.fqaddr
4970 fqaddr = self.httpd.fqaddr
4971 if ':' in fqaddr:
4971 if ':' in fqaddr:
4972 fqaddr = '[%s]' % fqaddr
4972 fqaddr = '[%s]' % fqaddr
4973 if opts['port']:
4973 if opts['port']:
4974 write = ui.status
4974 write = ui.status
4975 else:
4975 else:
4976 write = ui.write
4976 write = ui.write
4977 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4977 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4978 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4978 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4979
4979
4980 def run(self):
4980 def run(self):
4981 self.httpd.serve_forever()
4981 self.httpd.serve_forever()
4982
4982
4983 service = service()
4983 service = service()
4984
4984
4985 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4985 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4986
4986
4987 @command('showconfig|debugconfig',
4987 @command('showconfig|debugconfig',
4988 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4988 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4989 _('[-u] [NAME]...'))
4989 _('[-u] [NAME]...'))
4990 def showconfig(ui, repo, *values, **opts):
4990 def showconfig(ui, repo, *values, **opts):
4991 """show combined config settings from all hgrc files
4991 """show combined config settings from all hgrc files
4992
4992
4993 With no arguments, print names and values of all config items.
4993 With no arguments, print names and values of all config items.
4994
4994
4995 With one argument of the form section.name, print just the value
4995 With one argument of the form section.name, print just the value
4996 of that config item.
4996 of that config item.
4997
4997
4998 With multiple arguments, print names and values of all config
4998 With multiple arguments, print names and values of all config
4999 items with matching section names.
4999 items with matching section names.
5000
5000
5001 With --debug, the source (filename and line number) is printed
5001 With --debug, the source (filename and line number) is printed
5002 for each config item.
5002 for each config item.
5003
5003
5004 Returns 0 on success.
5004 Returns 0 on success.
5005 """
5005 """
5006
5006
5007 for f in scmutil.rcpath():
5007 for f in scmutil.rcpath():
5008 ui.debug('read config from: %s\n' % f)
5008 ui.debug('read config from: %s\n' % f)
5009 untrusted = bool(opts.get('untrusted'))
5009 untrusted = bool(opts.get('untrusted'))
5010 if values:
5010 if values:
5011 sections = [v for v in values if '.' not in v]
5011 sections = [v for v in values if '.' not in v]
5012 items = [v for v in values if '.' in v]
5012 items = [v for v in values if '.' in v]
5013 if len(items) > 1 or items and sections:
5013 if len(items) > 1 or items and sections:
5014 raise util.Abort(_('only one config item permitted'))
5014 raise util.Abort(_('only one config item permitted'))
5015 for section, name, value in ui.walkconfig(untrusted=untrusted):
5015 for section, name, value in ui.walkconfig(untrusted=untrusted):
5016 value = str(value).replace('\n', '\\n')
5016 value = str(value).replace('\n', '\\n')
5017 sectname = section + '.' + name
5017 sectname = section + '.' + name
5018 if values:
5018 if values:
5019 for v in values:
5019 for v in values:
5020 if v == section:
5020 if v == section:
5021 ui.debug('%s: ' %
5021 ui.debug('%s: ' %
5022 ui.configsource(section, name, untrusted))
5022 ui.configsource(section, name, untrusted))
5023 ui.write('%s=%s\n' % (sectname, value))
5023 ui.write('%s=%s\n' % (sectname, value))
5024 elif v == sectname:
5024 elif v == sectname:
5025 ui.debug('%s: ' %
5025 ui.debug('%s: ' %
5026 ui.configsource(section, name, untrusted))
5026 ui.configsource(section, name, untrusted))
5027 ui.write(value, '\n')
5027 ui.write(value, '\n')
5028 else:
5028 else:
5029 ui.debug('%s: ' %
5029 ui.debug('%s: ' %
5030 ui.configsource(section, name, untrusted))
5030 ui.configsource(section, name, untrusted))
5031 ui.write('%s=%s\n' % (sectname, value))
5031 ui.write('%s=%s\n' % (sectname, value))
5032
5032
5033 @command('^status|st',
5033 @command('^status|st',
5034 [('A', 'all', None, _('show status of all files')),
5034 [('A', 'all', None, _('show status of all files')),
5035 ('m', 'modified', None, _('show only modified files')),
5035 ('m', 'modified', None, _('show only modified files')),
5036 ('a', 'added', None, _('show only added files')),
5036 ('a', 'added', None, _('show only added files')),
5037 ('r', 'removed', None, _('show only removed files')),
5037 ('r', 'removed', None, _('show only removed files')),
5038 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5038 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5039 ('c', 'clean', None, _('show only files without changes')),
5039 ('c', 'clean', None, _('show only files without changes')),
5040 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5040 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5041 ('i', 'ignored', None, _('show only ignored files')),
5041 ('i', 'ignored', None, _('show only ignored files')),
5042 ('n', 'no-status', None, _('hide status prefix')),
5042 ('n', 'no-status', None, _('hide status prefix')),
5043 ('C', 'copies', None, _('show source of copied files')),
5043 ('C', 'copies', None, _('show source of copied files')),
5044 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5044 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5045 ('', 'rev', [], _('show difference from revision'), _('REV')),
5045 ('', 'rev', [], _('show difference from revision'), _('REV')),
5046 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5046 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5047 ] + walkopts + subrepoopts,
5047 ] + walkopts + subrepoopts,
5048 _('[OPTION]... [FILE]...'))
5048 _('[OPTION]... [FILE]...'))
5049 def status(ui, repo, *pats, **opts):
5049 def status(ui, repo, *pats, **opts):
5050 """show changed files in the working directory
5050 """show changed files in the working directory
5051
5051
5052 Show status of files in the repository. If names are given, only
5052 Show status of files in the repository. If names are given, only
5053 files that match are shown. Files that are clean or ignored or
5053 files that match are shown. Files that are clean or ignored or
5054 the source of a copy/move operation, are not listed unless
5054 the source of a copy/move operation, are not listed unless
5055 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5055 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5056 Unless options described with "show only ..." are given, the
5056 Unless options described with "show only ..." are given, the
5057 options -mardu are used.
5057 options -mardu are used.
5058
5058
5059 Option -q/--quiet hides untracked (unknown and ignored) files
5059 Option -q/--quiet hides untracked (unknown and ignored) files
5060 unless explicitly requested with -u/--unknown or -i/--ignored.
5060 unless explicitly requested with -u/--unknown or -i/--ignored.
5061
5061
5062 .. note::
5062 .. note::
5063 status may appear to disagree with diff if permissions have
5063 status may appear to disagree with diff if permissions have
5064 changed or a merge has occurred. The standard diff format does
5064 changed or a merge has occurred. The standard diff format does
5065 not report permission changes and diff only reports changes
5065 not report permission changes and diff only reports changes
5066 relative to one merge parent.
5066 relative to one merge parent.
5067
5067
5068 If one revision is given, it is used as the base revision.
5068 If one revision is given, it is used as the base revision.
5069 If two revisions are given, the differences between them are
5069 If two revisions are given, the differences between them are
5070 shown. The --change option can also be used as a shortcut to list
5070 shown. The --change option can also be used as a shortcut to list
5071 the changed files of a revision from its first parent.
5071 the changed files of a revision from its first parent.
5072
5072
5073 The codes used to show the status of files are::
5073 The codes used to show the status of files are::
5074
5074
5075 M = modified
5075 M = modified
5076 A = added
5076 A = added
5077 R = removed
5077 R = removed
5078 C = clean
5078 C = clean
5079 ! = missing (deleted by non-hg command, but still tracked)
5079 ! = missing (deleted by non-hg command, but still tracked)
5080 ? = not tracked
5080 ? = not tracked
5081 I = ignored
5081 I = ignored
5082 = origin of the previous file listed as A (added)
5082 = origin of the previous file listed as A (added)
5083
5083
5084 .. container:: verbose
5084 .. container:: verbose
5085
5085
5086 Examples:
5086 Examples:
5087
5087
5088 - show changes in the working directory relative to a
5088 - show changes in the working directory relative to a
5089 changeset::
5089 changeset::
5090
5090
5091 hg status --rev 9353
5091 hg status --rev 9353
5092
5092
5093 - show all changes including copies in an existing changeset::
5093 - show all changes including copies in an existing changeset::
5094
5094
5095 hg status --copies --change 9353
5095 hg status --copies --change 9353
5096
5096
5097 - get a NUL separated list of added files, suitable for xargs::
5097 - get a NUL separated list of added files, suitable for xargs::
5098
5098
5099 hg status -an0
5099 hg status -an0
5100
5100
5101 Returns 0 on success.
5101 Returns 0 on success.
5102 """
5102 """
5103
5103
5104 revs = opts.get('rev')
5104 revs = opts.get('rev')
5105 change = opts.get('change')
5105 change = opts.get('change')
5106
5106
5107 if revs and change:
5107 if revs and change:
5108 msg = _('cannot specify --rev and --change at the same time')
5108 msg = _('cannot specify --rev and --change at the same time')
5109 raise util.Abort(msg)
5109 raise util.Abort(msg)
5110 elif change:
5110 elif change:
5111 node2 = scmutil.revsingle(repo, change, None).node()
5111 node2 = scmutil.revsingle(repo, change, None).node()
5112 node1 = repo[node2].p1().node()
5112 node1 = repo[node2].p1().node()
5113 else:
5113 else:
5114 node1, node2 = scmutil.revpair(repo, revs)
5114 node1, node2 = scmutil.revpair(repo, revs)
5115
5115
5116 cwd = (pats and repo.getcwd()) or ''
5116 cwd = (pats and repo.getcwd()) or ''
5117 end = opts.get('print0') and '\0' or '\n'
5117 end = opts.get('print0') and '\0' or '\n'
5118 copy = {}
5118 copy = {}
5119 states = 'modified added removed deleted unknown ignored clean'.split()
5119 states = 'modified added removed deleted unknown ignored clean'.split()
5120 show = [k for k in states if opts.get(k)]
5120 show = [k for k in states if opts.get(k)]
5121 if opts.get('all'):
5121 if opts.get('all'):
5122 show += ui.quiet and (states[:4] + ['clean']) or states
5122 show += ui.quiet and (states[:4] + ['clean']) or states
5123 if not show:
5123 if not show:
5124 show = ui.quiet and states[:4] or states[:5]
5124 show = ui.quiet and states[:4] or states[:5]
5125
5125
5126 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5126 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5127 'ignored' in show, 'clean' in show, 'unknown' in show,
5127 'ignored' in show, 'clean' in show, 'unknown' in show,
5128 opts.get('subrepos'))
5128 opts.get('subrepos'))
5129 changestates = zip(states, 'MAR!?IC', stat)
5129 changestates = zip(states, 'MAR!?IC', stat)
5130
5130
5131 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5131 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5132 copy = copies.pathcopies(repo[node1], repo[node2])
5132 copy = copies.pathcopies(repo[node1], repo[node2])
5133
5133
5134 fm = ui.formatter('status', opts)
5134 fm = ui.formatter('status', opts)
5135 format = '%s %s' + end
5135 format = '%s %s' + end
5136 if opts.get('no_status'):
5136 if opts.get('no_status'):
5137 format = '%.0s%s' + end
5137 format = '%.0s%s' + end
5138
5138
5139 for state, char, files in changestates:
5139 for state, char, files in changestates:
5140 if state in show:
5140 if state in show:
5141 label = 'status.' + state
5141 label = 'status.' + state
5142 for f in files:
5142 for f in files:
5143 fm.startitem()
5143 fm.startitem()
5144 fm.write("status path", format, char,
5144 fm.write("status path", format, char,
5145 repo.pathto(f, cwd), label=label)
5145 repo.pathto(f, cwd), label=label)
5146 if f in copy:
5146 if f in copy:
5147 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5147 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5148 label='status.copied')
5148 label='status.copied')
5149 fm.end()
5149 fm.end()
5150
5150
5151 @command('^summary|sum',
5151 @command('^summary|sum',
5152 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5152 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5153 def summary(ui, repo, **opts):
5153 def summary(ui, repo, **opts):
5154 """summarize working directory state
5154 """summarize working directory state
5155
5155
5156 This generates a brief summary of the working directory state,
5156 This generates a brief summary of the working directory state,
5157 including parents, branch, commit status, and available updates.
5157 including parents, branch, commit status, and available updates.
5158
5158
5159 With the --remote option, this will check the default paths for
5159 With the --remote option, this will check the default paths for
5160 incoming and outgoing changes. This can be time-consuming.
5160 incoming and outgoing changes. This can be time-consuming.
5161
5161
5162 Returns 0 on success.
5162 Returns 0 on success.
5163 """
5163 """
5164
5164
5165 ctx = repo[None]
5165 ctx = repo[None]
5166 parents = ctx.parents()
5166 parents = ctx.parents()
5167 pnode = parents[0].node()
5167 pnode = parents[0].node()
5168 marks = []
5168 marks = []
5169
5169
5170 for p in parents:
5170 for p in parents:
5171 # label with log.changeset (instead of log.parent) since this
5171 # label with log.changeset (instead of log.parent) since this
5172 # shows a working directory parent *changeset*:
5172 # shows a working directory parent *changeset*:
5173 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5173 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5174 label='log.changeset')
5174 label='log.changeset')
5175 ui.write(' '.join(p.tags()), label='log.tag')
5175 ui.write(' '.join(p.tags()), label='log.tag')
5176 if p.bookmarks():
5176 if p.bookmarks():
5177 marks.extend(p.bookmarks())
5177 marks.extend(p.bookmarks())
5178 if p.rev() == -1:
5178 if p.rev() == -1:
5179 if not len(repo):
5179 if not len(repo):
5180 ui.write(_(' (empty repository)'))
5180 ui.write(_(' (empty repository)'))
5181 else:
5181 else:
5182 ui.write(_(' (no revision checked out)'))
5182 ui.write(_(' (no revision checked out)'))
5183 ui.write('\n')
5183 ui.write('\n')
5184 if p.description():
5184 if p.description():
5185 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5185 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5186 label='log.summary')
5186 label='log.summary')
5187
5187
5188 branch = ctx.branch()
5188 branch = ctx.branch()
5189 bheads = repo.branchheads(branch)
5189 bheads = repo.branchheads(branch)
5190 m = _('branch: %s\n') % branch
5190 m = _('branch: %s\n') % branch
5191 if branch != 'default':
5191 if branch != 'default':
5192 ui.write(m, label='log.branch')
5192 ui.write(m, label='log.branch')
5193 else:
5193 else:
5194 ui.status(m, label='log.branch')
5194 ui.status(m, label='log.branch')
5195
5195
5196 if marks:
5196 if marks:
5197 current = repo._bookmarkcurrent
5197 current = repo._bookmarkcurrent
5198 ui.write(_('bookmarks:'), label='log.bookmark')
5198 ui.write(_('bookmarks:'), label='log.bookmark')
5199 if current is not None:
5199 if current is not None:
5200 try:
5200 try:
5201 marks.remove(current)
5201 marks.remove(current)
5202 ui.write(' *' + current, label='bookmarks.current')
5202 ui.write(' *' + current, label='bookmarks.current')
5203 except ValueError:
5203 except ValueError:
5204 # current bookmark not in parent ctx marks
5204 # current bookmark not in parent ctx marks
5205 pass
5205 pass
5206 for m in marks:
5206 for m in marks:
5207 ui.write(' ' + m, label='log.bookmark')
5207 ui.write(' ' + m, label='log.bookmark')
5208 ui.write('\n', label='log.bookmark')
5208 ui.write('\n', label='log.bookmark')
5209
5209
5210 st = list(repo.status(unknown=True))[:6]
5210 st = list(repo.status(unknown=True))[:6]
5211
5211
5212 c = repo.dirstate.copies()
5212 c = repo.dirstate.copies()
5213 copied, renamed = [], []
5213 copied, renamed = [], []
5214 for d, s in c.iteritems():
5214 for d, s in c.iteritems():
5215 if s in st[2]:
5215 if s in st[2]:
5216 st[2].remove(s)
5216 st[2].remove(s)
5217 renamed.append(d)
5217 renamed.append(d)
5218 else:
5218 else:
5219 copied.append(d)
5219 copied.append(d)
5220 if d in st[1]:
5220 if d in st[1]:
5221 st[1].remove(d)
5221 st[1].remove(d)
5222 st.insert(3, renamed)
5222 st.insert(3, renamed)
5223 st.insert(4, copied)
5223 st.insert(4, copied)
5224
5224
5225 ms = mergemod.mergestate(repo)
5225 ms = mergemod.mergestate(repo)
5226 st.append([f for f in ms if ms[f] == 'u'])
5226 st.append([f for f in ms if ms[f] == 'u'])
5227
5227
5228 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5228 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5229 st.append(subs)
5229 st.append(subs)
5230
5230
5231 labels = [ui.label(_('%d modified'), 'status.modified'),
5231 labels = [ui.label(_('%d modified'), 'status.modified'),
5232 ui.label(_('%d added'), 'status.added'),
5232 ui.label(_('%d added'), 'status.added'),
5233 ui.label(_('%d removed'), 'status.removed'),
5233 ui.label(_('%d removed'), 'status.removed'),
5234 ui.label(_('%d renamed'), 'status.copied'),
5234 ui.label(_('%d renamed'), 'status.copied'),
5235 ui.label(_('%d copied'), 'status.copied'),
5235 ui.label(_('%d copied'), 'status.copied'),
5236 ui.label(_('%d deleted'), 'status.deleted'),
5236 ui.label(_('%d deleted'), 'status.deleted'),
5237 ui.label(_('%d unknown'), 'status.unknown'),
5237 ui.label(_('%d unknown'), 'status.unknown'),
5238 ui.label(_('%d ignored'), 'status.ignored'),
5238 ui.label(_('%d ignored'), 'status.ignored'),
5239 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5239 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5240 ui.label(_('%d subrepos'), 'status.modified')]
5240 ui.label(_('%d subrepos'), 'status.modified')]
5241 t = []
5241 t = []
5242 for s, l in zip(st, labels):
5242 for s, l in zip(st, labels):
5243 if s:
5243 if s:
5244 t.append(l % len(s))
5244 t.append(l % len(s))
5245
5245
5246 t = ', '.join(t)
5246 t = ', '.join(t)
5247 cleanworkdir = False
5247 cleanworkdir = False
5248
5248
5249 if len(parents) > 1:
5249 if len(parents) > 1:
5250 t += _(' (merge)')
5250 t += _(' (merge)')
5251 elif branch != parents[0].branch():
5251 elif branch != parents[0].branch():
5252 t += _(' (new branch)')
5252 t += _(' (new branch)')
5253 elif (parents[0].extra().get('close') and
5253 elif (parents[0].extra().get('close') and
5254 pnode in repo.branchheads(branch, closed=True)):
5254 pnode in repo.branchheads(branch, closed=True)):
5255 t += _(' (head closed)')
5255 t += _(' (head closed)')
5256 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5256 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5257 t += _(' (clean)')
5257 t += _(' (clean)')
5258 cleanworkdir = True
5258 cleanworkdir = True
5259 elif pnode not in bheads:
5259 elif pnode not in bheads:
5260 t += _(' (new branch head)')
5260 t += _(' (new branch head)')
5261
5261
5262 if cleanworkdir:
5262 if cleanworkdir:
5263 ui.status(_('commit: %s\n') % t.strip())
5263 ui.status(_('commit: %s\n') % t.strip())
5264 else:
5264 else:
5265 ui.write(_('commit: %s\n') % t.strip())
5265 ui.write(_('commit: %s\n') % t.strip())
5266
5266
5267 # all ancestors of branch heads - all ancestors of parent = new csets
5267 # all ancestors of branch heads - all ancestors of parent = new csets
5268 new = [0] * len(repo)
5268 new = [0] * len(repo)
5269 cl = repo.changelog
5269 cl = repo.changelog
5270 for a in [cl.rev(n) for n in bheads]:
5270 for a in [cl.rev(n) for n in bheads]:
5271 new[a] = 1
5271 new[a] = 1
5272 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
5272 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
5273 new[a] = 1
5273 new[a] = 1
5274 for a in [p.rev() for p in parents]:
5274 for a in [p.rev() for p in parents]:
5275 if a >= 0:
5275 if a >= 0:
5276 new[a] = 0
5276 new[a] = 0
5277 for a in cl.ancestors(*[p.rev() for p in parents]):
5277 for a in cl.ancestors(*[p.rev() for p in parents]):
5278 new[a] = 0
5278 new[a] = 0
5279 new = sum(new)
5279 new = sum(new)
5280
5280
5281 if new == 0:
5281 if new == 0:
5282 ui.status(_('update: (current)\n'))
5282 ui.status(_('update: (current)\n'))
5283 elif pnode not in bheads:
5283 elif pnode not in bheads:
5284 ui.write(_('update: %d new changesets (update)\n') % new)
5284 ui.write(_('update: %d new changesets (update)\n') % new)
5285 else:
5285 else:
5286 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5286 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5287 (new, len(bheads)))
5287 (new, len(bheads)))
5288
5288
5289 if opts.get('remote'):
5289 if opts.get('remote'):
5290 t = []
5290 t = []
5291 source, branches = hg.parseurl(ui.expandpath('default'))
5291 source, branches = hg.parseurl(ui.expandpath('default'))
5292 other = hg.peer(repo, {}, source)
5292 other = hg.peer(repo, {}, source)
5293 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
5293 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
5294 ui.debug('comparing with %s\n' % util.hidepassword(source))
5294 ui.debug('comparing with %s\n' % util.hidepassword(source))
5295 repo.ui.pushbuffer()
5295 repo.ui.pushbuffer()
5296 commoninc = discovery.findcommonincoming(repo, other)
5296 commoninc = discovery.findcommonincoming(repo, other)
5297 _common, incoming, _rheads = commoninc
5297 _common, incoming, _rheads = commoninc
5298 repo.ui.popbuffer()
5298 repo.ui.popbuffer()
5299 if incoming:
5299 if incoming:
5300 t.append(_('1 or more incoming'))
5300 t.append(_('1 or more incoming'))
5301
5301
5302 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5302 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5303 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5303 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5304 if source != dest:
5304 if source != dest:
5305 other = hg.peer(repo, {}, dest)
5305 other = hg.peer(repo, {}, dest)
5306 commoninc = None
5306 commoninc = None
5307 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5307 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5308 repo.ui.pushbuffer()
5308 repo.ui.pushbuffer()
5309 outgoing = discovery.findcommonoutgoing(repo, other,
5309 outgoing = discovery.findcommonoutgoing(repo, other,
5310 commoninc=commoninc)
5310 commoninc=commoninc)
5311 repo.ui.popbuffer()
5311 repo.ui.popbuffer()
5312 o = outgoing.missing
5312 o = outgoing.missing
5313 if o:
5313 if o:
5314 t.append(_('%d outgoing') % len(o))
5314 t.append(_('%d outgoing') % len(o))
5315 if 'bookmarks' in other.listkeys('namespaces'):
5315 if 'bookmarks' in other.listkeys('namespaces'):
5316 lmarks = repo.listkeys('bookmarks')
5316 lmarks = repo.listkeys('bookmarks')
5317 rmarks = other.listkeys('bookmarks')
5317 rmarks = other.listkeys('bookmarks')
5318 diff = set(rmarks) - set(lmarks)
5318 diff = set(rmarks) - set(lmarks)
5319 if len(diff) > 0:
5319 if len(diff) > 0:
5320 t.append(_('%d incoming bookmarks') % len(diff))
5320 t.append(_('%d incoming bookmarks') % len(diff))
5321 diff = set(lmarks) - set(rmarks)
5321 diff = set(lmarks) - set(rmarks)
5322 if len(diff) > 0:
5322 if len(diff) > 0:
5323 t.append(_('%d outgoing bookmarks') % len(diff))
5323 t.append(_('%d outgoing bookmarks') % len(diff))
5324
5324
5325 if t:
5325 if t:
5326 ui.write(_('remote: %s\n') % (', '.join(t)))
5326 ui.write(_('remote: %s\n') % (', '.join(t)))
5327 else:
5327 else:
5328 ui.status(_('remote: (synced)\n'))
5328 ui.status(_('remote: (synced)\n'))
5329
5329
5330 @command('tag',
5330 @command('tag',
5331 [('f', 'force', None, _('force tag')),
5331 [('f', 'force', None, _('force tag')),
5332 ('l', 'local', None, _('make the tag local')),
5332 ('l', 'local', None, _('make the tag local')),
5333 ('r', 'rev', '', _('revision to tag'), _('REV')),
5333 ('r', 'rev', '', _('revision to tag'), _('REV')),
5334 ('', 'remove', None, _('remove a tag')),
5334 ('', 'remove', None, _('remove a tag')),
5335 # -l/--local is already there, commitopts cannot be used
5335 # -l/--local is already there, commitopts cannot be used
5336 ('e', 'edit', None, _('edit commit message')),
5336 ('e', 'edit', None, _('edit commit message')),
5337 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5337 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5338 ] + commitopts2,
5338 ] + commitopts2,
5339 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5339 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5340 def tag(ui, repo, name1, *names, **opts):
5340 def tag(ui, repo, name1, *names, **opts):
5341 """add one or more tags for the current or given revision
5341 """add one or more tags for the current or given revision
5342
5342
5343 Name a particular revision using <name>.
5343 Name a particular revision using <name>.
5344
5344
5345 Tags are used to name particular revisions of the repository and are
5345 Tags are used to name particular revisions of the repository and are
5346 very useful to compare different revisions, to go back to significant
5346 very useful to compare different revisions, to go back to significant
5347 earlier versions or to mark branch points as releases, etc. Changing
5347 earlier versions or to mark branch points as releases, etc. Changing
5348 an existing tag is normally disallowed; use -f/--force to override.
5348 an existing tag is normally disallowed; use -f/--force to override.
5349
5349
5350 If no revision is given, the parent of the working directory is
5350 If no revision is given, the parent of the working directory is
5351 used, or tip if no revision is checked out.
5351 used, or tip if no revision is checked out.
5352
5352
5353 To facilitate version control, distribution, and merging of tags,
5353 To facilitate version control, distribution, and merging of tags,
5354 they are stored as a file named ".hgtags" which is managed similarly
5354 they are stored as a file named ".hgtags" which is managed similarly
5355 to other project files and can be hand-edited if necessary. This
5355 to other project files and can be hand-edited if necessary. This
5356 also means that tagging creates a new commit. The file
5356 also means that tagging creates a new commit. The file
5357 ".hg/localtags" is used for local tags (not shared among
5357 ".hg/localtags" is used for local tags (not shared among
5358 repositories).
5358 repositories).
5359
5359
5360 Tag commits are usually made at the head of a branch. If the parent
5360 Tag commits are usually made at the head of a branch. If the parent
5361 of the working directory is not a branch head, :hg:`tag` aborts; use
5361 of the working directory is not a branch head, :hg:`tag` aborts; use
5362 -f/--force to force the tag commit to be based on a non-head
5362 -f/--force to force the tag commit to be based on a non-head
5363 changeset.
5363 changeset.
5364
5364
5365 See :hg:`help dates` for a list of formats valid for -d/--date.
5365 See :hg:`help dates` for a list of formats valid for -d/--date.
5366
5366
5367 Since tag names have priority over branch names during revision
5367 Since tag names have priority over branch names during revision
5368 lookup, using an existing branch name as a tag name is discouraged.
5368 lookup, using an existing branch name as a tag name is discouraged.
5369
5369
5370 Returns 0 on success.
5370 Returns 0 on success.
5371 """
5371 """
5372 wlock = lock = None
5372 wlock = lock = None
5373 try:
5373 try:
5374 wlock = repo.wlock()
5374 wlock = repo.wlock()
5375 lock = repo.lock()
5375 lock = repo.lock()
5376 rev_ = "."
5376 rev_ = "."
5377 names = [t.strip() for t in (name1,) + names]
5377 names = [t.strip() for t in (name1,) + names]
5378 if len(names) != len(set(names)):
5378 if len(names) != len(set(names)):
5379 raise util.Abort(_('tag names must be unique'))
5379 raise util.Abort(_('tag names must be unique'))
5380 for n in names:
5380 for n in names:
5381 if n in ['tip', '.', 'null']:
5381 if n in ['tip', '.', 'null']:
5382 raise util.Abort(_("the name '%s' is reserved") % n)
5382 raise util.Abort(_("the name '%s' is reserved") % n)
5383 if not n:
5383 if not n:
5384 raise util.Abort(_('tag names cannot consist entirely of '
5384 raise util.Abort(_('tag names cannot consist entirely of '
5385 'whitespace'))
5385 'whitespace'))
5386 if opts.get('rev') and opts.get('remove'):
5386 if opts.get('rev') and opts.get('remove'):
5387 raise util.Abort(_("--rev and --remove are incompatible"))
5387 raise util.Abort(_("--rev and --remove are incompatible"))
5388 if opts.get('rev'):
5388 if opts.get('rev'):
5389 rev_ = opts['rev']
5389 rev_ = opts['rev']
5390 message = opts.get('message')
5390 message = opts.get('message')
5391 if opts.get('remove'):
5391 if opts.get('remove'):
5392 expectedtype = opts.get('local') and 'local' or 'global'
5392 expectedtype = opts.get('local') and 'local' or 'global'
5393 for n in names:
5393 for n in names:
5394 if not repo.tagtype(n):
5394 if not repo.tagtype(n):
5395 raise util.Abort(_("tag '%s' does not exist") % n)
5395 raise util.Abort(_("tag '%s' does not exist") % n)
5396 if repo.tagtype(n) != expectedtype:
5396 if repo.tagtype(n) != expectedtype:
5397 if expectedtype == 'global':
5397 if expectedtype == 'global':
5398 raise util.Abort(_("tag '%s' is not a global tag") % n)
5398 raise util.Abort(_("tag '%s' is not a global tag") % n)
5399 else:
5399 else:
5400 raise util.Abort(_("tag '%s' is not a local tag") % n)
5400 raise util.Abort(_("tag '%s' is not a local tag") % n)
5401 rev_ = nullid
5401 rev_ = nullid
5402 if not message:
5402 if not message:
5403 # we don't translate commit messages
5403 # we don't translate commit messages
5404 message = 'Removed tag %s' % ', '.join(names)
5404 message = 'Removed tag %s' % ', '.join(names)
5405 elif not opts.get('force'):
5405 elif not opts.get('force'):
5406 for n in names:
5406 for n in names:
5407 if n in repo.tags():
5407 if n in repo.tags():
5408 raise util.Abort(_("tag '%s' already exists "
5408 raise util.Abort(_("tag '%s' already exists "
5409 "(use -f to force)") % n)
5409 "(use -f to force)") % n)
5410 if not opts.get('local'):
5410 if not opts.get('local'):
5411 p1, p2 = repo.dirstate.parents()
5411 p1, p2 = repo.dirstate.parents()
5412 if p2 != nullid:
5412 if p2 != nullid:
5413 raise util.Abort(_('uncommitted merge'))
5413 raise util.Abort(_('uncommitted merge'))
5414 bheads = repo.branchheads()
5414 bheads = repo.branchheads()
5415 if not opts.get('force') and bheads and p1 not in bheads:
5415 if not opts.get('force') and bheads and p1 not in bheads:
5416 raise util.Abort(_('not at a branch head (use -f to force)'))
5416 raise util.Abort(_('not at a branch head (use -f to force)'))
5417 r = scmutil.revsingle(repo, rev_).node()
5417 r = scmutil.revsingle(repo, rev_).node()
5418
5418
5419 if not message:
5419 if not message:
5420 # we don't translate commit messages
5420 # we don't translate commit messages
5421 message = ('Added tag %s for changeset %s' %
5421 message = ('Added tag %s for changeset %s' %
5422 (', '.join(names), short(r)))
5422 (', '.join(names), short(r)))
5423
5423
5424 date = opts.get('date')
5424 date = opts.get('date')
5425 if date:
5425 if date:
5426 date = util.parsedate(date)
5426 date = util.parsedate(date)
5427
5427
5428 if opts.get('edit'):
5428 if opts.get('edit'):
5429 message = ui.edit(message, ui.username())
5429 message = ui.edit(message, ui.username())
5430
5430
5431 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5431 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5432 finally:
5432 finally:
5433 release(lock, wlock)
5433 release(lock, wlock)
5434
5434
5435 @command('tags', [], '')
5435 @command('tags', [], '')
5436 def tags(ui, repo):
5436 def tags(ui, repo):
5437 """list repository tags
5437 """list repository tags
5438
5438
5439 This lists both regular and local tags. When the -v/--verbose
5439 This lists both regular and local tags. When the -v/--verbose
5440 switch is used, a third column "local" is printed for local tags.
5440 switch is used, a third column "local" is printed for local tags.
5441
5441
5442 Returns 0 on success.
5442 Returns 0 on success.
5443 """
5443 """
5444
5444
5445 hexfunc = ui.debugflag and hex or short
5445 hexfunc = ui.debugflag and hex or short
5446 tagtype = ""
5446 tagtype = ""
5447
5447
5448 for t, n in reversed(repo.tagslist()):
5448 for t, n in reversed(repo.tagslist()):
5449 if ui.quiet:
5449 if ui.quiet:
5450 ui.write("%s\n" % t, label='tags.normal')
5450 ui.write("%s\n" % t, label='tags.normal')
5451 continue
5451 continue
5452
5452
5453 hn = hexfunc(n)
5453 hn = hexfunc(n)
5454 r = "%5d:%s" % (repo.changelog.rev(n), hn)
5454 r = "%5d:%s" % (repo.changelog.rev(n), hn)
5455 rev = ui.label(r, 'log.changeset')
5455 rev = ui.label(r, 'log.changeset')
5456 spaces = " " * (30 - encoding.colwidth(t))
5456 spaces = " " * (30 - encoding.colwidth(t))
5457
5457
5458 tag = ui.label(t, 'tags.normal')
5458 tag = ui.label(t, 'tags.normal')
5459 if ui.verbose:
5459 if ui.verbose:
5460 if repo.tagtype(t) == 'local':
5460 if repo.tagtype(t) == 'local':
5461 tagtype = " local"
5461 tagtype = " local"
5462 tag = ui.label(t, 'tags.local')
5462 tag = ui.label(t, 'tags.local')
5463 else:
5463 else:
5464 tagtype = ""
5464 tagtype = ""
5465 ui.write("%s%s %s%s\n" % (tag, spaces, rev, tagtype))
5465 ui.write("%s%s %s%s\n" % (tag, spaces, rev, tagtype))
5466
5466
5467 @command('tip',
5467 @command('tip',
5468 [('p', 'patch', None, _('show patch')),
5468 [('p', 'patch', None, _('show patch')),
5469 ('g', 'git', None, _('use git extended diff format')),
5469 ('g', 'git', None, _('use git extended diff format')),
5470 ] + templateopts,
5470 ] + templateopts,
5471 _('[-p] [-g]'))
5471 _('[-p] [-g]'))
5472 def tip(ui, repo, **opts):
5472 def tip(ui, repo, **opts):
5473 """show the tip revision
5473 """show the tip revision
5474
5474
5475 The tip revision (usually just called the tip) is the changeset
5475 The tip revision (usually just called the tip) is the changeset
5476 most recently added to the repository (and therefore the most
5476 most recently added to the repository (and therefore the most
5477 recently changed head).
5477 recently changed head).
5478
5478
5479 If you have just made a commit, that commit will be the tip. If
5479 If you have just made a commit, that commit will be the tip. If
5480 you have just pulled changes from another repository, the tip of
5480 you have just pulled changes from another repository, the tip of
5481 that repository becomes the current tip. The "tip" tag is special
5481 that repository becomes the current tip. The "tip" tag is special
5482 and cannot be renamed or assigned to a different changeset.
5482 and cannot be renamed or assigned to a different changeset.
5483
5483
5484 Returns 0 on success.
5484 Returns 0 on success.
5485 """
5485 """
5486 displayer = cmdutil.show_changeset(ui, repo, opts)
5486 displayer = cmdutil.show_changeset(ui, repo, opts)
5487 displayer.show(repo[len(repo) - 1])
5487 displayer.show(repo[len(repo) - 1])
5488 displayer.close()
5488 displayer.close()
5489
5489
5490 @command('unbundle',
5490 @command('unbundle',
5491 [('u', 'update', None,
5491 [('u', 'update', None,
5492 _('update to new branch head if changesets were unbundled'))],
5492 _('update to new branch head if changesets were unbundled'))],
5493 _('[-u] FILE...'))
5493 _('[-u] FILE...'))
5494 def unbundle(ui, repo, fname1, *fnames, **opts):
5494 def unbundle(ui, repo, fname1, *fnames, **opts):
5495 """apply one or more changegroup files
5495 """apply one or more changegroup files
5496
5496
5497 Apply one or more compressed changegroup files generated by the
5497 Apply one or more compressed changegroup files generated by the
5498 bundle command.
5498 bundle command.
5499
5499
5500 Returns 0 on success, 1 if an update has unresolved files.
5500 Returns 0 on success, 1 if an update has unresolved files.
5501 """
5501 """
5502 fnames = (fname1,) + fnames
5502 fnames = (fname1,) + fnames
5503
5503
5504 lock = repo.lock()
5504 lock = repo.lock()
5505 wc = repo['.']
5505 wc = repo['.']
5506 try:
5506 try:
5507 for fname in fnames:
5507 for fname in fnames:
5508 f = url.open(ui, fname)
5508 f = url.open(ui, fname)
5509 gen = changegroup.readbundle(f, fname)
5509 gen = changegroup.readbundle(f, fname)
5510 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5510 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5511 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5511 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5512 finally:
5512 finally:
5513 lock.release()
5513 lock.release()
5514 return postincoming(ui, repo, modheads, opts.get('update'), None)
5514 return postincoming(ui, repo, modheads, opts.get('update'), None)
5515
5515
5516 @command('^update|up|checkout|co',
5516 @command('^update|up|checkout|co',
5517 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5517 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5518 ('c', 'check', None,
5518 ('c', 'check', None,
5519 _('update across branches if no uncommitted changes')),
5519 _('update across branches if no uncommitted changes')),
5520 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5520 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5521 ('r', 'rev', '', _('revision'), _('REV'))],
5521 ('r', 'rev', '', _('revision'), _('REV'))],
5522 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5522 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5523 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5523 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5524 """update working directory (or switch revisions)
5524 """update working directory (or switch revisions)
5525
5525
5526 Update the repository's working directory to the specified
5526 Update the repository's working directory to the specified
5527 changeset. If no changeset is specified, update to the tip of the
5527 changeset. If no changeset is specified, update to the tip of the
5528 current named branch and move the current bookmark (see :hg:`help
5528 current named branch and move the current bookmark (see :hg:`help
5529 bookmarks`).
5529 bookmarks`).
5530
5530
5531 If the changeset is not a descendant of the working directory's
5531 If the changeset is not a descendant of the working directory's
5532 parent, the update is aborted. With the -c/--check option, the
5532 parent, the update is aborted. With the -c/--check option, the
5533 working directory is checked for uncommitted changes; if none are
5533 working directory is checked for uncommitted changes; if none are
5534 found, the working directory is updated to the specified
5534 found, the working directory is updated to the specified
5535 changeset.
5535 changeset.
5536
5536
5537 Update sets the working directory's parent revison to the specified
5537 Update sets the working directory's parent revison to the specified
5538 changeset (see :hg:`help parents`).
5538 changeset (see :hg:`help parents`).
5539
5539
5540 The following rules apply when the working directory contains
5540 The following rules apply when the working directory contains
5541 uncommitted changes:
5541 uncommitted changes:
5542
5542
5543 1. If neither -c/--check nor -C/--clean is specified, and if
5543 1. If neither -c/--check nor -C/--clean is specified, and if
5544 the requested changeset is an ancestor or descendant of
5544 the requested changeset is an ancestor or descendant of
5545 the working directory's parent, the uncommitted changes
5545 the working directory's parent, the uncommitted changes
5546 are merged into the requested changeset and the merged
5546 are merged into the requested changeset and the merged
5547 result is left uncommitted. If the requested changeset is
5547 result is left uncommitted. If the requested changeset is
5548 not an ancestor or descendant (that is, it is on another
5548 not an ancestor or descendant (that is, it is on another
5549 branch), the update is aborted and the uncommitted changes
5549 branch), the update is aborted and the uncommitted changes
5550 are preserved.
5550 are preserved.
5551
5551
5552 2. With the -c/--check option, the update is aborted and the
5552 2. With the -c/--check option, the update is aborted and the
5553 uncommitted changes are preserved.
5553 uncommitted changes are preserved.
5554
5554
5555 3. With the -C/--clean option, uncommitted changes are discarded and
5555 3. With the -C/--clean option, uncommitted changes are discarded and
5556 the working directory is updated to the requested changeset.
5556 the working directory is updated to the requested changeset.
5557
5557
5558 Use null as the changeset to remove the working directory (like
5558 Use null as the changeset to remove the working directory (like
5559 :hg:`clone -U`).
5559 :hg:`clone -U`).
5560
5560
5561 If you want to revert just one file to an older revision, use
5561 If you want to revert just one file to an older revision, use
5562 :hg:`revert [-r REV] NAME`.
5562 :hg:`revert [-r REV] NAME`.
5563
5563
5564 See :hg:`help dates` for a list of formats valid for -d/--date.
5564 See :hg:`help dates` for a list of formats valid for -d/--date.
5565
5565
5566 Returns 0 on success, 1 if there are unresolved files.
5566 Returns 0 on success, 1 if there are unresolved files.
5567 """
5567 """
5568 if rev and node:
5568 if rev and node:
5569 raise util.Abort(_("please specify just one revision"))
5569 raise util.Abort(_("please specify just one revision"))
5570
5570
5571 if rev is None or rev == '':
5571 if rev is None or rev == '':
5572 rev = node
5572 rev = node
5573
5573
5574 # with no argument, we also move the current bookmark, if any
5574 # with no argument, we also move the current bookmark, if any
5575 movemarkfrom = None
5575 movemarkfrom = None
5576 if rev is None or node == '':
5576 if rev is None or node == '':
5577 movemarkfrom = repo['.'].node()
5577 movemarkfrom = repo['.'].node()
5578
5578
5579 # if we defined a bookmark, we have to remember the original bookmark name
5579 # if we defined a bookmark, we have to remember the original bookmark name
5580 brev = rev
5580 brev = rev
5581 rev = scmutil.revsingle(repo, rev, rev).rev()
5581 rev = scmutil.revsingle(repo, rev, rev).rev()
5582
5582
5583 if check and clean:
5583 if check and clean:
5584 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5584 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5585
5585
5586 if date:
5586 if date:
5587 if rev is not None:
5587 if rev is not None:
5588 raise util.Abort(_("you can't specify a revision and a date"))
5588 raise util.Abort(_("you can't specify a revision and a date"))
5589 rev = cmdutil.finddate(ui, repo, date)
5589 rev = cmdutil.finddate(ui, repo, date)
5590
5590
5591 if check:
5591 if check:
5592 # we could use dirty() but we can ignore merge and branch trivia
5592 # we could use dirty() but we can ignore merge and branch trivia
5593 c = repo[None]
5593 c = repo[None]
5594 if c.modified() or c.added() or c.removed():
5594 if c.modified() or c.added() or c.removed():
5595 raise util.Abort(_("uncommitted local changes"))
5595 raise util.Abort(_("uncommitted local changes"))
5596 if not rev:
5596 if not rev:
5597 rev = repo[repo[None].branch()].rev()
5597 rev = repo[repo[None].branch()].rev()
5598 mergemod._checkunknown(repo, repo[None], repo[rev])
5598 mergemod._checkunknown(repo, repo[None], repo[rev])
5599
5599
5600 if clean:
5600 if clean:
5601 ret = hg.clean(repo, rev)
5601 ret = hg.clean(repo, rev)
5602 else:
5602 else:
5603 ret = hg.update(repo, rev)
5603 ret = hg.update(repo, rev)
5604
5604
5605 if not ret and movemarkfrom:
5605 if not ret and movemarkfrom:
5606 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5606 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5607 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5607 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5608 elif brev in repo._bookmarks:
5608 elif brev in repo._bookmarks:
5609 bookmarks.setcurrent(repo, brev)
5609 bookmarks.setcurrent(repo, brev)
5610 elif brev:
5610 elif brev:
5611 bookmarks.unsetcurrent(repo)
5611 bookmarks.unsetcurrent(repo)
5612
5612
5613 return ret
5613 return ret
5614
5614
5615 @command('verify', [])
5615 @command('verify', [])
5616 def verify(ui, repo):
5616 def verify(ui, repo):
5617 """verify the integrity of the repository
5617 """verify the integrity of the repository
5618
5618
5619 Verify the integrity of the current repository.
5619 Verify the integrity of the current repository.
5620
5620
5621 This will perform an extensive check of the repository's
5621 This will perform an extensive check of the repository's
5622 integrity, validating the hashes and checksums of each entry in
5622 integrity, validating the hashes and checksums of each entry in
5623 the changelog, manifest, and tracked files, as well as the
5623 the changelog, manifest, and tracked files, as well as the
5624 integrity of their crosslinks and indices.
5624 integrity of their crosslinks and indices.
5625
5625
5626 Returns 0 on success, 1 if errors are encountered.
5626 Returns 0 on success, 1 if errors are encountered.
5627 """
5627 """
5628 return hg.verify(repo)
5628 return hg.verify(repo)
5629
5629
5630 @command('version', [])
5630 @command('version', [])
5631 def version_(ui):
5631 def version_(ui):
5632 """output version and copyright information"""
5632 """output version and copyright information"""
5633 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5633 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5634 % util.version())
5634 % util.version())
5635 ui.status(_(
5635 ui.status(_(
5636 "(see http://mercurial.selenic.com for more information)\n"
5636 "(see http://mercurial.selenic.com for more information)\n"
5637 "\nCopyright (C) 2005-2012 Matt Mackall and others\n"
5637 "\nCopyright (C) 2005-2012 Matt Mackall and others\n"
5638 "This is free software; see the source for copying conditions. "
5638 "This is free software; see the source for copying conditions. "
5639 "There is NO\nwarranty; "
5639 "There is NO\nwarranty; "
5640 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5640 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5641 ))
5641 ))
5642
5642
5643 norepo = ("clone init version help debugcommands debugcomplete"
5643 norepo = ("clone init version help debugcommands debugcomplete"
5644 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5644 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5645 " debugknown debuggetbundle debugbundle")
5645 " debugknown debuggetbundle debugbundle")
5646 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5646 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5647 " debugdata debugindex debugindexdot debugrevlog")
5647 " debugdata debugindex debugindexdot debugrevlog")
@@ -1,1194 +1,1194 b''
1 # context.py - changeset and file context objects for mercurial
1 # context.py - changeset and file context objects for mercurial
2 #
2 #
3 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006, 2007 Matt Mackall <mpm@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 from node import nullid, nullrev, short, hex
8 from node import nullid, nullrev, short, hex
9 from i18n import _
9 from i18n import _
10 import ancestor, mdiff, error, util, scmutil, subrepo, patch, encoding, phases
10 import ancestor, mdiff, error, util, scmutil, subrepo, patch, encoding, phases
11 import match as matchmod
11 import match as matchmod
12 import os, errno, stat
12 import os, errno, stat
13
13
14 propertycache = util.propertycache
14 propertycache = util.propertycache
15
15
16 class changectx(object):
16 class changectx(object):
17 """A changecontext object makes access to data related to a particular
17 """A changecontext object makes access to data related to a particular
18 changeset convenient."""
18 changeset convenient."""
19 def __init__(self, repo, changeid=''):
19 def __init__(self, repo, changeid=''):
20 """changeid is a revision number, node, or tag"""
20 """changeid is a revision number, node, or tag"""
21 if changeid == '':
21 if changeid == '':
22 changeid = '.'
22 changeid = '.'
23 self._repo = repo
23 self._repo = repo
24 if isinstance(changeid, (long, int)):
24 if isinstance(changeid, (long, int)):
25 self._rev = changeid
25 self._rev = changeid
26 self._node = self._repo.changelog.node(changeid)
26 self._node = self._repo.changelog.node(changeid)
27 else:
27 else:
28 self._node = self._repo.lookup(changeid)
28 self._node = self._repo.lookup(changeid)
29 self._rev = self._repo.changelog.rev(self._node)
29 self._rev = self._repo.changelog.rev(self._node)
30
30
31 def __str__(self):
31 def __str__(self):
32 return short(self.node())
32 return short(self.node())
33
33
34 def __int__(self):
34 def __int__(self):
35 return self.rev()
35 return self.rev()
36
36
37 def __repr__(self):
37 def __repr__(self):
38 return "<changectx %s>" % str(self)
38 return "<changectx %s>" % str(self)
39
39
40 def __hash__(self):
40 def __hash__(self):
41 try:
41 try:
42 return hash(self._rev)
42 return hash(self._rev)
43 except AttributeError:
43 except AttributeError:
44 return id(self)
44 return id(self)
45
45
46 def __eq__(self, other):
46 def __eq__(self, other):
47 try:
47 try:
48 return self._rev == other._rev
48 return self._rev == other._rev
49 except AttributeError:
49 except AttributeError:
50 return False
50 return False
51
51
52 def __ne__(self, other):
52 def __ne__(self, other):
53 return not (self == other)
53 return not (self == other)
54
54
55 def __nonzero__(self):
55 def __nonzero__(self):
56 return self._rev != nullrev
56 return self._rev != nullrev
57
57
58 @propertycache
58 @propertycache
59 def _changeset(self):
59 def _changeset(self):
60 return self._repo.changelog.read(self.node())
60 return self._repo.changelog.read(self.node())
61
61
62 @propertycache
62 @propertycache
63 def _manifest(self):
63 def _manifest(self):
64 return self._repo.manifest.read(self._changeset[0])
64 return self._repo.manifest.read(self._changeset[0])
65
65
66 @propertycache
66 @propertycache
67 def _manifestdelta(self):
67 def _manifestdelta(self):
68 return self._repo.manifest.readdelta(self._changeset[0])
68 return self._repo.manifest.readdelta(self._changeset[0])
69
69
70 @propertycache
70 @propertycache
71 def _parents(self):
71 def _parents(self):
72 p = self._repo.changelog.parentrevs(self._rev)
72 p = self._repo.changelog.parentrevs(self._rev)
73 if p[1] == nullrev:
73 if p[1] == nullrev:
74 p = p[:-1]
74 p = p[:-1]
75 return [changectx(self._repo, x) for x in p]
75 return [changectx(self._repo, x) for x in p]
76
76
77 @propertycache
77 @propertycache
78 def substate(self):
78 def substate(self):
79 return subrepo.state(self, self._repo.ui)
79 return subrepo.state(self, self._repo.ui)
80
80
81 def __contains__(self, key):
81 def __contains__(self, key):
82 return key in self._manifest
82 return key in self._manifest
83
83
84 def __getitem__(self, key):
84 def __getitem__(self, key):
85 return self.filectx(key)
85 return self.filectx(key)
86
86
87 def __iter__(self):
87 def __iter__(self):
88 for f in sorted(self._manifest):
88 for f in sorted(self._manifest):
89 yield f
89 yield f
90
90
91 def changeset(self):
91 def changeset(self):
92 return self._changeset
92 return self._changeset
93 def manifest(self):
93 def manifest(self):
94 return self._manifest
94 return self._manifest
95 def manifestnode(self):
95 def manifestnode(self):
96 return self._changeset[0]
96 return self._changeset[0]
97
97
98 def rev(self):
98 def rev(self):
99 return self._rev
99 return self._rev
100 def node(self):
100 def node(self):
101 return self._node
101 return self._node
102 def hex(self):
102 def hex(self):
103 return hex(self._node)
103 return hex(self._node)
104 def user(self):
104 def user(self):
105 return self._changeset[1]
105 return self._changeset[1]
106 def date(self):
106 def date(self):
107 return self._changeset[2]
107 return self._changeset[2]
108 def files(self):
108 def files(self):
109 return self._changeset[3]
109 return self._changeset[3]
110 def description(self):
110 def description(self):
111 return self._changeset[4]
111 return self._changeset[4]
112 def branch(self):
112 def branch(self):
113 return encoding.tolocal(self._changeset[5].get("branch"))
113 return encoding.tolocal(self._changeset[5].get("branch"))
114 def extra(self):
114 def extra(self):
115 return self._changeset[5]
115 return self._changeset[5]
116 def tags(self):
116 def tags(self):
117 return self._repo.nodetags(self._node)
117 return self._repo.nodetags(self._node)
118 def bookmarks(self):
118 def bookmarks(self):
119 return self._repo.nodebookmarks(self._node)
119 return self._repo.nodebookmarks(self._node)
120 def phase(self):
120 def phase(self):
121 if self._rev == -1:
121 if self._rev == -1:
122 return phases.public
122 return phases.public
123 if self._rev >= len(self._repo._phaserev):
123 if self._rev >= len(self._repo._phaserev):
124 # outdated cache
124 # outdated cache
125 del self._repo._phaserev
125 del self._repo._phaserev
126 return self._repo._phaserev[self._rev]
126 return self._repo._phaserev[self._rev]
127 def phasestr(self):
127 def phasestr(self):
128 return phases.phasenames[self.phase()]
128 return phases.phasenames[self.phase()]
129 def mutable(self):
129 def mutable(self):
130 return self._repo._phaserev[self._rev] > phases.public
130 return self.phase() > phases.public
131 def hidden(self):
131 def hidden(self):
132 return self._rev in self._repo.changelog.hiddenrevs
132 return self._rev in self._repo.changelog.hiddenrevs
133
133
134 def parents(self):
134 def parents(self):
135 """return contexts for each parent changeset"""
135 """return contexts for each parent changeset"""
136 return self._parents
136 return self._parents
137
137
138 def p1(self):
138 def p1(self):
139 return self._parents[0]
139 return self._parents[0]
140
140
141 def p2(self):
141 def p2(self):
142 if len(self._parents) == 2:
142 if len(self._parents) == 2:
143 return self._parents[1]
143 return self._parents[1]
144 return changectx(self._repo, -1)
144 return changectx(self._repo, -1)
145
145
146 def children(self):
146 def children(self):
147 """return contexts for each child changeset"""
147 """return contexts for each child changeset"""
148 c = self._repo.changelog.children(self._node)
148 c = self._repo.changelog.children(self._node)
149 return [changectx(self._repo, x) for x in c]
149 return [changectx(self._repo, x) for x in c]
150
150
151 def ancestors(self):
151 def ancestors(self):
152 for a in self._repo.changelog.ancestors(self._rev):
152 for a in self._repo.changelog.ancestors(self._rev):
153 yield changectx(self._repo, a)
153 yield changectx(self._repo, a)
154
154
155 def descendants(self):
155 def descendants(self):
156 for d in self._repo.changelog.descendants(self._rev):
156 for d in self._repo.changelog.descendants(self._rev):
157 yield changectx(self._repo, d)
157 yield changectx(self._repo, d)
158
158
159 def _fileinfo(self, path):
159 def _fileinfo(self, path):
160 if '_manifest' in self.__dict__:
160 if '_manifest' in self.__dict__:
161 try:
161 try:
162 return self._manifest[path], self._manifest.flags(path)
162 return self._manifest[path], self._manifest.flags(path)
163 except KeyError:
163 except KeyError:
164 raise error.LookupError(self._node, path,
164 raise error.LookupError(self._node, path,
165 _('not found in manifest'))
165 _('not found in manifest'))
166 if '_manifestdelta' in self.__dict__ or path in self.files():
166 if '_manifestdelta' in self.__dict__ or path in self.files():
167 if path in self._manifestdelta:
167 if path in self._manifestdelta:
168 return self._manifestdelta[path], self._manifestdelta.flags(path)
168 return self._manifestdelta[path], self._manifestdelta.flags(path)
169 node, flag = self._repo.manifest.find(self._changeset[0], path)
169 node, flag = self._repo.manifest.find(self._changeset[0], path)
170 if not node:
170 if not node:
171 raise error.LookupError(self._node, path,
171 raise error.LookupError(self._node, path,
172 _('not found in manifest'))
172 _('not found in manifest'))
173
173
174 return node, flag
174 return node, flag
175
175
176 def filenode(self, path):
176 def filenode(self, path):
177 return self._fileinfo(path)[0]
177 return self._fileinfo(path)[0]
178
178
179 def flags(self, path):
179 def flags(self, path):
180 try:
180 try:
181 return self._fileinfo(path)[1]
181 return self._fileinfo(path)[1]
182 except error.LookupError:
182 except error.LookupError:
183 return ''
183 return ''
184
184
185 def filectx(self, path, fileid=None, filelog=None):
185 def filectx(self, path, fileid=None, filelog=None):
186 """get a file context from this changeset"""
186 """get a file context from this changeset"""
187 if fileid is None:
187 if fileid is None:
188 fileid = self.filenode(path)
188 fileid = self.filenode(path)
189 return filectx(self._repo, path, fileid=fileid,
189 return filectx(self._repo, path, fileid=fileid,
190 changectx=self, filelog=filelog)
190 changectx=self, filelog=filelog)
191
191
192 def ancestor(self, c2):
192 def ancestor(self, c2):
193 """
193 """
194 return the ancestor context of self and c2
194 return the ancestor context of self and c2
195 """
195 """
196 # deal with workingctxs
196 # deal with workingctxs
197 n2 = c2._node
197 n2 = c2._node
198 if n2 is None:
198 if n2 is None:
199 n2 = c2._parents[0]._node
199 n2 = c2._parents[0]._node
200 n = self._repo.changelog.ancestor(self._node, n2)
200 n = self._repo.changelog.ancestor(self._node, n2)
201 return changectx(self._repo, n)
201 return changectx(self._repo, n)
202
202
203 def walk(self, match):
203 def walk(self, match):
204 fset = set(match.files())
204 fset = set(match.files())
205 # for dirstate.walk, files=['.'] means "walk the whole tree".
205 # for dirstate.walk, files=['.'] means "walk the whole tree".
206 # follow that here, too
206 # follow that here, too
207 fset.discard('.')
207 fset.discard('.')
208 for fn in self:
208 for fn in self:
209 if fn in fset:
209 if fn in fset:
210 # specified pattern is the exact name
210 # specified pattern is the exact name
211 fset.remove(fn)
211 fset.remove(fn)
212 if match(fn):
212 if match(fn):
213 yield fn
213 yield fn
214 for fn in sorted(fset):
214 for fn in sorted(fset):
215 if fn in self._dirs:
215 if fn in self._dirs:
216 # specified pattern is a directory
216 # specified pattern is a directory
217 continue
217 continue
218 if match.bad(fn, _('no such file in rev %s') % self) and match(fn):
218 if match.bad(fn, _('no such file in rev %s') % self) and match(fn):
219 yield fn
219 yield fn
220
220
221 def sub(self, path):
221 def sub(self, path):
222 return subrepo.subrepo(self, path)
222 return subrepo.subrepo(self, path)
223
223
224 def match(self, pats=[], include=None, exclude=None, default='glob'):
224 def match(self, pats=[], include=None, exclude=None, default='glob'):
225 r = self._repo
225 r = self._repo
226 return matchmod.match(r.root, r.getcwd(), pats,
226 return matchmod.match(r.root, r.getcwd(), pats,
227 include, exclude, default,
227 include, exclude, default,
228 auditor=r.auditor, ctx=self)
228 auditor=r.auditor, ctx=self)
229
229
230 def diff(self, ctx2=None, match=None, **opts):
230 def diff(self, ctx2=None, match=None, **opts):
231 """Returns a diff generator for the given contexts and matcher"""
231 """Returns a diff generator for the given contexts and matcher"""
232 if ctx2 is None:
232 if ctx2 is None:
233 ctx2 = self.p1()
233 ctx2 = self.p1()
234 if ctx2 is not None and not isinstance(ctx2, changectx):
234 if ctx2 is not None and not isinstance(ctx2, changectx):
235 ctx2 = self._repo[ctx2]
235 ctx2 = self._repo[ctx2]
236 diffopts = patch.diffopts(self._repo.ui, opts)
236 diffopts = patch.diffopts(self._repo.ui, opts)
237 return patch.diff(self._repo, ctx2.node(), self.node(),
237 return patch.diff(self._repo, ctx2.node(), self.node(),
238 match=match, opts=diffopts)
238 match=match, opts=diffopts)
239
239
240 @propertycache
240 @propertycache
241 def _dirs(self):
241 def _dirs(self):
242 dirs = set()
242 dirs = set()
243 for f in self._manifest:
243 for f in self._manifest:
244 pos = f.rfind('/')
244 pos = f.rfind('/')
245 while pos != -1:
245 while pos != -1:
246 f = f[:pos]
246 f = f[:pos]
247 if f in dirs:
247 if f in dirs:
248 break # dirs already contains this and above
248 break # dirs already contains this and above
249 dirs.add(f)
249 dirs.add(f)
250 pos = f.rfind('/')
250 pos = f.rfind('/')
251 return dirs
251 return dirs
252
252
253 def dirs(self):
253 def dirs(self):
254 return self._dirs
254 return self._dirs
255
255
256 class filectx(object):
256 class filectx(object):
257 """A filecontext object makes access to data related to a particular
257 """A filecontext object makes access to data related to a particular
258 filerevision convenient."""
258 filerevision convenient."""
259 def __init__(self, repo, path, changeid=None, fileid=None,
259 def __init__(self, repo, path, changeid=None, fileid=None,
260 filelog=None, changectx=None):
260 filelog=None, changectx=None):
261 """changeid can be a changeset revision, node, or tag.
261 """changeid can be a changeset revision, node, or tag.
262 fileid can be a file revision or node."""
262 fileid can be a file revision or node."""
263 self._repo = repo
263 self._repo = repo
264 self._path = path
264 self._path = path
265
265
266 assert (changeid is not None
266 assert (changeid is not None
267 or fileid is not None
267 or fileid is not None
268 or changectx is not None), \
268 or changectx is not None), \
269 ("bad args: changeid=%r, fileid=%r, changectx=%r"
269 ("bad args: changeid=%r, fileid=%r, changectx=%r"
270 % (changeid, fileid, changectx))
270 % (changeid, fileid, changectx))
271
271
272 if filelog:
272 if filelog:
273 self._filelog = filelog
273 self._filelog = filelog
274
274
275 if changeid is not None:
275 if changeid is not None:
276 self._changeid = changeid
276 self._changeid = changeid
277 if changectx is not None:
277 if changectx is not None:
278 self._changectx = changectx
278 self._changectx = changectx
279 if fileid is not None:
279 if fileid is not None:
280 self._fileid = fileid
280 self._fileid = fileid
281
281
282 @propertycache
282 @propertycache
283 def _changectx(self):
283 def _changectx(self):
284 return changectx(self._repo, self._changeid)
284 return changectx(self._repo, self._changeid)
285
285
286 @propertycache
286 @propertycache
287 def _filelog(self):
287 def _filelog(self):
288 return self._repo.file(self._path)
288 return self._repo.file(self._path)
289
289
290 @propertycache
290 @propertycache
291 def _changeid(self):
291 def _changeid(self):
292 if '_changectx' in self.__dict__:
292 if '_changectx' in self.__dict__:
293 return self._changectx.rev()
293 return self._changectx.rev()
294 else:
294 else:
295 return self._filelog.linkrev(self._filerev)
295 return self._filelog.linkrev(self._filerev)
296
296
297 @propertycache
297 @propertycache
298 def _filenode(self):
298 def _filenode(self):
299 if '_fileid' in self.__dict__:
299 if '_fileid' in self.__dict__:
300 return self._filelog.lookup(self._fileid)
300 return self._filelog.lookup(self._fileid)
301 else:
301 else:
302 return self._changectx.filenode(self._path)
302 return self._changectx.filenode(self._path)
303
303
304 @propertycache
304 @propertycache
305 def _filerev(self):
305 def _filerev(self):
306 return self._filelog.rev(self._filenode)
306 return self._filelog.rev(self._filenode)
307
307
308 @propertycache
308 @propertycache
309 def _repopath(self):
309 def _repopath(self):
310 return self._path
310 return self._path
311
311
312 def __nonzero__(self):
312 def __nonzero__(self):
313 try:
313 try:
314 self._filenode
314 self._filenode
315 return True
315 return True
316 except error.LookupError:
316 except error.LookupError:
317 # file is missing
317 # file is missing
318 return False
318 return False
319
319
320 def __str__(self):
320 def __str__(self):
321 return "%s@%s" % (self.path(), short(self.node()))
321 return "%s@%s" % (self.path(), short(self.node()))
322
322
323 def __repr__(self):
323 def __repr__(self):
324 return "<filectx %s>" % str(self)
324 return "<filectx %s>" % str(self)
325
325
326 def __hash__(self):
326 def __hash__(self):
327 try:
327 try:
328 return hash((self._path, self._filenode))
328 return hash((self._path, self._filenode))
329 except AttributeError:
329 except AttributeError:
330 return id(self)
330 return id(self)
331
331
332 def __eq__(self, other):
332 def __eq__(self, other):
333 try:
333 try:
334 return (self._path == other._path
334 return (self._path == other._path
335 and self._filenode == other._filenode)
335 and self._filenode == other._filenode)
336 except AttributeError:
336 except AttributeError:
337 return False
337 return False
338
338
339 def __ne__(self, other):
339 def __ne__(self, other):
340 return not (self == other)
340 return not (self == other)
341
341
342 def filectx(self, fileid):
342 def filectx(self, fileid):
343 '''opens an arbitrary revision of the file without
343 '''opens an arbitrary revision of the file without
344 opening a new filelog'''
344 opening a new filelog'''
345 return filectx(self._repo, self._path, fileid=fileid,
345 return filectx(self._repo, self._path, fileid=fileid,
346 filelog=self._filelog)
346 filelog=self._filelog)
347
347
348 def filerev(self):
348 def filerev(self):
349 return self._filerev
349 return self._filerev
350 def filenode(self):
350 def filenode(self):
351 return self._filenode
351 return self._filenode
352 def flags(self):
352 def flags(self):
353 return self._changectx.flags(self._path)
353 return self._changectx.flags(self._path)
354 def filelog(self):
354 def filelog(self):
355 return self._filelog
355 return self._filelog
356
356
357 def rev(self):
357 def rev(self):
358 if '_changectx' in self.__dict__:
358 if '_changectx' in self.__dict__:
359 return self._changectx.rev()
359 return self._changectx.rev()
360 if '_changeid' in self.__dict__:
360 if '_changeid' in self.__dict__:
361 return self._changectx.rev()
361 return self._changectx.rev()
362 return self._filelog.linkrev(self._filerev)
362 return self._filelog.linkrev(self._filerev)
363
363
364 def linkrev(self):
364 def linkrev(self):
365 return self._filelog.linkrev(self._filerev)
365 return self._filelog.linkrev(self._filerev)
366 def node(self):
366 def node(self):
367 return self._changectx.node()
367 return self._changectx.node()
368 def hex(self):
368 def hex(self):
369 return hex(self.node())
369 return hex(self.node())
370 def user(self):
370 def user(self):
371 return self._changectx.user()
371 return self._changectx.user()
372 def date(self):
372 def date(self):
373 return self._changectx.date()
373 return self._changectx.date()
374 def files(self):
374 def files(self):
375 return self._changectx.files()
375 return self._changectx.files()
376 def description(self):
376 def description(self):
377 return self._changectx.description()
377 return self._changectx.description()
378 def branch(self):
378 def branch(self):
379 return self._changectx.branch()
379 return self._changectx.branch()
380 def extra(self):
380 def extra(self):
381 return self._changectx.extra()
381 return self._changectx.extra()
382 def manifest(self):
382 def manifest(self):
383 return self._changectx.manifest()
383 return self._changectx.manifest()
384 def changectx(self):
384 def changectx(self):
385 return self._changectx
385 return self._changectx
386
386
387 def data(self):
387 def data(self):
388 return self._filelog.read(self._filenode)
388 return self._filelog.read(self._filenode)
389 def path(self):
389 def path(self):
390 return self._path
390 return self._path
391 def size(self):
391 def size(self):
392 return self._filelog.size(self._filerev)
392 return self._filelog.size(self._filerev)
393
393
394 def isbinary(self):
394 def isbinary(self):
395 try:
395 try:
396 return util.binary(self.data())
396 return util.binary(self.data())
397 except IOError:
397 except IOError:
398 return False
398 return False
399
399
400 def cmp(self, fctx):
400 def cmp(self, fctx):
401 """compare with other file context
401 """compare with other file context
402
402
403 returns True if different than fctx.
403 returns True if different than fctx.
404 """
404 """
405 if (fctx._filerev is None
405 if (fctx._filerev is None
406 and (self._repo._encodefilterpats
406 and (self._repo._encodefilterpats
407 # if file data starts with '\1\n', empty metadata block is
407 # if file data starts with '\1\n', empty metadata block is
408 # prepended, which adds 4 bytes to filelog.size().
408 # prepended, which adds 4 bytes to filelog.size().
409 or self.size() - 4 == fctx.size())
409 or self.size() - 4 == fctx.size())
410 or self.size() == fctx.size()):
410 or self.size() == fctx.size()):
411 return self._filelog.cmp(self._filenode, fctx.data())
411 return self._filelog.cmp(self._filenode, fctx.data())
412
412
413 return True
413 return True
414
414
415 def renamed(self):
415 def renamed(self):
416 """check if file was actually renamed in this changeset revision
416 """check if file was actually renamed in this changeset revision
417
417
418 If rename logged in file revision, we report copy for changeset only
418 If rename logged in file revision, we report copy for changeset only
419 if file revisions linkrev points back to the changeset in question
419 if file revisions linkrev points back to the changeset in question
420 or both changeset parents contain different file revisions.
420 or both changeset parents contain different file revisions.
421 """
421 """
422
422
423 renamed = self._filelog.renamed(self._filenode)
423 renamed = self._filelog.renamed(self._filenode)
424 if not renamed:
424 if not renamed:
425 return renamed
425 return renamed
426
426
427 if self.rev() == self.linkrev():
427 if self.rev() == self.linkrev():
428 return renamed
428 return renamed
429
429
430 name = self.path()
430 name = self.path()
431 fnode = self._filenode
431 fnode = self._filenode
432 for p in self._changectx.parents():
432 for p in self._changectx.parents():
433 try:
433 try:
434 if fnode == p.filenode(name):
434 if fnode == p.filenode(name):
435 return None
435 return None
436 except error.LookupError:
436 except error.LookupError:
437 pass
437 pass
438 return renamed
438 return renamed
439
439
440 def parents(self):
440 def parents(self):
441 p = self._path
441 p = self._path
442 fl = self._filelog
442 fl = self._filelog
443 pl = [(p, n, fl) for n in self._filelog.parents(self._filenode)]
443 pl = [(p, n, fl) for n in self._filelog.parents(self._filenode)]
444
444
445 r = self._filelog.renamed(self._filenode)
445 r = self._filelog.renamed(self._filenode)
446 if r:
446 if r:
447 pl[0] = (r[0], r[1], None)
447 pl[0] = (r[0], r[1], None)
448
448
449 return [filectx(self._repo, p, fileid=n, filelog=l)
449 return [filectx(self._repo, p, fileid=n, filelog=l)
450 for p, n, l in pl if n != nullid]
450 for p, n, l in pl if n != nullid]
451
451
452 def p1(self):
452 def p1(self):
453 return self.parents()[0]
453 return self.parents()[0]
454
454
455 def p2(self):
455 def p2(self):
456 p = self.parents()
456 p = self.parents()
457 if len(p) == 2:
457 if len(p) == 2:
458 return p[1]
458 return p[1]
459 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
459 return filectx(self._repo, self._path, fileid=-1, filelog=self._filelog)
460
460
461 def children(self):
461 def children(self):
462 # hard for renames
462 # hard for renames
463 c = self._filelog.children(self._filenode)
463 c = self._filelog.children(self._filenode)
464 return [filectx(self._repo, self._path, fileid=x,
464 return [filectx(self._repo, self._path, fileid=x,
465 filelog=self._filelog) for x in c]
465 filelog=self._filelog) for x in c]
466
466
467 def annotate(self, follow=False, linenumber=None, diffopts=None):
467 def annotate(self, follow=False, linenumber=None, diffopts=None):
468 '''returns a list of tuples of (ctx, line) for each line
468 '''returns a list of tuples of (ctx, line) for each line
469 in the file, where ctx is the filectx of the node where
469 in the file, where ctx is the filectx of the node where
470 that line was last changed.
470 that line was last changed.
471 This returns tuples of ((ctx, linenumber), line) for each line,
471 This returns tuples of ((ctx, linenumber), line) for each line,
472 if "linenumber" parameter is NOT "None".
472 if "linenumber" parameter is NOT "None".
473 In such tuples, linenumber means one at the first appearance
473 In such tuples, linenumber means one at the first appearance
474 in the managed file.
474 in the managed file.
475 To reduce annotation cost,
475 To reduce annotation cost,
476 this returns fixed value(False is used) as linenumber,
476 this returns fixed value(False is used) as linenumber,
477 if "linenumber" parameter is "False".'''
477 if "linenumber" parameter is "False".'''
478
478
479 def decorate_compat(text, rev):
479 def decorate_compat(text, rev):
480 return ([rev] * len(text.splitlines()), text)
480 return ([rev] * len(text.splitlines()), text)
481
481
482 def without_linenumber(text, rev):
482 def without_linenumber(text, rev):
483 return ([(rev, False)] * len(text.splitlines()), text)
483 return ([(rev, False)] * len(text.splitlines()), text)
484
484
485 def with_linenumber(text, rev):
485 def with_linenumber(text, rev):
486 size = len(text.splitlines())
486 size = len(text.splitlines())
487 return ([(rev, i) for i in xrange(1, size + 1)], text)
487 return ([(rev, i) for i in xrange(1, size + 1)], text)
488
488
489 decorate = (((linenumber is None) and decorate_compat) or
489 decorate = (((linenumber is None) and decorate_compat) or
490 (linenumber and with_linenumber) or
490 (linenumber and with_linenumber) or
491 without_linenumber)
491 without_linenumber)
492
492
493 def pair(parent, child):
493 def pair(parent, child):
494 blocks = mdiff.allblocks(parent[1], child[1], opts=diffopts,
494 blocks = mdiff.allblocks(parent[1], child[1], opts=diffopts,
495 refine=True)
495 refine=True)
496 for (a1, a2, b1, b2), t in blocks:
496 for (a1, a2, b1, b2), t in blocks:
497 # Changed blocks ('!') or blocks made only of blank lines ('~')
497 # Changed blocks ('!') or blocks made only of blank lines ('~')
498 # belong to the child.
498 # belong to the child.
499 if t == '=':
499 if t == '=':
500 child[0][b1:b2] = parent[0][a1:a2]
500 child[0][b1:b2] = parent[0][a1:a2]
501 return child
501 return child
502
502
503 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
503 getlog = util.lrucachefunc(lambda x: self._repo.file(x))
504 def getctx(path, fileid):
504 def getctx(path, fileid):
505 log = path == self._path and self._filelog or getlog(path)
505 log = path == self._path and self._filelog or getlog(path)
506 return filectx(self._repo, path, fileid=fileid, filelog=log)
506 return filectx(self._repo, path, fileid=fileid, filelog=log)
507 getctx = util.lrucachefunc(getctx)
507 getctx = util.lrucachefunc(getctx)
508
508
509 def parents(f):
509 def parents(f):
510 # we want to reuse filectx objects as much as possible
510 # we want to reuse filectx objects as much as possible
511 p = f._path
511 p = f._path
512 if f._filerev is None: # working dir
512 if f._filerev is None: # working dir
513 pl = [(n.path(), n.filerev()) for n in f.parents()]
513 pl = [(n.path(), n.filerev()) for n in f.parents()]
514 else:
514 else:
515 pl = [(p, n) for n in f._filelog.parentrevs(f._filerev)]
515 pl = [(p, n) for n in f._filelog.parentrevs(f._filerev)]
516
516
517 if follow:
517 if follow:
518 r = f.renamed()
518 r = f.renamed()
519 if r:
519 if r:
520 pl[0] = (r[0], getlog(r[0]).rev(r[1]))
520 pl[0] = (r[0], getlog(r[0]).rev(r[1]))
521
521
522 return [getctx(p, n) for p, n in pl if n != nullrev]
522 return [getctx(p, n) for p, n in pl if n != nullrev]
523
523
524 # use linkrev to find the first changeset where self appeared
524 # use linkrev to find the first changeset where self appeared
525 if self.rev() != self.linkrev():
525 if self.rev() != self.linkrev():
526 base = self.filectx(self.filerev())
526 base = self.filectx(self.filerev())
527 else:
527 else:
528 base = self
528 base = self
529
529
530 # This algorithm would prefer to be recursive, but Python is a
530 # This algorithm would prefer to be recursive, but Python is a
531 # bit recursion-hostile. Instead we do an iterative
531 # bit recursion-hostile. Instead we do an iterative
532 # depth-first search.
532 # depth-first search.
533
533
534 visit = [base]
534 visit = [base]
535 hist = {}
535 hist = {}
536 pcache = {}
536 pcache = {}
537 needed = {base: 1}
537 needed = {base: 1}
538 while visit:
538 while visit:
539 f = visit[-1]
539 f = visit[-1]
540 if f not in pcache:
540 if f not in pcache:
541 pcache[f] = parents(f)
541 pcache[f] = parents(f)
542
542
543 ready = True
543 ready = True
544 pl = pcache[f]
544 pl = pcache[f]
545 for p in pl:
545 for p in pl:
546 if p not in hist:
546 if p not in hist:
547 ready = False
547 ready = False
548 visit.append(p)
548 visit.append(p)
549 needed[p] = needed.get(p, 0) + 1
549 needed[p] = needed.get(p, 0) + 1
550 if ready:
550 if ready:
551 visit.pop()
551 visit.pop()
552 curr = decorate(f.data(), f)
552 curr = decorate(f.data(), f)
553 for p in pl:
553 for p in pl:
554 curr = pair(hist[p], curr)
554 curr = pair(hist[p], curr)
555 if needed[p] == 1:
555 if needed[p] == 1:
556 del hist[p]
556 del hist[p]
557 else:
557 else:
558 needed[p] -= 1
558 needed[p] -= 1
559
559
560 hist[f] = curr
560 hist[f] = curr
561 pcache[f] = []
561 pcache[f] = []
562
562
563 return zip(hist[base][0], hist[base][1].splitlines(True))
563 return zip(hist[base][0], hist[base][1].splitlines(True))
564
564
565 def ancestor(self, fc2, actx=None):
565 def ancestor(self, fc2, actx=None):
566 """
566 """
567 find the common ancestor file context, if any, of self, and fc2
567 find the common ancestor file context, if any, of self, and fc2
568
568
569 If actx is given, it must be the changectx of the common ancestor
569 If actx is given, it must be the changectx of the common ancestor
570 of self's and fc2's respective changesets.
570 of self's and fc2's respective changesets.
571 """
571 """
572
572
573 if actx is None:
573 if actx is None:
574 actx = self.changectx().ancestor(fc2.changectx())
574 actx = self.changectx().ancestor(fc2.changectx())
575
575
576 # the trivial case: changesets are unrelated, files must be too
576 # the trivial case: changesets are unrelated, files must be too
577 if not actx:
577 if not actx:
578 return None
578 return None
579
579
580 # the easy case: no (relevant) renames
580 # the easy case: no (relevant) renames
581 if fc2.path() == self.path() and self.path() in actx:
581 if fc2.path() == self.path() and self.path() in actx:
582 return actx[self.path()]
582 return actx[self.path()]
583 acache = {}
583 acache = {}
584
584
585 # prime the ancestor cache for the working directory
585 # prime the ancestor cache for the working directory
586 for c in (self, fc2):
586 for c in (self, fc2):
587 if c._filerev is None:
587 if c._filerev is None:
588 pl = [(n.path(), n.filenode()) for n in c.parents()]
588 pl = [(n.path(), n.filenode()) for n in c.parents()]
589 acache[(c._path, None)] = pl
589 acache[(c._path, None)] = pl
590
590
591 flcache = {self._repopath:self._filelog, fc2._repopath:fc2._filelog}
591 flcache = {self._repopath:self._filelog, fc2._repopath:fc2._filelog}
592 def parents(vertex):
592 def parents(vertex):
593 if vertex in acache:
593 if vertex in acache:
594 return acache[vertex]
594 return acache[vertex]
595 f, n = vertex
595 f, n = vertex
596 if f not in flcache:
596 if f not in flcache:
597 flcache[f] = self._repo.file(f)
597 flcache[f] = self._repo.file(f)
598 fl = flcache[f]
598 fl = flcache[f]
599 pl = [(f, p) for p in fl.parents(n) if p != nullid]
599 pl = [(f, p) for p in fl.parents(n) if p != nullid]
600 re = fl.renamed(n)
600 re = fl.renamed(n)
601 if re:
601 if re:
602 pl.append(re)
602 pl.append(re)
603 acache[vertex] = pl
603 acache[vertex] = pl
604 return pl
604 return pl
605
605
606 a, b = (self._path, self._filenode), (fc2._path, fc2._filenode)
606 a, b = (self._path, self._filenode), (fc2._path, fc2._filenode)
607 v = ancestor.ancestor(a, b, parents)
607 v = ancestor.ancestor(a, b, parents)
608 if v:
608 if v:
609 f, n = v
609 f, n = v
610 return filectx(self._repo, f, fileid=n, filelog=flcache[f])
610 return filectx(self._repo, f, fileid=n, filelog=flcache[f])
611
611
612 return None
612 return None
613
613
614 def ancestors(self, followfirst=False):
614 def ancestors(self, followfirst=False):
615 visit = {}
615 visit = {}
616 c = self
616 c = self
617 cut = followfirst and 1 or None
617 cut = followfirst and 1 or None
618 while True:
618 while True:
619 for parent in c.parents()[:cut]:
619 for parent in c.parents()[:cut]:
620 visit[(parent.rev(), parent.node())] = parent
620 visit[(parent.rev(), parent.node())] = parent
621 if not visit:
621 if not visit:
622 break
622 break
623 c = visit.pop(max(visit))
623 c = visit.pop(max(visit))
624 yield c
624 yield c
625
625
626 class workingctx(changectx):
626 class workingctx(changectx):
627 """A workingctx object makes access to data related to
627 """A workingctx object makes access to data related to
628 the current working directory convenient.
628 the current working directory convenient.
629 date - any valid date string or (unixtime, offset), or None.
629 date - any valid date string or (unixtime, offset), or None.
630 user - username string, or None.
630 user - username string, or None.
631 extra - a dictionary of extra values, or None.
631 extra - a dictionary of extra values, or None.
632 changes - a list of file lists as returned by localrepo.status()
632 changes - a list of file lists as returned by localrepo.status()
633 or None to use the repository status.
633 or None to use the repository status.
634 """
634 """
635 def __init__(self, repo, text="", user=None, date=None, extra=None,
635 def __init__(self, repo, text="", user=None, date=None, extra=None,
636 changes=None):
636 changes=None):
637 self._repo = repo
637 self._repo = repo
638 self._rev = None
638 self._rev = None
639 self._node = None
639 self._node = None
640 self._text = text
640 self._text = text
641 if date:
641 if date:
642 self._date = util.parsedate(date)
642 self._date = util.parsedate(date)
643 if user:
643 if user:
644 self._user = user
644 self._user = user
645 if changes:
645 if changes:
646 self._status = list(changes[:4])
646 self._status = list(changes[:4])
647 self._unknown = changes[4]
647 self._unknown = changes[4]
648 self._ignored = changes[5]
648 self._ignored = changes[5]
649 self._clean = changes[6]
649 self._clean = changes[6]
650 else:
650 else:
651 self._unknown = None
651 self._unknown = None
652 self._ignored = None
652 self._ignored = None
653 self._clean = None
653 self._clean = None
654
654
655 self._extra = {}
655 self._extra = {}
656 if extra:
656 if extra:
657 self._extra = extra.copy()
657 self._extra = extra.copy()
658 if 'branch' not in self._extra:
658 if 'branch' not in self._extra:
659 try:
659 try:
660 branch = encoding.fromlocal(self._repo.dirstate.branch())
660 branch = encoding.fromlocal(self._repo.dirstate.branch())
661 except UnicodeDecodeError:
661 except UnicodeDecodeError:
662 raise util.Abort(_('branch name not in UTF-8!'))
662 raise util.Abort(_('branch name not in UTF-8!'))
663 self._extra['branch'] = branch
663 self._extra['branch'] = branch
664 if self._extra['branch'] == '':
664 if self._extra['branch'] == '':
665 self._extra['branch'] = 'default'
665 self._extra['branch'] = 'default'
666
666
667 def __str__(self):
667 def __str__(self):
668 return str(self._parents[0]) + "+"
668 return str(self._parents[0]) + "+"
669
669
670 def __repr__(self):
670 def __repr__(self):
671 return "<workingctx %s>" % str(self)
671 return "<workingctx %s>" % str(self)
672
672
673 def __nonzero__(self):
673 def __nonzero__(self):
674 return True
674 return True
675
675
676 def __contains__(self, key):
676 def __contains__(self, key):
677 return self._repo.dirstate[key] not in "?r"
677 return self._repo.dirstate[key] not in "?r"
678
678
679 def _buildflagfunc(self):
679 def _buildflagfunc(self):
680 # Create a fallback function for getting file flags when the
680 # Create a fallback function for getting file flags when the
681 # filesystem doesn't support them
681 # filesystem doesn't support them
682
682
683 copiesget = self._repo.dirstate.copies().get
683 copiesget = self._repo.dirstate.copies().get
684
684
685 if len(self._parents) < 2:
685 if len(self._parents) < 2:
686 # when we have one parent, it's easy: copy from parent
686 # when we have one parent, it's easy: copy from parent
687 man = self._parents[0].manifest()
687 man = self._parents[0].manifest()
688 def func(f):
688 def func(f):
689 f = copiesget(f, f)
689 f = copiesget(f, f)
690 return man.flags(f)
690 return man.flags(f)
691 else:
691 else:
692 # merges are tricky: we try to reconstruct the unstored
692 # merges are tricky: we try to reconstruct the unstored
693 # result from the merge (issue1802)
693 # result from the merge (issue1802)
694 p1, p2 = self._parents
694 p1, p2 = self._parents
695 pa = p1.ancestor(p2)
695 pa = p1.ancestor(p2)
696 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
696 m1, m2, ma = p1.manifest(), p2.manifest(), pa.manifest()
697
697
698 def func(f):
698 def func(f):
699 f = copiesget(f, f) # may be wrong for merges with copies
699 f = copiesget(f, f) # may be wrong for merges with copies
700 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
700 fl1, fl2, fla = m1.flags(f), m2.flags(f), ma.flags(f)
701 if fl1 == fl2:
701 if fl1 == fl2:
702 return fl1
702 return fl1
703 if fl1 == fla:
703 if fl1 == fla:
704 return fl2
704 return fl2
705 if fl2 == fla:
705 if fl2 == fla:
706 return fl1
706 return fl1
707 return '' # punt for conflicts
707 return '' # punt for conflicts
708
708
709 return func
709 return func
710
710
711 @propertycache
711 @propertycache
712 def _flagfunc(self):
712 def _flagfunc(self):
713 return self._repo.dirstate.flagfunc(self._buildflagfunc)
713 return self._repo.dirstate.flagfunc(self._buildflagfunc)
714
714
715 @propertycache
715 @propertycache
716 def _manifest(self):
716 def _manifest(self):
717 """generate a manifest corresponding to the working directory"""
717 """generate a manifest corresponding to the working directory"""
718
718
719 man = self._parents[0].manifest().copy()
719 man = self._parents[0].manifest().copy()
720 if len(self._parents) > 1:
720 if len(self._parents) > 1:
721 man2 = self.p2().manifest()
721 man2 = self.p2().manifest()
722 def getman(f):
722 def getman(f):
723 if f in man:
723 if f in man:
724 return man
724 return man
725 return man2
725 return man2
726 else:
726 else:
727 getman = lambda f: man
727 getman = lambda f: man
728
728
729 copied = self._repo.dirstate.copies()
729 copied = self._repo.dirstate.copies()
730 ff = self._flagfunc
730 ff = self._flagfunc
731 modified, added, removed, deleted = self._status
731 modified, added, removed, deleted = self._status
732 for i, l in (("a", added), ("m", modified)):
732 for i, l in (("a", added), ("m", modified)):
733 for f in l:
733 for f in l:
734 orig = copied.get(f, f)
734 orig = copied.get(f, f)
735 man[f] = getman(orig).get(orig, nullid) + i
735 man[f] = getman(orig).get(orig, nullid) + i
736 try:
736 try:
737 man.set(f, ff(f))
737 man.set(f, ff(f))
738 except OSError:
738 except OSError:
739 pass
739 pass
740
740
741 for f in deleted + removed:
741 for f in deleted + removed:
742 if f in man:
742 if f in man:
743 del man[f]
743 del man[f]
744
744
745 return man
745 return man
746
746
747 def __iter__(self):
747 def __iter__(self):
748 d = self._repo.dirstate
748 d = self._repo.dirstate
749 for f in d:
749 for f in d:
750 if d[f] != 'r':
750 if d[f] != 'r':
751 yield f
751 yield f
752
752
753 @propertycache
753 @propertycache
754 def _status(self):
754 def _status(self):
755 return self._repo.status()[:4]
755 return self._repo.status()[:4]
756
756
757 @propertycache
757 @propertycache
758 def _user(self):
758 def _user(self):
759 return self._repo.ui.username()
759 return self._repo.ui.username()
760
760
761 @propertycache
761 @propertycache
762 def _date(self):
762 def _date(self):
763 return util.makedate()
763 return util.makedate()
764
764
765 @propertycache
765 @propertycache
766 def _parents(self):
766 def _parents(self):
767 p = self._repo.dirstate.parents()
767 p = self._repo.dirstate.parents()
768 if p[1] == nullid:
768 if p[1] == nullid:
769 p = p[:-1]
769 p = p[:-1]
770 self._parents = [changectx(self._repo, x) for x in p]
770 self._parents = [changectx(self._repo, x) for x in p]
771 return self._parents
771 return self._parents
772
772
773 def status(self, ignored=False, clean=False, unknown=False):
773 def status(self, ignored=False, clean=False, unknown=False):
774 """Explicit status query
774 """Explicit status query
775 Unless this method is used to query the working copy status, the
775 Unless this method is used to query the working copy status, the
776 _status property will implicitly read the status using its default
776 _status property will implicitly read the status using its default
777 arguments."""
777 arguments."""
778 stat = self._repo.status(ignored=ignored, clean=clean, unknown=unknown)
778 stat = self._repo.status(ignored=ignored, clean=clean, unknown=unknown)
779 self._unknown = self._ignored = self._clean = None
779 self._unknown = self._ignored = self._clean = None
780 if unknown:
780 if unknown:
781 self._unknown = stat[4]
781 self._unknown = stat[4]
782 if ignored:
782 if ignored:
783 self._ignored = stat[5]
783 self._ignored = stat[5]
784 if clean:
784 if clean:
785 self._clean = stat[6]
785 self._clean = stat[6]
786 self._status = stat[:4]
786 self._status = stat[:4]
787 return stat
787 return stat
788
788
789 def manifest(self):
789 def manifest(self):
790 return self._manifest
790 return self._manifest
791 def user(self):
791 def user(self):
792 return self._user or self._repo.ui.username()
792 return self._user or self._repo.ui.username()
793 def date(self):
793 def date(self):
794 return self._date
794 return self._date
795 def description(self):
795 def description(self):
796 return self._text
796 return self._text
797 def files(self):
797 def files(self):
798 return sorted(self._status[0] + self._status[1] + self._status[2])
798 return sorted(self._status[0] + self._status[1] + self._status[2])
799
799
800 def modified(self):
800 def modified(self):
801 return self._status[0]
801 return self._status[0]
802 def added(self):
802 def added(self):
803 return self._status[1]
803 return self._status[1]
804 def removed(self):
804 def removed(self):
805 return self._status[2]
805 return self._status[2]
806 def deleted(self):
806 def deleted(self):
807 return self._status[3]
807 return self._status[3]
808 def unknown(self):
808 def unknown(self):
809 assert self._unknown is not None # must call status first
809 assert self._unknown is not None # must call status first
810 return self._unknown
810 return self._unknown
811 def ignored(self):
811 def ignored(self):
812 assert self._ignored is not None # must call status first
812 assert self._ignored is not None # must call status first
813 return self._ignored
813 return self._ignored
814 def clean(self):
814 def clean(self):
815 assert self._clean is not None # must call status first
815 assert self._clean is not None # must call status first
816 return self._clean
816 return self._clean
817 def branch(self):
817 def branch(self):
818 return encoding.tolocal(self._extra['branch'])
818 return encoding.tolocal(self._extra['branch'])
819 def extra(self):
819 def extra(self):
820 return self._extra
820 return self._extra
821
821
822 def tags(self):
822 def tags(self):
823 t = []
823 t = []
824 for p in self.parents():
824 for p in self.parents():
825 t.extend(p.tags())
825 t.extend(p.tags())
826 return t
826 return t
827
827
828 def bookmarks(self):
828 def bookmarks(self):
829 b = []
829 b = []
830 for p in self.parents():
830 for p in self.parents():
831 b.extend(p.bookmarks())
831 b.extend(p.bookmarks())
832 return b
832 return b
833
833
834 def phase(self):
834 def phase(self):
835 phase = phases.draft # default phase to draft
835 phase = phases.draft # default phase to draft
836 for p in self.parents():
836 for p in self.parents():
837 phase = max(phase, p.phase())
837 phase = max(phase, p.phase())
838 return phase
838 return phase
839
839
840 def hidden(self):
840 def hidden(self):
841 return False
841 return False
842
842
843 def children(self):
843 def children(self):
844 return []
844 return []
845
845
846 def flags(self, path):
846 def flags(self, path):
847 if '_manifest' in self.__dict__:
847 if '_manifest' in self.__dict__:
848 try:
848 try:
849 return self._manifest.flags(path)
849 return self._manifest.flags(path)
850 except KeyError:
850 except KeyError:
851 return ''
851 return ''
852
852
853 try:
853 try:
854 return self._flagfunc(path)
854 return self._flagfunc(path)
855 except OSError:
855 except OSError:
856 return ''
856 return ''
857
857
858 def filectx(self, path, filelog=None):
858 def filectx(self, path, filelog=None):
859 """get a file context from the working directory"""
859 """get a file context from the working directory"""
860 return workingfilectx(self._repo, path, workingctx=self,
860 return workingfilectx(self._repo, path, workingctx=self,
861 filelog=filelog)
861 filelog=filelog)
862
862
863 def ancestor(self, c2):
863 def ancestor(self, c2):
864 """return the ancestor context of self and c2"""
864 """return the ancestor context of self and c2"""
865 return self._parents[0].ancestor(c2) # punt on two parents for now
865 return self._parents[0].ancestor(c2) # punt on two parents for now
866
866
867 def walk(self, match):
867 def walk(self, match):
868 return sorted(self._repo.dirstate.walk(match, self.substate.keys(),
868 return sorted(self._repo.dirstate.walk(match, self.substate.keys(),
869 True, False))
869 True, False))
870
870
871 def dirty(self, missing=False):
871 def dirty(self, missing=False):
872 "check whether a working directory is modified"
872 "check whether a working directory is modified"
873 # check subrepos first
873 # check subrepos first
874 for s in self.substate:
874 for s in self.substate:
875 if self.sub(s).dirty():
875 if self.sub(s).dirty():
876 return True
876 return True
877 # check current working dir
877 # check current working dir
878 return (self.p2() or self.branch() != self.p1().branch() or
878 return (self.p2() or self.branch() != self.p1().branch() or
879 self.modified() or self.added() or self.removed() or
879 self.modified() or self.added() or self.removed() or
880 (missing and self.deleted()))
880 (missing and self.deleted()))
881
881
882 def add(self, list, prefix=""):
882 def add(self, list, prefix=""):
883 join = lambda f: os.path.join(prefix, f)
883 join = lambda f: os.path.join(prefix, f)
884 wlock = self._repo.wlock()
884 wlock = self._repo.wlock()
885 ui, ds = self._repo.ui, self._repo.dirstate
885 ui, ds = self._repo.ui, self._repo.dirstate
886 try:
886 try:
887 rejected = []
887 rejected = []
888 for f in list:
888 for f in list:
889 scmutil.checkportable(ui, join(f))
889 scmutil.checkportable(ui, join(f))
890 p = self._repo.wjoin(f)
890 p = self._repo.wjoin(f)
891 try:
891 try:
892 st = os.lstat(p)
892 st = os.lstat(p)
893 except OSError:
893 except OSError:
894 ui.warn(_("%s does not exist!\n") % join(f))
894 ui.warn(_("%s does not exist!\n") % join(f))
895 rejected.append(f)
895 rejected.append(f)
896 continue
896 continue
897 if st.st_size > 10000000:
897 if st.st_size > 10000000:
898 ui.warn(_("%s: up to %d MB of RAM may be required "
898 ui.warn(_("%s: up to %d MB of RAM may be required "
899 "to manage this file\n"
899 "to manage this file\n"
900 "(use 'hg revert %s' to cancel the "
900 "(use 'hg revert %s' to cancel the "
901 "pending addition)\n")
901 "pending addition)\n")
902 % (f, 3 * st.st_size // 1000000, join(f)))
902 % (f, 3 * st.st_size // 1000000, join(f)))
903 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
903 if not (stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode)):
904 ui.warn(_("%s not added: only files and symlinks "
904 ui.warn(_("%s not added: only files and symlinks "
905 "supported currently\n") % join(f))
905 "supported currently\n") % join(f))
906 rejected.append(p)
906 rejected.append(p)
907 elif ds[f] in 'amn':
907 elif ds[f] in 'amn':
908 ui.warn(_("%s already tracked!\n") % join(f))
908 ui.warn(_("%s already tracked!\n") % join(f))
909 elif ds[f] == 'r':
909 elif ds[f] == 'r':
910 ds.normallookup(f)
910 ds.normallookup(f)
911 else:
911 else:
912 ds.add(f)
912 ds.add(f)
913 return rejected
913 return rejected
914 finally:
914 finally:
915 wlock.release()
915 wlock.release()
916
916
917 def forget(self, files, prefix=""):
917 def forget(self, files, prefix=""):
918 join = lambda f: os.path.join(prefix, f)
918 join = lambda f: os.path.join(prefix, f)
919 wlock = self._repo.wlock()
919 wlock = self._repo.wlock()
920 try:
920 try:
921 rejected = []
921 rejected = []
922 for f in files:
922 for f in files:
923 if f not in self._repo.dirstate:
923 if f not in self._repo.dirstate:
924 self._repo.ui.warn(_("%s not tracked!\n") % join(f))
924 self._repo.ui.warn(_("%s not tracked!\n") % join(f))
925 rejected.append(f)
925 rejected.append(f)
926 elif self._repo.dirstate[f] != 'a':
926 elif self._repo.dirstate[f] != 'a':
927 self._repo.dirstate.remove(f)
927 self._repo.dirstate.remove(f)
928 else:
928 else:
929 self._repo.dirstate.drop(f)
929 self._repo.dirstate.drop(f)
930 return rejected
930 return rejected
931 finally:
931 finally:
932 wlock.release()
932 wlock.release()
933
933
934 def ancestors(self, followfirst=False):
934 def ancestors(self, followfirst=False):
935 cut = followfirst and 1 or None
935 cut = followfirst and 1 or None
936 for a in self._repo.changelog.ancestors(
936 for a in self._repo.changelog.ancestors(
937 *[p.rev() for p in self._parents[:cut]]):
937 *[p.rev() for p in self._parents[:cut]]):
938 yield changectx(self._repo, a)
938 yield changectx(self._repo, a)
939
939
940 def undelete(self, list):
940 def undelete(self, list):
941 pctxs = self.parents()
941 pctxs = self.parents()
942 wlock = self._repo.wlock()
942 wlock = self._repo.wlock()
943 try:
943 try:
944 for f in list:
944 for f in list:
945 if self._repo.dirstate[f] != 'r':
945 if self._repo.dirstate[f] != 'r':
946 self._repo.ui.warn(_("%s not removed!\n") % f)
946 self._repo.ui.warn(_("%s not removed!\n") % f)
947 else:
947 else:
948 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
948 fctx = f in pctxs[0] and pctxs[0][f] or pctxs[1][f]
949 t = fctx.data()
949 t = fctx.data()
950 self._repo.wwrite(f, t, fctx.flags())
950 self._repo.wwrite(f, t, fctx.flags())
951 self._repo.dirstate.normal(f)
951 self._repo.dirstate.normal(f)
952 finally:
952 finally:
953 wlock.release()
953 wlock.release()
954
954
955 def copy(self, source, dest):
955 def copy(self, source, dest):
956 p = self._repo.wjoin(dest)
956 p = self._repo.wjoin(dest)
957 if not os.path.lexists(p):
957 if not os.path.lexists(p):
958 self._repo.ui.warn(_("%s does not exist!\n") % dest)
958 self._repo.ui.warn(_("%s does not exist!\n") % dest)
959 elif not (os.path.isfile(p) or os.path.islink(p)):
959 elif not (os.path.isfile(p) or os.path.islink(p)):
960 self._repo.ui.warn(_("copy failed: %s is not a file or a "
960 self._repo.ui.warn(_("copy failed: %s is not a file or a "
961 "symbolic link\n") % dest)
961 "symbolic link\n") % dest)
962 else:
962 else:
963 wlock = self._repo.wlock()
963 wlock = self._repo.wlock()
964 try:
964 try:
965 if self._repo.dirstate[dest] in '?r':
965 if self._repo.dirstate[dest] in '?r':
966 self._repo.dirstate.add(dest)
966 self._repo.dirstate.add(dest)
967 self._repo.dirstate.copy(source, dest)
967 self._repo.dirstate.copy(source, dest)
968 finally:
968 finally:
969 wlock.release()
969 wlock.release()
970
970
971 def dirs(self):
971 def dirs(self):
972 return self._repo.dirstate.dirs()
972 return self._repo.dirstate.dirs()
973
973
974 class workingfilectx(filectx):
974 class workingfilectx(filectx):
975 """A workingfilectx object makes access to data related to a particular
975 """A workingfilectx object makes access to data related to a particular
976 file in the working directory convenient."""
976 file in the working directory convenient."""
977 def __init__(self, repo, path, filelog=None, workingctx=None):
977 def __init__(self, repo, path, filelog=None, workingctx=None):
978 """changeid can be a changeset revision, node, or tag.
978 """changeid can be a changeset revision, node, or tag.
979 fileid can be a file revision or node."""
979 fileid can be a file revision or node."""
980 self._repo = repo
980 self._repo = repo
981 self._path = path
981 self._path = path
982 self._changeid = None
982 self._changeid = None
983 self._filerev = self._filenode = None
983 self._filerev = self._filenode = None
984
984
985 if filelog:
985 if filelog:
986 self._filelog = filelog
986 self._filelog = filelog
987 if workingctx:
987 if workingctx:
988 self._changectx = workingctx
988 self._changectx = workingctx
989
989
990 @propertycache
990 @propertycache
991 def _changectx(self):
991 def _changectx(self):
992 return workingctx(self._repo)
992 return workingctx(self._repo)
993
993
994 def __nonzero__(self):
994 def __nonzero__(self):
995 return True
995 return True
996
996
997 def __str__(self):
997 def __str__(self):
998 return "%s@%s" % (self.path(), self._changectx)
998 return "%s@%s" % (self.path(), self._changectx)
999
999
1000 def __repr__(self):
1000 def __repr__(self):
1001 return "<workingfilectx %s>" % str(self)
1001 return "<workingfilectx %s>" % str(self)
1002
1002
1003 def data(self):
1003 def data(self):
1004 return self._repo.wread(self._path)
1004 return self._repo.wread(self._path)
1005 def renamed(self):
1005 def renamed(self):
1006 rp = self._repo.dirstate.copied(self._path)
1006 rp = self._repo.dirstate.copied(self._path)
1007 if not rp:
1007 if not rp:
1008 return None
1008 return None
1009 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1009 return rp, self._changectx._parents[0]._manifest.get(rp, nullid)
1010
1010
1011 def parents(self):
1011 def parents(self):
1012 '''return parent filectxs, following copies if necessary'''
1012 '''return parent filectxs, following copies if necessary'''
1013 def filenode(ctx, path):
1013 def filenode(ctx, path):
1014 return ctx._manifest.get(path, nullid)
1014 return ctx._manifest.get(path, nullid)
1015
1015
1016 path = self._path
1016 path = self._path
1017 fl = self._filelog
1017 fl = self._filelog
1018 pcl = self._changectx._parents
1018 pcl = self._changectx._parents
1019 renamed = self.renamed()
1019 renamed = self.renamed()
1020
1020
1021 if renamed:
1021 if renamed:
1022 pl = [renamed + (None,)]
1022 pl = [renamed + (None,)]
1023 else:
1023 else:
1024 pl = [(path, filenode(pcl[0], path), fl)]
1024 pl = [(path, filenode(pcl[0], path), fl)]
1025
1025
1026 for pc in pcl[1:]:
1026 for pc in pcl[1:]:
1027 pl.append((path, filenode(pc, path), fl))
1027 pl.append((path, filenode(pc, path), fl))
1028
1028
1029 return [filectx(self._repo, p, fileid=n, filelog=l)
1029 return [filectx(self._repo, p, fileid=n, filelog=l)
1030 for p, n, l in pl if n != nullid]
1030 for p, n, l in pl if n != nullid]
1031
1031
1032 def children(self):
1032 def children(self):
1033 return []
1033 return []
1034
1034
1035 def size(self):
1035 def size(self):
1036 return os.lstat(self._repo.wjoin(self._path)).st_size
1036 return os.lstat(self._repo.wjoin(self._path)).st_size
1037 def date(self):
1037 def date(self):
1038 t, tz = self._changectx.date()
1038 t, tz = self._changectx.date()
1039 try:
1039 try:
1040 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
1040 return (int(os.lstat(self._repo.wjoin(self._path)).st_mtime), tz)
1041 except OSError, err:
1041 except OSError, err:
1042 if err.errno != errno.ENOENT:
1042 if err.errno != errno.ENOENT:
1043 raise
1043 raise
1044 return (t, tz)
1044 return (t, tz)
1045
1045
1046 def cmp(self, fctx):
1046 def cmp(self, fctx):
1047 """compare with other file context
1047 """compare with other file context
1048
1048
1049 returns True if different than fctx.
1049 returns True if different than fctx.
1050 """
1050 """
1051 # fctx should be a filectx (not a wfctx)
1051 # fctx should be a filectx (not a wfctx)
1052 # invert comparison to reuse the same code path
1052 # invert comparison to reuse the same code path
1053 return fctx.cmp(self)
1053 return fctx.cmp(self)
1054
1054
1055 class memctx(object):
1055 class memctx(object):
1056 """Use memctx to perform in-memory commits via localrepo.commitctx().
1056 """Use memctx to perform in-memory commits via localrepo.commitctx().
1057
1057
1058 Revision information is supplied at initialization time while
1058 Revision information is supplied at initialization time while
1059 related files data and is made available through a callback
1059 related files data and is made available through a callback
1060 mechanism. 'repo' is the current localrepo, 'parents' is a
1060 mechanism. 'repo' is the current localrepo, 'parents' is a
1061 sequence of two parent revisions identifiers (pass None for every
1061 sequence of two parent revisions identifiers (pass None for every
1062 missing parent), 'text' is the commit message and 'files' lists
1062 missing parent), 'text' is the commit message and 'files' lists
1063 names of files touched by the revision (normalized and relative to
1063 names of files touched by the revision (normalized and relative to
1064 repository root).
1064 repository root).
1065
1065
1066 filectxfn(repo, memctx, path) is a callable receiving the
1066 filectxfn(repo, memctx, path) is a callable receiving the
1067 repository, the current memctx object and the normalized path of
1067 repository, the current memctx object and the normalized path of
1068 requested file, relative to repository root. It is fired by the
1068 requested file, relative to repository root. It is fired by the
1069 commit function for every file in 'files', but calls order is
1069 commit function for every file in 'files', but calls order is
1070 undefined. If the file is available in the revision being
1070 undefined. If the file is available in the revision being
1071 committed (updated or added), filectxfn returns a memfilectx
1071 committed (updated or added), filectxfn returns a memfilectx
1072 object. If the file was removed, filectxfn raises an
1072 object. If the file was removed, filectxfn raises an
1073 IOError. Moved files are represented by marking the source file
1073 IOError. Moved files are represented by marking the source file
1074 removed and the new file added with copy information (see
1074 removed and the new file added with copy information (see
1075 memfilectx).
1075 memfilectx).
1076
1076
1077 user receives the committer name and defaults to current
1077 user receives the committer name and defaults to current
1078 repository username, date is the commit date in any format
1078 repository username, date is the commit date in any format
1079 supported by util.parsedate() and defaults to current date, extra
1079 supported by util.parsedate() and defaults to current date, extra
1080 is a dictionary of metadata or is left empty.
1080 is a dictionary of metadata or is left empty.
1081 """
1081 """
1082 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1082 def __init__(self, repo, parents, text, files, filectxfn, user=None,
1083 date=None, extra=None):
1083 date=None, extra=None):
1084 self._repo = repo
1084 self._repo = repo
1085 self._rev = None
1085 self._rev = None
1086 self._node = None
1086 self._node = None
1087 self._text = text
1087 self._text = text
1088 self._date = date and util.parsedate(date) or util.makedate()
1088 self._date = date and util.parsedate(date) or util.makedate()
1089 self._user = user
1089 self._user = user
1090 parents = [(p or nullid) for p in parents]
1090 parents = [(p or nullid) for p in parents]
1091 p1, p2 = parents
1091 p1, p2 = parents
1092 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1092 self._parents = [changectx(self._repo, p) for p in (p1, p2)]
1093 files = sorted(set(files))
1093 files = sorted(set(files))
1094 self._status = [files, [], [], [], []]
1094 self._status = [files, [], [], [], []]
1095 self._filectxfn = filectxfn
1095 self._filectxfn = filectxfn
1096
1096
1097 self._extra = extra and extra.copy() or {}
1097 self._extra = extra and extra.copy() or {}
1098 if self._extra.get('branch', '') == '':
1098 if self._extra.get('branch', '') == '':
1099 self._extra['branch'] = 'default'
1099 self._extra['branch'] = 'default'
1100
1100
1101 def __str__(self):
1101 def __str__(self):
1102 return str(self._parents[0]) + "+"
1102 return str(self._parents[0]) + "+"
1103
1103
1104 def __int__(self):
1104 def __int__(self):
1105 return self._rev
1105 return self._rev
1106
1106
1107 def __nonzero__(self):
1107 def __nonzero__(self):
1108 return True
1108 return True
1109
1109
1110 def __getitem__(self, key):
1110 def __getitem__(self, key):
1111 return self.filectx(key)
1111 return self.filectx(key)
1112
1112
1113 def p1(self):
1113 def p1(self):
1114 return self._parents[0]
1114 return self._parents[0]
1115 def p2(self):
1115 def p2(self):
1116 return self._parents[1]
1116 return self._parents[1]
1117
1117
1118 def user(self):
1118 def user(self):
1119 return self._user or self._repo.ui.username()
1119 return self._user or self._repo.ui.username()
1120 def date(self):
1120 def date(self):
1121 return self._date
1121 return self._date
1122 def description(self):
1122 def description(self):
1123 return self._text
1123 return self._text
1124 def files(self):
1124 def files(self):
1125 return self.modified()
1125 return self.modified()
1126 def modified(self):
1126 def modified(self):
1127 return self._status[0]
1127 return self._status[0]
1128 def added(self):
1128 def added(self):
1129 return self._status[1]
1129 return self._status[1]
1130 def removed(self):
1130 def removed(self):
1131 return self._status[2]
1131 return self._status[2]
1132 def deleted(self):
1132 def deleted(self):
1133 return self._status[3]
1133 return self._status[3]
1134 def unknown(self):
1134 def unknown(self):
1135 return self._status[4]
1135 return self._status[4]
1136 def ignored(self):
1136 def ignored(self):
1137 return self._status[5]
1137 return self._status[5]
1138 def clean(self):
1138 def clean(self):
1139 return self._status[6]
1139 return self._status[6]
1140 def branch(self):
1140 def branch(self):
1141 return encoding.tolocal(self._extra['branch'])
1141 return encoding.tolocal(self._extra['branch'])
1142 def extra(self):
1142 def extra(self):
1143 return self._extra
1143 return self._extra
1144 def flags(self, f):
1144 def flags(self, f):
1145 return self[f].flags()
1145 return self[f].flags()
1146
1146
1147 def parents(self):
1147 def parents(self):
1148 """return contexts for each parent changeset"""
1148 """return contexts for each parent changeset"""
1149 return self._parents
1149 return self._parents
1150
1150
1151 def filectx(self, path, filelog=None):
1151 def filectx(self, path, filelog=None):
1152 """get a file context from the working directory"""
1152 """get a file context from the working directory"""
1153 return self._filectxfn(self._repo, self, path)
1153 return self._filectxfn(self._repo, self, path)
1154
1154
1155 def commit(self):
1155 def commit(self):
1156 """commit context to the repo"""
1156 """commit context to the repo"""
1157 return self._repo.commitctx(self)
1157 return self._repo.commitctx(self)
1158
1158
1159 class memfilectx(object):
1159 class memfilectx(object):
1160 """memfilectx represents an in-memory file to commit.
1160 """memfilectx represents an in-memory file to commit.
1161
1161
1162 See memctx for more details.
1162 See memctx for more details.
1163 """
1163 """
1164 def __init__(self, path, data, islink=False, isexec=False, copied=None):
1164 def __init__(self, path, data, islink=False, isexec=False, copied=None):
1165 """
1165 """
1166 path is the normalized file path relative to repository root.
1166 path is the normalized file path relative to repository root.
1167 data is the file content as a string.
1167 data is the file content as a string.
1168 islink is True if the file is a symbolic link.
1168 islink is True if the file is a symbolic link.
1169 isexec is True if the file is executable.
1169 isexec is True if the file is executable.
1170 copied is the source file path if current file was copied in the
1170 copied is the source file path if current file was copied in the
1171 revision being committed, or None."""
1171 revision being committed, or None."""
1172 self._path = path
1172 self._path = path
1173 self._data = data
1173 self._data = data
1174 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1174 self._flags = (islink and 'l' or '') + (isexec and 'x' or '')
1175 self._copied = None
1175 self._copied = None
1176 if copied:
1176 if copied:
1177 self._copied = (copied, nullid)
1177 self._copied = (copied, nullid)
1178
1178
1179 def __nonzero__(self):
1179 def __nonzero__(self):
1180 return True
1180 return True
1181 def __str__(self):
1181 def __str__(self):
1182 return "%s@%s" % (self.path(), self._changectx)
1182 return "%s@%s" % (self.path(), self._changectx)
1183 def path(self):
1183 def path(self):
1184 return self._path
1184 return self._path
1185 def data(self):
1185 def data(self):
1186 return self._data
1186 return self._data
1187 def flags(self):
1187 def flags(self):
1188 return self._flags
1188 return self._flags
1189 def isexec(self):
1189 def isexec(self):
1190 return 'x' in self._flags
1190 return 'x' in self._flags
1191 def islink(self):
1191 def islink(self):
1192 return 'l' in self._flags
1192 return 'l' in self._flags
1193 def renamed(self):
1193 def renamed(self):
1194 return self._copied
1194 return self._copied
@@ -1,342 +1,342 b''
1 # mdiff.py - diff and patch routines for mercurial
1 # mdiff.py - diff and patch routines for mercurial
2 #
2 #
3 # Copyright 2005, 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005, 2006 Matt Mackall <mpm@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 from i18n import _
8 from i18n import _
9 import bdiff, mpatch, util
9 import bdiff, mpatch, util
10 import re, struct
10 import re, struct
11
11
12 def splitnewlines(text):
12 def splitnewlines(text):
13 '''like str.splitlines, but only split on newlines.'''
13 '''like str.splitlines, but only split on newlines.'''
14 lines = [l + '\n' for l in text.split('\n')]
14 lines = [l + '\n' for l in text.split('\n')]
15 if lines:
15 if lines:
16 if lines[-1] == '\n':
16 if lines[-1] == '\n':
17 lines.pop()
17 lines.pop()
18 else:
18 else:
19 lines[-1] = lines[-1][:-1]
19 lines[-1] = lines[-1][:-1]
20 return lines
20 return lines
21
21
22 class diffopts(object):
22 class diffopts(object):
23 '''context is the number of context lines
23 '''context is the number of context lines
24 text treats all files as text
24 text treats all files as text
25 showfunc enables diff -p output
25 showfunc enables diff -p output
26 git enables the git extended patch format
26 git enables the git extended patch format
27 nodates removes dates from diff headers
27 nodates removes dates from diff headers
28 ignorews ignores all whitespace changes in the diff
28 ignorews ignores all whitespace changes in the diff
29 ignorewsamount ignores changes in the amount of whitespace
29 ignorewsamount ignores changes in the amount of whitespace
30 ignoreblanklines ignores changes whose lines are all blank
30 ignoreblanklines ignores changes whose lines are all blank
31 upgrade generates git diffs to avoid data loss
31 upgrade generates git diffs to avoid data loss
32 '''
32 '''
33
33
34 defaults = {
34 defaults = {
35 'context': 3,
35 'context': 3,
36 'text': False,
36 'text': False,
37 'showfunc': False,
37 'showfunc': False,
38 'git': False,
38 'git': False,
39 'nodates': False,
39 'nodates': False,
40 'ignorews': False,
40 'ignorews': False,
41 'ignorewsamount': False,
41 'ignorewsamount': False,
42 'ignoreblanklines': False,
42 'ignoreblanklines': False,
43 'upgrade': False,
43 'upgrade': False,
44 }
44 }
45
45
46 __slots__ = defaults.keys()
46 __slots__ = defaults.keys()
47
47
48 def __init__(self, **opts):
48 def __init__(self, **opts):
49 for k in self.__slots__:
49 for k in self.__slots__:
50 v = opts.get(k)
50 v = opts.get(k)
51 if v is None:
51 if v is None:
52 v = self.defaults[k]
52 v = self.defaults[k]
53 setattr(self, k, v)
53 setattr(self, k, v)
54
54
55 try:
55 try:
56 self.context = int(self.context)
56 self.context = int(self.context)
57 except ValueError:
57 except ValueError:
58 raise util.Abort(_('diff context lines count must be '
58 raise util.Abort(_('diff context lines count must be '
59 'an integer, not %r') % self.context)
59 'an integer, not %r') % self.context)
60
60
61 def copy(self, **kwargs):
61 def copy(self, **kwargs):
62 opts = dict((k, getattr(self, k)) for k in self.defaults)
62 opts = dict((k, getattr(self, k)) for k in self.defaults)
63 opts.update(kwargs)
63 opts.update(kwargs)
64 return diffopts(**opts)
64 return diffopts(**opts)
65
65
66 defaultopts = diffopts()
66 defaultopts = diffopts()
67
67
68 def wsclean(opts, text, blank=True):
68 def wsclean(opts, text, blank=True):
69 if opts.ignorews:
69 if opts.ignorews:
70 text = bdiff.fixws(text, 1)
70 text = bdiff.fixws(text, 1)
71 elif opts.ignorewsamount:
71 elif opts.ignorewsamount:
72 text = bdiff.fixws(text, 0)
72 text = bdiff.fixws(text, 0)
73 if blank and opts.ignoreblanklines:
73 if blank and opts.ignoreblanklines:
74 text = re.sub('\n+', '\n', text).strip('\n')
74 text = re.sub('\n+', '\n', text).strip('\n')
75 return text
75 return text
76
76
77 def splitblock(base1, lines1, base2, lines2, opts):
77 def splitblock(base1, lines1, base2, lines2, opts):
78 # The input lines matches except for interwoven blank lines. We
78 # The input lines matches except for interwoven blank lines. We
79 # transform it into a sequence of matching blocks and blank blocks.
79 # transform it into a sequence of matching blocks and blank blocks.
80 lines1 = [(wsclean(opts, l) and 1 or 0) for l in lines1]
80 lines1 = [(wsclean(opts, l) and 1 or 0) for l in lines1]
81 lines2 = [(wsclean(opts, l) and 1 or 0) for l in lines2]
81 lines2 = [(wsclean(opts, l) and 1 or 0) for l in lines2]
82 s1, e1 = 0, len(lines1)
82 s1, e1 = 0, len(lines1)
83 s2, e2 = 0, len(lines2)
83 s2, e2 = 0, len(lines2)
84 while s1 < e1 or s2 < e2:
84 while s1 < e1 or s2 < e2:
85 i1, i2, btype = s1, s2, '='
85 i1, i2, btype = s1, s2, '='
86 if (i1 >= e1 or lines1[i1] == 0
86 if (i1 >= e1 or lines1[i1] == 0
87 or i2 >= e2 or lines2[i2] == 0):
87 or i2 >= e2 or lines2[i2] == 0):
88 # Consume the block of blank lines
88 # Consume the block of blank lines
89 btype = '~'
89 btype = '~'
90 while i1 < e1 and lines1[i1] == 0:
90 while i1 < e1 and lines1[i1] == 0:
91 i1 += 1
91 i1 += 1
92 while i2 < e2 and lines2[i2] == 0:
92 while i2 < e2 and lines2[i2] == 0:
93 i2 += 1
93 i2 += 1
94 else:
94 else:
95 # Consume the matching lines
95 # Consume the matching lines
96 while i1 < e1 and lines1[i1] == 1 and lines2[i2] == 1:
96 while i1 < e1 and lines1[i1] == 1 and lines2[i2] == 1:
97 i1 += 1
97 i1 += 1
98 i2 += 1
98 i2 += 1
99 yield [base1 + s1, base1 + i1, base2 + s2, base2 + i2], btype
99 yield [base1 + s1, base1 + i1, base2 + s2, base2 + i2], btype
100 s1 = i1
100 s1 = i1
101 s2 = i2
101 s2 = i2
102
102
103 def allblocks(text1, text2, opts=None, lines1=None, lines2=None, refine=False):
103 def allblocks(text1, text2, opts=None, lines1=None, lines2=None, refine=False):
104 """Return (block, type) tuples, where block is an mdiff.blocks
104 """Return (block, type) tuples, where block is an mdiff.blocks
105 line entry. type is '=' for blocks matching exactly one another
105 line entry. type is '=' for blocks matching exactly one another
106 (bdiff blocks), '!' for non-matching blocks and '~' for blocks
106 (bdiff blocks), '!' for non-matching blocks and '~' for blocks
107 matching only after having filtered blank lines. If refine is True,
107 matching only after having filtered blank lines. If refine is True,
108 then '~' blocks are refined and are only made of blank lines.
108 then '~' blocks are refined and are only made of blank lines.
109 line1 and line2 are text1 and text2 split with splitnewlines() if
109 line1 and line2 are text1 and text2 split with splitnewlines() if
110 they are already available.
110 they are already available.
111 """
111 """
112 if opts is None:
112 if opts is None:
113 opts = defaultopts
113 opts = defaultopts
114 if opts.ignorews or opts.ignorewsamount:
114 if opts.ignorews or opts.ignorewsamount:
115 text1 = wsclean(opts, text1, False)
115 text1 = wsclean(opts, text1, False)
116 text2 = wsclean(opts, text2, False)
116 text2 = wsclean(opts, text2, False)
117 diff = bdiff.blocks(text1, text2)
117 diff = bdiff.blocks(text1, text2)
118 for i, s1 in enumerate(diff):
118 for i, s1 in enumerate(diff):
119 # The first match is special.
119 # The first match is special.
120 # we've either found a match starting at line 0 or a match later
120 # we've either found a match starting at line 0 or a match later
121 # in the file. If it starts later, old and new below will both be
121 # in the file. If it starts later, old and new below will both be
122 # empty and we'll continue to the next match.
122 # empty and we'll continue to the next match.
123 if i > 0:
123 if i > 0:
124 s = diff[i - 1]
124 s = diff[i - 1]
125 else:
125 else:
126 s = [0, 0, 0, 0]
126 s = [0, 0, 0, 0]
127 s = [s[1], s1[0], s[3], s1[2]]
127 s = [s[1], s1[0], s[3], s1[2]]
128
128
129 # bdiff sometimes gives huge matches past eof, this check eats them,
129 # bdiff sometimes gives huge matches past eof, this check eats them,
130 # and deals with the special first match case described above
130 # and deals with the special first match case described above
131 if s[0] != s[1] or s[2] != s[3]:
131 if s[0] != s[1] or s[2] != s[3]:
132 type = '!'
132 type = '!'
133 if opts.ignoreblanklines:
133 if opts.ignoreblanklines:
134 if lines1 is None:
134 if lines1 is None:
135 lines1 = splitnewlines(text1)
135 lines1 = splitnewlines(text1)
136 if lines2 is None:
136 if lines2 is None:
137 lines2 = splitnewlines(text2)
137 lines2 = splitnewlines(text2)
138 old = wsclean(opts, "".join(lines1[s[0]:s[1]]))
138 old = wsclean(opts, "".join(lines1[s[0]:s[1]]))
139 new = wsclean(opts, "".join(lines2[s[2]:s[3]]))
139 new = wsclean(opts, "".join(lines2[s[2]:s[3]]))
140 if old == new:
140 if old == new:
141 type = '~'
141 type = '~'
142 yield s, type
142 yield s, type
143 yield s1, '='
143 yield s1, '='
144
144
145 def diffline(revs, a, b, opts):
145 def diffline(revs, a, b, opts):
146 parts = ['diff']
146 parts = ['diff']
147 if opts.git:
147 if opts.git:
148 parts.append('--git')
148 parts.append('--git')
149 if revs and not opts.git:
149 if revs and not opts.git:
150 parts.append(' '.join(["-r %s" % rev for rev in revs]))
150 parts.append(' '.join(["-r %s" % rev for rev in revs]))
151 if opts.git:
151 if opts.git:
152 parts.append('a/%s' % a)
152 parts.append('a/%s' % a)
153 parts.append('b/%s' % b)
153 parts.append('b/%s' % b)
154 else:
154 else:
155 parts.append(a)
155 parts.append(a)
156 return ' '.join(parts) + '\n'
156 return ' '.join(parts) + '\n'
157
157
158 def unidiff(a, ad, b, bd, fn1, fn2, r=None, opts=defaultopts):
158 def unidiff(a, ad, b, bd, fn1, fn2, r=None, opts=defaultopts):
159 def datetag(date, addtab=True):
159 def datetag(date, fn=None):
160 if not opts.git and not opts.nodates:
160 if not opts.git and not opts.nodates:
161 return '\t%s\n' % date
161 return '\t%s\n' % date
162 if addtab and ' ' in fn1:
162 if fn and ' ' in fn:
163 return '\t\n'
163 return '\t\n'
164 return '\n'
164 return '\n'
165
165
166 if not a and not b:
166 if not a and not b:
167 return ""
167 return ""
168 epoch = util.datestr((0, 0))
168 epoch = util.datestr((0, 0))
169
169
170 fn1 = util.pconvert(fn1)
170 fn1 = util.pconvert(fn1)
171 fn2 = util.pconvert(fn2)
171 fn2 = util.pconvert(fn2)
172
172
173 if not opts.text and (util.binary(a) or util.binary(b)):
173 if not opts.text and (util.binary(a) or util.binary(b)):
174 if a and b and len(a) == len(b) and a == b:
174 if a and b and len(a) == len(b) and a == b:
175 return ""
175 return ""
176 l = ['Binary file %s has changed\n' % fn1]
176 l = ['Binary file %s has changed\n' % fn1]
177 elif not a:
177 elif not a:
178 b = splitnewlines(b)
178 b = splitnewlines(b)
179 if a is None:
179 if a is None:
180 l1 = '--- /dev/null%s' % datetag(epoch, False)
180 l1 = '--- /dev/null%s' % datetag(epoch)
181 else:
181 else:
182 l1 = "--- %s%s" % ("a/" + fn1, datetag(ad))
182 l1 = "--- %s%s" % ("a/" + fn1, datetag(ad, fn1))
183 l2 = "+++ %s%s" % ("b/" + fn2, datetag(bd))
183 l2 = "+++ %s%s" % ("b/" + fn2, datetag(bd, fn2))
184 l3 = "@@ -0,0 +1,%d @@\n" % len(b)
184 l3 = "@@ -0,0 +1,%d @@\n" % len(b)
185 l = [l1, l2, l3] + ["+" + e for e in b]
185 l = [l1, l2, l3] + ["+" + e for e in b]
186 elif not b:
186 elif not b:
187 a = splitnewlines(a)
187 a = splitnewlines(a)
188 l1 = "--- %s%s" % ("a/" + fn1, datetag(ad))
188 l1 = "--- %s%s" % ("a/" + fn1, datetag(ad, fn1))
189 if b is None:
189 if b is None:
190 l2 = '+++ /dev/null%s' % datetag(epoch, False)
190 l2 = '+++ /dev/null%s' % datetag(epoch)
191 else:
191 else:
192 l2 = "+++ %s%s" % ("b/" + fn2, datetag(bd))
192 l2 = "+++ %s%s" % ("b/" + fn2, datetag(bd, fn2))
193 l3 = "@@ -1,%d +0,0 @@\n" % len(a)
193 l3 = "@@ -1,%d +0,0 @@\n" % len(a)
194 l = [l1, l2, l3] + ["-" + e for e in a]
194 l = [l1, l2, l3] + ["-" + e for e in a]
195 else:
195 else:
196 al = splitnewlines(a)
196 al = splitnewlines(a)
197 bl = splitnewlines(b)
197 bl = splitnewlines(b)
198 l = list(_unidiff(a, b, al, bl, opts=opts))
198 l = list(_unidiff(a, b, al, bl, opts=opts))
199 if not l:
199 if not l:
200 return ""
200 return ""
201
201
202 l.insert(0, "--- a/%s%s" % (fn1, datetag(ad)))
202 l.insert(0, "--- a/%s%s" % (fn1, datetag(ad, fn1)))
203 l.insert(1, "+++ b/%s%s" % (fn2, datetag(bd)))
203 l.insert(1, "+++ b/%s%s" % (fn2, datetag(bd, fn2)))
204
204
205 for ln in xrange(len(l)):
205 for ln in xrange(len(l)):
206 if l[ln][-1] != '\n':
206 if l[ln][-1] != '\n':
207 l[ln] += "\n\ No newline at end of file\n"
207 l[ln] += "\n\ No newline at end of file\n"
208
208
209 if r:
209 if r:
210 l.insert(0, diffline(r, fn1, fn2, opts))
210 l.insert(0, diffline(r, fn1, fn2, opts))
211
211
212 return "".join(l)
212 return "".join(l)
213
213
214 # creates a headerless unified diff
214 # creates a headerless unified diff
215 # t1 and t2 are the text to be diffed
215 # t1 and t2 are the text to be diffed
216 # l1 and l2 are the text broken up into lines
216 # l1 and l2 are the text broken up into lines
217 def _unidiff(t1, t2, l1, l2, opts=defaultopts):
217 def _unidiff(t1, t2, l1, l2, opts=defaultopts):
218 def contextend(l, len):
218 def contextend(l, len):
219 ret = l + opts.context
219 ret = l + opts.context
220 if ret > len:
220 if ret > len:
221 ret = len
221 ret = len
222 return ret
222 return ret
223
223
224 def contextstart(l):
224 def contextstart(l):
225 ret = l - opts.context
225 ret = l - opts.context
226 if ret < 0:
226 if ret < 0:
227 return 0
227 return 0
228 return ret
228 return ret
229
229
230 lastfunc = [0, '']
230 lastfunc = [0, '']
231 def yieldhunk(hunk):
231 def yieldhunk(hunk):
232 (astart, a2, bstart, b2, delta) = hunk
232 (astart, a2, bstart, b2, delta) = hunk
233 aend = contextend(a2, len(l1))
233 aend = contextend(a2, len(l1))
234 alen = aend - astart
234 alen = aend - astart
235 blen = b2 - bstart + aend - a2
235 blen = b2 - bstart + aend - a2
236
236
237 func = ""
237 func = ""
238 if opts.showfunc:
238 if opts.showfunc:
239 lastpos, func = lastfunc
239 lastpos, func = lastfunc
240 # walk backwards from the start of the context up to the start of
240 # walk backwards from the start of the context up to the start of
241 # the previous hunk context until we find a line starting with an
241 # the previous hunk context until we find a line starting with an
242 # alphanumeric char.
242 # alphanumeric char.
243 for i in xrange(astart - 1, lastpos - 1, -1):
243 for i in xrange(astart - 1, lastpos - 1, -1):
244 if l1[i][0].isalnum():
244 if l1[i][0].isalnum():
245 func = ' ' + l1[i].rstrip()[:40]
245 func = ' ' + l1[i].rstrip()[:40]
246 lastfunc[1] = func
246 lastfunc[1] = func
247 break
247 break
248 # by recording this hunk's starting point as the next place to
248 # by recording this hunk's starting point as the next place to
249 # start looking for function lines, we avoid reading any line in
249 # start looking for function lines, we avoid reading any line in
250 # the file more than once.
250 # the file more than once.
251 lastfunc[0] = astart
251 lastfunc[0] = astart
252
252
253 # zero-length hunk ranges report their start line as one less
253 # zero-length hunk ranges report their start line as one less
254 if alen:
254 if alen:
255 astart += 1
255 astart += 1
256 if blen:
256 if blen:
257 bstart += 1
257 bstart += 1
258
258
259 yield "@@ -%d,%d +%d,%d @@%s\n" % (astart, alen,
259 yield "@@ -%d,%d +%d,%d @@%s\n" % (astart, alen,
260 bstart, blen, func)
260 bstart, blen, func)
261 for x in delta:
261 for x in delta:
262 yield x
262 yield x
263 for x in xrange(a2, aend):
263 for x in xrange(a2, aend):
264 yield ' ' + l1[x]
264 yield ' ' + l1[x]
265
265
266 # bdiff.blocks gives us the matching sequences in the files. The loop
266 # bdiff.blocks gives us the matching sequences in the files. The loop
267 # below finds the spaces between those matching sequences and translates
267 # below finds the spaces between those matching sequences and translates
268 # them into diff output.
268 # them into diff output.
269 #
269 #
270 hunk = None
270 hunk = None
271 ignoredlines = 0
271 ignoredlines = 0
272 for s, stype in allblocks(t1, t2, opts, l1, l2):
272 for s, stype in allblocks(t1, t2, opts, l1, l2):
273 a1, a2, b1, b2 = s
273 a1, a2, b1, b2 = s
274 if stype != '!':
274 if stype != '!':
275 if stype == '~':
275 if stype == '~':
276 # The diff context lines are based on t1 content. When
276 # The diff context lines are based on t1 content. When
277 # blank lines are ignored, the new lines offsets must
277 # blank lines are ignored, the new lines offsets must
278 # be adjusted as if equivalent blocks ('~') had the
278 # be adjusted as if equivalent blocks ('~') had the
279 # same sizes on both sides.
279 # same sizes on both sides.
280 ignoredlines += (b2 - b1) - (a2 - a1)
280 ignoredlines += (b2 - b1) - (a2 - a1)
281 continue
281 continue
282 delta = []
282 delta = []
283 old = l1[a1:a2]
283 old = l1[a1:a2]
284 new = l2[b1:b2]
284 new = l2[b1:b2]
285
285
286 b1 -= ignoredlines
286 b1 -= ignoredlines
287 b2 -= ignoredlines
287 b2 -= ignoredlines
288 astart = contextstart(a1)
288 astart = contextstart(a1)
289 bstart = contextstart(b1)
289 bstart = contextstart(b1)
290 prev = None
290 prev = None
291 if hunk:
291 if hunk:
292 # join with the previous hunk if it falls inside the context
292 # join with the previous hunk if it falls inside the context
293 if astart < hunk[1] + opts.context + 1:
293 if astart < hunk[1] + opts.context + 1:
294 prev = hunk
294 prev = hunk
295 astart = hunk[1]
295 astart = hunk[1]
296 bstart = hunk[3]
296 bstart = hunk[3]
297 else:
297 else:
298 for x in yieldhunk(hunk):
298 for x in yieldhunk(hunk):
299 yield x
299 yield x
300 if prev:
300 if prev:
301 # we've joined the previous hunk, record the new ending points.
301 # we've joined the previous hunk, record the new ending points.
302 hunk[1] = a2
302 hunk[1] = a2
303 hunk[3] = b2
303 hunk[3] = b2
304 delta = hunk[4]
304 delta = hunk[4]
305 else:
305 else:
306 # create a new hunk
306 # create a new hunk
307 hunk = [astart, a2, bstart, b2, delta]
307 hunk = [astart, a2, bstart, b2, delta]
308
308
309 delta[len(delta):] = [' ' + x for x in l1[astart:a1]]
309 delta[len(delta):] = [' ' + x for x in l1[astart:a1]]
310 delta[len(delta):] = ['-' + x for x in old]
310 delta[len(delta):] = ['-' + x for x in old]
311 delta[len(delta):] = ['+' + x for x in new]
311 delta[len(delta):] = ['+' + x for x in new]
312
312
313 if hunk:
313 if hunk:
314 for x in yieldhunk(hunk):
314 for x in yieldhunk(hunk):
315 yield x
315 yield x
316
316
317 def patchtext(bin):
317 def patchtext(bin):
318 pos = 0
318 pos = 0
319 t = []
319 t = []
320 while pos < len(bin):
320 while pos < len(bin):
321 p1, p2, l = struct.unpack(">lll", bin[pos:pos + 12])
321 p1, p2, l = struct.unpack(">lll", bin[pos:pos + 12])
322 pos += 12
322 pos += 12
323 t.append(bin[pos:pos + l])
323 t.append(bin[pos:pos + l])
324 pos += l
324 pos += l
325 return "".join(t)
325 return "".join(t)
326
326
327 def patch(a, bin):
327 def patch(a, bin):
328 if len(a) == 0:
328 if len(a) == 0:
329 # skip over trivial delta header
329 # skip over trivial delta header
330 return util.buffer(bin, 12)
330 return util.buffer(bin, 12)
331 return mpatch.patches(a, [bin])
331 return mpatch.patches(a, [bin])
332
332
333 # similar to difflib.SequenceMatcher.get_matching_blocks
333 # similar to difflib.SequenceMatcher.get_matching_blocks
334 def get_matching_blocks(a, b):
334 def get_matching_blocks(a, b):
335 return [(d[0], d[2], d[1] - d[0]) for d in bdiff.blocks(a, b)]
335 return [(d[0], d[2], d[1] - d[0]) for d in bdiff.blocks(a, b)]
336
336
337 def trivialdiffheader(length):
337 def trivialdiffheader(length):
338 return struct.pack(">lll", 0, 0, length)
338 return struct.pack(">lll", 0, 0, length)
339
339
340 patches = mpatch.patches
340 patches = mpatch.patches
341 patchedsize = mpatch.patchedsize
341 patchedsize = mpatch.patchedsize
342 textdiff = bdiff.bdiff
342 textdiff = bdiff.bdiff
@@ -1,746 +1,746 b''
1 # ui.py - user interface bits for mercurial
1 # ui.py - user interface bits for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@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 from i18n import _
8 from i18n import _
9 import errno, getpass, os, socket, sys, tempfile, traceback
9 import errno, getpass, os, socket, sys, tempfile, traceback
10 import config, scmutil, util, error, formatter
10 import config, scmutil, util, error, formatter
11
11
12 class ui(object):
12 class ui(object):
13 def __init__(self, src=None):
13 def __init__(self, src=None):
14 self._buffers = []
14 self._buffers = []
15 self.quiet = self.verbose = self.debugflag = self.tracebackflag = False
15 self.quiet = self.verbose = self.debugflag = self.tracebackflag = False
16 self._reportuntrusted = True
16 self._reportuntrusted = True
17 self._ocfg = config.config() # overlay
17 self._ocfg = config.config() # overlay
18 self._tcfg = config.config() # trusted
18 self._tcfg = config.config() # trusted
19 self._ucfg = config.config() # untrusted
19 self._ucfg = config.config() # untrusted
20 self._trustusers = set()
20 self._trustusers = set()
21 self._trustgroups = set()
21 self._trustgroups = set()
22
22
23 if src:
23 if src:
24 self.fout = src.fout
24 self.fout = src.fout
25 self.ferr = src.ferr
25 self.ferr = src.ferr
26 self.fin = src.fin
26 self.fin = src.fin
27
27
28 self._tcfg = src._tcfg.copy()
28 self._tcfg = src._tcfg.copy()
29 self._ucfg = src._ucfg.copy()
29 self._ucfg = src._ucfg.copy()
30 self._ocfg = src._ocfg.copy()
30 self._ocfg = src._ocfg.copy()
31 self._trustusers = src._trustusers.copy()
31 self._trustusers = src._trustusers.copy()
32 self._trustgroups = src._trustgroups.copy()
32 self._trustgroups = src._trustgroups.copy()
33 self.environ = src.environ
33 self.environ = src.environ
34 self.fixconfig()
34 self.fixconfig()
35 else:
35 else:
36 self.fout = sys.stdout
36 self.fout = sys.stdout
37 self.ferr = sys.stderr
37 self.ferr = sys.stderr
38 self.fin = sys.stdin
38 self.fin = sys.stdin
39
39
40 # shared read-only environment
40 # shared read-only environment
41 self.environ = os.environ
41 self.environ = os.environ
42 # we always trust global config files
42 # we always trust global config files
43 for f in scmutil.rcpath():
43 for f in scmutil.rcpath():
44 self.readconfig(f, trust=True)
44 self.readconfig(f, trust=True)
45
45
46 def copy(self):
46 def copy(self):
47 return self.__class__(self)
47 return self.__class__(self)
48
48
49 def formatter(self, topic, opts):
49 def formatter(self, topic, opts):
50 return formatter.formatter(self, topic, opts)
50 return formatter.formatter(self, topic, opts)
51
51
52 def _trusted(self, fp, f):
52 def _trusted(self, fp, f):
53 st = util.fstat(fp)
53 st = util.fstat(fp)
54 if util.isowner(st):
54 if util.isowner(st):
55 return True
55 return True
56
56
57 tusers, tgroups = self._trustusers, self._trustgroups
57 tusers, tgroups = self._trustusers, self._trustgroups
58 if '*' in tusers or '*' in tgroups:
58 if '*' in tusers or '*' in tgroups:
59 return True
59 return True
60
60
61 user = util.username(st.st_uid)
61 user = util.username(st.st_uid)
62 group = util.groupname(st.st_gid)
62 group = util.groupname(st.st_gid)
63 if user in tusers or group in tgroups or user == util.username():
63 if user in tusers or group in tgroups or user == util.username():
64 return True
64 return True
65
65
66 if self._reportuntrusted:
66 if self._reportuntrusted:
67 self.warn(_('Not trusting file %s from untrusted '
67 self.warn(_('Not trusting file %s from untrusted '
68 'user %s, group %s\n') % (f, user, group))
68 'user %s, group %s\n') % (f, user, group))
69 return False
69 return False
70
70
71 def readconfig(self, filename, root=None, trust=False,
71 def readconfig(self, filename, root=None, trust=False,
72 sections=None, remap=None):
72 sections=None, remap=None):
73 try:
73 try:
74 fp = open(filename)
74 fp = open(filename)
75 except IOError:
75 except IOError:
76 if not sections: # ignore unless we were looking for something
76 if not sections: # ignore unless we were looking for something
77 return
77 return
78 raise
78 raise
79
79
80 cfg = config.config()
80 cfg = config.config()
81 trusted = sections or trust or self._trusted(fp, filename)
81 trusted = sections or trust or self._trusted(fp, filename)
82
82
83 try:
83 try:
84 cfg.read(filename, fp, sections=sections, remap=remap)
84 cfg.read(filename, fp, sections=sections, remap=remap)
85 fp.close()
85 fp.close()
86 except error.ConfigError, inst:
86 except error.ConfigError, inst:
87 if trusted:
87 if trusted:
88 raise
88 raise
89 self.warn(_("Ignored: %s\n") % str(inst))
89 self.warn(_("Ignored: %s\n") % str(inst))
90
90
91 if self.plain():
91 if self.plain():
92 for k in ('debug', 'fallbackencoding', 'quiet', 'slash',
92 for k in ('debug', 'fallbackencoding', 'quiet', 'slash',
93 'logtemplate', 'style',
93 'logtemplate', 'style',
94 'traceback', 'verbose'):
94 'traceback', 'verbose'):
95 if k in cfg['ui']:
95 if k in cfg['ui']:
96 del cfg['ui'][k]
96 del cfg['ui'][k]
97 for k, v in cfg.items('defaults'):
97 for k, v in cfg.items('defaults'):
98 del cfg['defaults'][k]
98 del cfg['defaults'][k]
99 # Don't remove aliases from the configuration if in the exceptionlist
99 # Don't remove aliases from the configuration if in the exceptionlist
100 if self.plain('alias'):
100 if self.plain('alias'):
101 for k, v in cfg.items('alias'):
101 for k, v in cfg.items('alias'):
102 del cfg['alias'][k]
102 del cfg['alias'][k]
103
103
104 if trusted:
104 if trusted:
105 self._tcfg.update(cfg)
105 self._tcfg.update(cfg)
106 self._tcfg.update(self._ocfg)
106 self._tcfg.update(self._ocfg)
107 self._ucfg.update(cfg)
107 self._ucfg.update(cfg)
108 self._ucfg.update(self._ocfg)
108 self._ucfg.update(self._ocfg)
109
109
110 if root is None:
110 if root is None:
111 root = os.path.expanduser('~')
111 root = os.path.expanduser('~')
112 self.fixconfig(root=root)
112 self.fixconfig(root=root)
113
113
114 def fixconfig(self, root=None, section=None):
114 def fixconfig(self, root=None, section=None):
115 if section in (None, 'paths'):
115 if section in (None, 'paths'):
116 # expand vars and ~
116 # expand vars and ~
117 # translate paths relative to root (or home) into absolute paths
117 # translate paths relative to root (or home) into absolute paths
118 root = root or os.getcwd()
118 root = root or os.getcwd()
119 for c in self._tcfg, self._ucfg, self._ocfg:
119 for c in self._tcfg, self._ucfg, self._ocfg:
120 for n, p in c.items('paths'):
120 for n, p in c.items('paths'):
121 if not p:
121 if not p:
122 continue
122 continue
123 if '%%' in p:
123 if '%%' in p:
124 self.warn(_("(deprecated '%%' in path %s=%s from %s)\n")
124 self.warn(_("(deprecated '%%' in path %s=%s from %s)\n")
125 % (n, p, self.configsource('paths', n)))
125 % (n, p, self.configsource('paths', n)))
126 p = p.replace('%%', '%')
126 p = p.replace('%%', '%')
127 p = util.expandpath(p)
127 p = util.expandpath(p)
128 if not util.hasscheme(p) and not os.path.isabs(p):
128 if not util.hasscheme(p) and not os.path.isabs(p):
129 p = os.path.normpath(os.path.join(root, p))
129 p = os.path.normpath(os.path.join(root, p))
130 c.set("paths", n, p)
130 c.set("paths", n, p)
131
131
132 if section in (None, 'ui'):
132 if section in (None, 'ui'):
133 # update ui options
133 # update ui options
134 self.debugflag = self.configbool('ui', 'debug')
134 self.debugflag = self.configbool('ui', 'debug')
135 self.verbose = self.debugflag or self.configbool('ui', 'verbose')
135 self.verbose = self.debugflag or self.configbool('ui', 'verbose')
136 self.quiet = not self.debugflag and self.configbool('ui', 'quiet')
136 self.quiet = not self.debugflag and self.configbool('ui', 'quiet')
137 if self.verbose and self.quiet:
137 if self.verbose and self.quiet:
138 self.quiet = self.verbose = False
138 self.quiet = self.verbose = False
139 self._reportuntrusted = self.debugflag or self.configbool("ui",
139 self._reportuntrusted = self.debugflag or self.configbool("ui",
140 "report_untrusted", True)
140 "report_untrusted", True)
141 self.tracebackflag = self.configbool('ui', 'traceback', False)
141 self.tracebackflag = self.configbool('ui', 'traceback', False)
142
142
143 if section in (None, 'trusted'):
143 if section in (None, 'trusted'):
144 # update trust information
144 # update trust information
145 self._trustusers.update(self.configlist('trusted', 'users'))
145 self._trustusers.update(self.configlist('trusted', 'users'))
146 self._trustgroups.update(self.configlist('trusted', 'groups'))
146 self._trustgroups.update(self.configlist('trusted', 'groups'))
147
147
148 def backupconfig(self, section, item):
148 def backupconfig(self, section, item):
149 return (self._ocfg.backup(section, item),
149 return (self._ocfg.backup(section, item),
150 self._tcfg.backup(section, item),
150 self._tcfg.backup(section, item),
151 self._ucfg.backup(section, item),)
151 self._ucfg.backup(section, item),)
152 def restoreconfig(self, data):
152 def restoreconfig(self, data):
153 self._ocfg.restore(data[0])
153 self._ocfg.restore(data[0])
154 self._tcfg.restore(data[1])
154 self._tcfg.restore(data[1])
155 self._ucfg.restore(data[2])
155 self._ucfg.restore(data[2])
156
156
157 def setconfig(self, section, name, value, overlay=True):
157 def setconfig(self, section, name, value, overlay=True):
158 if overlay:
158 if overlay:
159 self._ocfg.set(section, name, value)
159 self._ocfg.set(section, name, value)
160 self._tcfg.set(section, name, value)
160 self._tcfg.set(section, name, value)
161 self._ucfg.set(section, name, value)
161 self._ucfg.set(section, name, value)
162 self.fixconfig(section=section)
162 self.fixconfig(section=section)
163
163
164 def _data(self, untrusted):
164 def _data(self, untrusted):
165 return untrusted and self._ucfg or self._tcfg
165 return untrusted and self._ucfg or self._tcfg
166
166
167 def configsource(self, section, name, untrusted=False):
167 def configsource(self, section, name, untrusted=False):
168 return self._data(untrusted).source(section, name) or 'none'
168 return self._data(untrusted).source(section, name) or 'none'
169
169
170 def config(self, section, name, default=None, untrusted=False):
170 def config(self, section, name, default=None, untrusted=False):
171 if isinstance(name, list):
171 if isinstance(name, list):
172 alternates = name
172 alternates = name
173 else:
173 else:
174 alternates = [name]
174 alternates = [name]
175
175
176 for n in alternates:
176 for n in alternates:
177 value = self._data(untrusted).get(section, name, None)
177 value = self._data(untrusted).get(section, name, None)
178 if value is not None:
178 if value is not None:
179 name = n
179 name = n
180 break
180 break
181 else:
181 else:
182 value = default
182 value = default
183
183
184 if self.debugflag and not untrusted and self._reportuntrusted:
184 if self.debugflag and not untrusted and self._reportuntrusted:
185 uvalue = self._ucfg.get(section, name)
185 uvalue = self._ucfg.get(section, name)
186 if uvalue is not None and uvalue != value:
186 if uvalue is not None and uvalue != value:
187 self.debug("ignoring untrusted configuration option "
187 self.debug("ignoring untrusted configuration option "
188 "%s.%s = %s\n" % (section, name, uvalue))
188 "%s.%s = %s\n" % (section, name, uvalue))
189 return value
189 return value
190
190
191 def configpath(self, section, name, default=None, untrusted=False):
191 def configpath(self, section, name, default=None, untrusted=False):
192 'get a path config item, expanded relative to repo root or config file'
192 'get a path config item, expanded relative to repo root or config file'
193 v = self.config(section, name, default, untrusted)
193 v = self.config(section, name, default, untrusted)
194 if v is None:
194 if v is None:
195 return None
195 return None
196 if not os.path.isabs(v) or "://" not in v:
196 if not os.path.isabs(v) or "://" not in v:
197 src = self.configsource(section, name, untrusted)
197 src = self.configsource(section, name, untrusted)
198 if ':' in src:
198 if ':' in src:
199 base = os.path.dirname(src.rsplit(':')[0])
199 base = os.path.dirname(src.rsplit(':')[0])
200 v = os.path.join(base, os.path.expanduser(v))
200 v = os.path.join(base, os.path.expanduser(v))
201 return v
201 return v
202
202
203 def configbool(self, section, name, default=False, untrusted=False):
203 def configbool(self, section, name, default=False, untrusted=False):
204 """parse a configuration element as a boolean
204 """parse a configuration element as a boolean
205
205
206 >>> u = ui(); s = 'foo'
206 >>> u = ui(); s = 'foo'
207 >>> u.setconfig(s, 'true', 'yes')
207 >>> u.setconfig(s, 'true', 'yes')
208 >>> u.configbool(s, 'true')
208 >>> u.configbool(s, 'true')
209 True
209 True
210 >>> u.setconfig(s, 'false', 'no')
210 >>> u.setconfig(s, 'false', 'no')
211 >>> u.configbool(s, 'false')
211 >>> u.configbool(s, 'false')
212 False
212 False
213 >>> u.configbool(s, 'unknown')
213 >>> u.configbool(s, 'unknown')
214 False
214 False
215 >>> u.configbool(s, 'unknown', True)
215 >>> u.configbool(s, 'unknown', True)
216 True
216 True
217 >>> u.setconfig(s, 'invalid', 'somevalue')
217 >>> u.setconfig(s, 'invalid', 'somevalue')
218 >>> u.configbool(s, 'invalid')
218 >>> u.configbool(s, 'invalid')
219 Traceback (most recent call last):
219 Traceback (most recent call last):
220 ...
220 ...
221 ConfigError: foo.invalid is not a boolean ('somevalue')
221 ConfigError: foo.invalid is not a boolean ('somevalue')
222 """
222 """
223
223
224 v = self.config(section, name, None, untrusted)
224 v = self.config(section, name, None, untrusted)
225 if v is None:
225 if v is None:
226 return default
226 return default
227 if isinstance(v, bool):
227 if isinstance(v, bool):
228 return v
228 return v
229 b = util.parsebool(v)
229 b = util.parsebool(v)
230 if b is None:
230 if b is None:
231 raise error.ConfigError(_("%s.%s is not a boolean ('%s')")
231 raise error.ConfigError(_("%s.%s is not a boolean ('%s')")
232 % (section, name, v))
232 % (section, name, v))
233 return b
233 return b
234
234
235 def configint(self, section, name, default=None, untrusted=False):
235 def configint(self, section, name, default=None, untrusted=False):
236 """parse a configuration element as an integer
236 """parse a configuration element as an integer
237
237
238 >>> u = ui(); s = 'foo'
238 >>> u = ui(); s = 'foo'
239 >>> u.setconfig(s, 'int1', '42')
239 >>> u.setconfig(s, 'int1', '42')
240 >>> u.configint(s, 'int1')
240 >>> u.configint(s, 'int1')
241 42
241 42
242 >>> u.setconfig(s, 'int2', '-42')
242 >>> u.setconfig(s, 'int2', '-42')
243 >>> u.configint(s, 'int2')
243 >>> u.configint(s, 'int2')
244 -42
244 -42
245 >>> u.configint(s, 'unknown', 7)
245 >>> u.configint(s, 'unknown', 7)
246 7
246 7
247 >>> u.setconfig(s, 'invalid', 'somevalue')
247 >>> u.setconfig(s, 'invalid', 'somevalue')
248 >>> u.configint(s, 'invalid')
248 >>> u.configint(s, 'invalid')
249 Traceback (most recent call last):
249 Traceback (most recent call last):
250 ...
250 ...
251 ConfigError: foo.invalid is not an integer ('somevalue')
251 ConfigError: foo.invalid is not an integer ('somevalue')
252 """
252 """
253
253
254 v = self.config(section, name, None, untrusted)
254 v = self.config(section, name, None, untrusted)
255 if v is None:
255 if v is None:
256 return default
256 return default
257 try:
257 try:
258 return int(v)
258 return int(v)
259 except ValueError:
259 except ValueError:
260 raise error.ConfigError(_("%s.%s is not an integer ('%s')")
260 raise error.ConfigError(_("%s.%s is not an integer ('%s')")
261 % (section, name, v))
261 % (section, name, v))
262
262
263 def configlist(self, section, name, default=None, untrusted=False):
263 def configlist(self, section, name, default=None, untrusted=False):
264 """parse a configuration element as a list of comma/space separated
264 """parse a configuration element as a list of comma/space separated
265 strings
265 strings
266
266
267 >>> u = ui(); s = 'foo'
267 >>> u = ui(); s = 'foo'
268 >>> u.setconfig(s, 'list1', 'this,is "a small" ,test')
268 >>> u.setconfig(s, 'list1', 'this,is "a small" ,test')
269 >>> u.configlist(s, 'list1')
269 >>> u.configlist(s, 'list1')
270 ['this', 'is', 'a small', 'test']
270 ['this', 'is', 'a small', 'test']
271 """
271 """
272
272
273 def _parse_plain(parts, s, offset):
273 def _parse_plain(parts, s, offset):
274 whitespace = False
274 whitespace = False
275 while offset < len(s) and (s[offset].isspace() or s[offset] == ','):
275 while offset < len(s) and (s[offset].isspace() or s[offset] == ','):
276 whitespace = True
276 whitespace = True
277 offset += 1
277 offset += 1
278 if offset >= len(s):
278 if offset >= len(s):
279 return None, parts, offset
279 return None, parts, offset
280 if whitespace:
280 if whitespace:
281 parts.append('')
281 parts.append('')
282 if s[offset] == '"' and not parts[-1]:
282 if s[offset] == '"' and not parts[-1]:
283 return _parse_quote, parts, offset + 1
283 return _parse_quote, parts, offset + 1
284 elif s[offset] == '"' and parts[-1][-1] == '\\':
284 elif s[offset] == '"' and parts[-1][-1] == '\\':
285 parts[-1] = parts[-1][:-1] + s[offset]
285 parts[-1] = parts[-1][:-1] + s[offset]
286 return _parse_plain, parts, offset + 1
286 return _parse_plain, parts, offset + 1
287 parts[-1] += s[offset]
287 parts[-1] += s[offset]
288 return _parse_plain, parts, offset + 1
288 return _parse_plain, parts, offset + 1
289
289
290 def _parse_quote(parts, s, offset):
290 def _parse_quote(parts, s, offset):
291 if offset < len(s) and s[offset] == '"': # ""
291 if offset < len(s) and s[offset] == '"': # ""
292 parts.append('')
292 parts.append('')
293 offset += 1
293 offset += 1
294 while offset < len(s) and (s[offset].isspace() or
294 while offset < len(s) and (s[offset].isspace() or
295 s[offset] == ','):
295 s[offset] == ','):
296 offset += 1
296 offset += 1
297 return _parse_plain, parts, offset
297 return _parse_plain, parts, offset
298
298
299 while offset < len(s) and s[offset] != '"':
299 while offset < len(s) and s[offset] != '"':
300 if (s[offset] == '\\' and offset + 1 < len(s)
300 if (s[offset] == '\\' and offset + 1 < len(s)
301 and s[offset + 1] == '"'):
301 and s[offset + 1] == '"'):
302 offset += 1
302 offset += 1
303 parts[-1] += '"'
303 parts[-1] += '"'
304 else:
304 else:
305 parts[-1] += s[offset]
305 parts[-1] += s[offset]
306 offset += 1
306 offset += 1
307
307
308 if offset >= len(s):
308 if offset >= len(s):
309 real_parts = _configlist(parts[-1])
309 real_parts = _configlist(parts[-1])
310 if not real_parts:
310 if not real_parts:
311 parts[-1] = '"'
311 parts[-1] = '"'
312 else:
312 else:
313 real_parts[0] = '"' + real_parts[0]
313 real_parts[0] = '"' + real_parts[0]
314 parts = parts[:-1]
314 parts = parts[:-1]
315 parts.extend(real_parts)
315 parts.extend(real_parts)
316 return None, parts, offset
316 return None, parts, offset
317
317
318 offset += 1
318 offset += 1
319 while offset < len(s) and s[offset] in [' ', ',']:
319 while offset < len(s) and s[offset] in [' ', ',']:
320 offset += 1
320 offset += 1
321
321
322 if offset < len(s):
322 if offset < len(s):
323 if offset + 1 == len(s) and s[offset] == '"':
323 if offset + 1 == len(s) and s[offset] == '"':
324 parts[-1] += '"'
324 parts[-1] += '"'
325 offset += 1
325 offset += 1
326 else:
326 else:
327 parts.append('')
327 parts.append('')
328 else:
328 else:
329 return None, parts, offset
329 return None, parts, offset
330
330
331 return _parse_plain, parts, offset
331 return _parse_plain, parts, offset
332
332
333 def _configlist(s):
333 def _configlist(s):
334 s = s.rstrip(' ,')
334 s = s.rstrip(' ,')
335 if not s:
335 if not s:
336 return []
336 return []
337 parser, parts, offset = _parse_plain, [''], 0
337 parser, parts, offset = _parse_plain, [''], 0
338 while parser:
338 while parser:
339 parser, parts, offset = parser(parts, s, offset)
339 parser, parts, offset = parser(parts, s, offset)
340 return parts
340 return parts
341
341
342 result = self.config(section, name, untrusted=untrusted)
342 result = self.config(section, name, untrusted=untrusted)
343 if result is None:
343 if result is None:
344 result = default or []
344 result = default or []
345 if isinstance(result, basestring):
345 if isinstance(result, basestring):
346 result = _configlist(result.lstrip(' ,\n'))
346 result = _configlist(result.lstrip(' ,\n'))
347 if result is None:
347 if result is None:
348 result = default or []
348 result = default or []
349 return result
349 return result
350
350
351 def has_section(self, section, untrusted=False):
351 def has_section(self, section, untrusted=False):
352 '''tell whether section exists in config.'''
352 '''tell whether section exists in config.'''
353 return section in self._data(untrusted)
353 return section in self._data(untrusted)
354
354
355 def configitems(self, section, untrusted=False):
355 def configitems(self, section, untrusted=False):
356 items = self._data(untrusted).items(section)
356 items = self._data(untrusted).items(section)
357 if self.debugflag and not untrusted and self._reportuntrusted:
357 if self.debugflag and not untrusted and self._reportuntrusted:
358 for k, v in self._ucfg.items(section):
358 for k, v in self._ucfg.items(section):
359 if self._tcfg.get(section, k) != v:
359 if self._tcfg.get(section, k) != v:
360 self.debug("ignoring untrusted configuration option "
360 self.debug("ignoring untrusted configuration option "
361 "%s.%s = %s\n" % (section, k, v))
361 "%s.%s = %s\n" % (section, k, v))
362 return items
362 return items
363
363
364 def walkconfig(self, untrusted=False):
364 def walkconfig(self, untrusted=False):
365 cfg = self._data(untrusted)
365 cfg = self._data(untrusted)
366 for section in cfg.sections():
366 for section in cfg.sections():
367 for name, value in self.configitems(section, untrusted):
367 for name, value in self.configitems(section, untrusted):
368 yield section, name, value
368 yield section, name, value
369
369
370 def plain(self, feature=None):
370 def plain(self, feature=None):
371 '''is plain mode active?
371 '''is plain mode active?
372
372
373 Plain mode means that all configuration variables which affect
373 Plain mode means that all configuration variables which affect
374 the behavior and output of Mercurial should be
374 the behavior and output of Mercurial should be
375 ignored. Additionally, the output should be stable,
375 ignored. Additionally, the output should be stable,
376 reproducible and suitable for use in scripts or applications.
376 reproducible and suitable for use in scripts or applications.
377
377
378 The only way to trigger plain mode is by setting either the
378 The only way to trigger plain mode is by setting either the
379 `HGPLAIN' or `HGPLAINEXCEPT' environment variables.
379 `HGPLAIN' or `HGPLAINEXCEPT' environment variables.
380
380
381 The return value can either be
381 The return value can either be
382 - False if HGPLAIN is not set, or feature is in HGPLAINEXCEPT
382 - False if HGPLAIN is not set, or feature is in HGPLAINEXCEPT
383 - True otherwise
383 - True otherwise
384 '''
384 '''
385 if 'HGPLAIN' not in os.environ and 'HGPLAINEXCEPT' not in os.environ:
385 if 'HGPLAIN' not in os.environ and 'HGPLAINEXCEPT' not in os.environ:
386 return False
386 return False
387 exceptions = os.environ.get('HGPLAINEXCEPT', '').strip().split(',')
387 exceptions = os.environ.get('HGPLAINEXCEPT', '').strip().split(',')
388 if feature and exceptions:
388 if feature and exceptions:
389 return feature not in exceptions
389 return feature not in exceptions
390 return True
390 return True
391
391
392 def username(self):
392 def username(self):
393 """Return default username to be used in commits.
393 """Return default username to be used in commits.
394
394
395 Searched in this order: $HGUSER, [ui] section of hgrcs, $EMAIL
395 Searched in this order: $HGUSER, [ui] section of hgrcs, $EMAIL
396 and stop searching if one of these is set.
396 and stop searching if one of these is set.
397 If not found and ui.askusername is True, ask the user, else use
397 If not found and ui.askusername is True, ask the user, else use
398 ($LOGNAME or $USER or $LNAME or $USERNAME) + "@full.hostname".
398 ($LOGNAME or $USER or $LNAME or $USERNAME) + "@full.hostname".
399 """
399 """
400 user = os.environ.get("HGUSER")
400 user = os.environ.get("HGUSER")
401 if user is None:
401 if user is None:
402 user = self.config("ui", "username")
402 user = self.config("ui", "username")
403 if user is not None:
403 if user is not None:
404 user = os.path.expandvars(user)
404 user = os.path.expandvars(user)
405 if user is None:
405 if user is None:
406 user = os.environ.get("EMAIL")
406 user = os.environ.get("EMAIL")
407 if user is None and self.configbool("ui", "askusername"):
407 if user is None and self.configbool("ui", "askusername"):
408 user = self.prompt(_("enter a commit username:"), default=None)
408 user = self.prompt(_("enter a commit username:"), default=None)
409 if user is None and not self.interactive():
409 if user is None and not self.interactive():
410 try:
410 try:
411 user = '%s@%s' % (util.getuser(), socket.getfqdn())
411 user = '%s@%s' % (util.getuser(), socket.getfqdn())
412 self.warn(_("No username found, using '%s' instead\n") % user)
412 self.warn(_("No username found, using '%s' instead\n") % user)
413 except KeyError:
413 except KeyError:
414 pass
414 pass
415 if not user:
415 if not user:
416 raise util.Abort(_('no username supplied (see "hg help config")'))
416 raise util.Abort(_('no username supplied (see "hg help config")'))
417 if "\n" in user:
417 if "\n" in user:
418 raise util.Abort(_("username %s contains a newline\n") % repr(user))
418 raise util.Abort(_("username %s contains a newline\n") % repr(user))
419 return user
419 return user
420
420
421 def shortuser(self, user):
421 def shortuser(self, user):
422 """Return a short representation of a user name or email address."""
422 """Return a short representation of a user name or email address."""
423 if not self.verbose:
423 if not self.verbose:
424 user = util.shortuser(user)
424 user = util.shortuser(user)
425 return user
425 return user
426
426
427 def expandpath(self, loc, default=None):
427 def expandpath(self, loc, default=None):
428 """Return repository location relative to cwd or from [paths]"""
428 """Return repository location relative to cwd or from [paths]"""
429 if util.hasscheme(loc) or os.path.isdir(os.path.join(loc, '.hg')):
429 if util.hasscheme(loc) or os.path.isdir(os.path.join(loc, '.hg')):
430 return loc
430 return loc
431
431
432 path = self.config('paths', loc)
432 path = self.config('paths', loc)
433 if not path and default is not None:
433 if not path and default is not None:
434 path = self.config('paths', default)
434 path = self.config('paths', default)
435 return path or loc
435 return path or loc
436
436
437 def pushbuffer(self):
437 def pushbuffer(self):
438 self._buffers.append([])
438 self._buffers.append([])
439
439
440 def popbuffer(self, labeled=False):
440 def popbuffer(self, labeled=False):
441 '''pop the last buffer and return the buffered output
441 '''pop the last buffer and return the buffered output
442
442
443 If labeled is True, any labels associated with buffered
443 If labeled is True, any labels associated with buffered
444 output will be handled. By default, this has no effect
444 output will be handled. By default, this has no effect
445 on the output returned, but extensions and GUI tools may
445 on the output returned, but extensions and GUI tools may
446 handle this argument and returned styled output. If output
446 handle this argument and returned styled output. If output
447 is being buffered so it can be captured and parsed or
447 is being buffered so it can be captured and parsed or
448 processed, labeled should not be set to True.
448 processed, labeled should not be set to True.
449 '''
449 '''
450 return "".join(self._buffers.pop())
450 return "".join(self._buffers.pop())
451
451
452 def write(self, *args, **opts):
452 def write(self, *args, **opts):
453 '''write args to output
453 '''write args to output
454
454
455 By default, this method simply writes to the buffer or stdout,
455 By default, this method simply writes to the buffer or stdout,
456 but extensions or GUI tools may override this method,
456 but extensions or GUI tools may override this method,
457 write_err(), popbuffer(), and label() to style output from
457 write_err(), popbuffer(), and label() to style output from
458 various parts of hg.
458 various parts of hg.
459
459
460 An optional keyword argument, "label", can be passed in.
460 An optional keyword argument, "label", can be passed in.
461 This should be a string containing label names separated by
461 This should be a string containing label names separated by
462 space. Label names take the form of "topic.type". For example,
462 space. Label names take the form of "topic.type". For example,
463 ui.debug() issues a label of "ui.debug".
463 ui.debug() issues a label of "ui.debug".
464
464
465 When labeling output for a specific command, a label of
465 When labeling output for a specific command, a label of
466 "cmdname.type" is recommended. For example, status issues
466 "cmdname.type" is recommended. For example, status issues
467 a label of "status.modified" for modified files.
467 a label of "status.modified" for modified files.
468 '''
468 '''
469 if self._buffers:
469 if self._buffers:
470 self._buffers[-1].extend([str(a) for a in args])
470 self._buffers[-1].extend([str(a) for a in args])
471 else:
471 else:
472 for a in args:
472 for a in args:
473 self.fout.write(str(a))
473 self.fout.write(str(a))
474
474
475 def write_err(self, *args, **opts):
475 def write_err(self, *args, **opts):
476 try:
476 try:
477 if not getattr(self.fout, 'closed', False):
477 if not getattr(self.fout, 'closed', False):
478 self.fout.flush()
478 self.fout.flush()
479 for a in args:
479 for a in args:
480 self.ferr.write(str(a))
480 self.ferr.write(str(a))
481 # stderr may be buffered under win32 when redirected to files,
481 # stderr may be buffered under win32 when redirected to files,
482 # including stdout.
482 # including stdout.
483 if not getattr(self.ferr, 'closed', False):
483 if not getattr(self.ferr, 'closed', False):
484 self.ferr.flush()
484 self.ferr.flush()
485 except IOError, inst:
485 except IOError, inst:
486 if inst.errno not in (errno.EPIPE, errno.EIO):
486 if inst.errno not in (errno.EPIPE, errno.EIO, errno.EBADF):
487 raise
487 raise
488
488
489 def flush(self):
489 def flush(self):
490 try: self.fout.flush()
490 try: self.fout.flush()
491 except: pass
491 except: pass
492 try: self.ferr.flush()
492 try: self.ferr.flush()
493 except: pass
493 except: pass
494
494
495 def interactive(self):
495 def interactive(self):
496 '''is interactive input allowed?
496 '''is interactive input allowed?
497
497
498 An interactive session is a session where input can be reasonably read
498 An interactive session is a session where input can be reasonably read
499 from `sys.stdin'. If this function returns false, any attempt to read
499 from `sys.stdin'. If this function returns false, any attempt to read
500 from stdin should fail with an error, unless a sensible default has been
500 from stdin should fail with an error, unless a sensible default has been
501 specified.
501 specified.
502
502
503 Interactiveness is triggered by the value of the `ui.interactive'
503 Interactiveness is triggered by the value of the `ui.interactive'
504 configuration variable or - if it is unset - when `sys.stdin' points
504 configuration variable or - if it is unset - when `sys.stdin' points
505 to a terminal device.
505 to a terminal device.
506
506
507 This function refers to input only; for output, see `ui.formatted()'.
507 This function refers to input only; for output, see `ui.formatted()'.
508 '''
508 '''
509 i = self.configbool("ui", "interactive", None)
509 i = self.configbool("ui", "interactive", None)
510 if i is None:
510 if i is None:
511 # some environments replace stdin without implementing isatty
511 # some environments replace stdin without implementing isatty
512 # usually those are non-interactive
512 # usually those are non-interactive
513 return util.isatty(self.fin)
513 return util.isatty(self.fin)
514
514
515 return i
515 return i
516
516
517 def termwidth(self):
517 def termwidth(self):
518 '''how wide is the terminal in columns?
518 '''how wide is the terminal in columns?
519 '''
519 '''
520 if 'COLUMNS' in os.environ:
520 if 'COLUMNS' in os.environ:
521 try:
521 try:
522 return int(os.environ['COLUMNS'])
522 return int(os.environ['COLUMNS'])
523 except ValueError:
523 except ValueError:
524 pass
524 pass
525 return util.termwidth()
525 return util.termwidth()
526
526
527 def formatted(self):
527 def formatted(self):
528 '''should formatted output be used?
528 '''should formatted output be used?
529
529
530 It is often desirable to format the output to suite the output medium.
530 It is often desirable to format the output to suite the output medium.
531 Examples of this are truncating long lines or colorizing messages.
531 Examples of this are truncating long lines or colorizing messages.
532 However, this is not often not desirable when piping output into other
532 However, this is not often not desirable when piping output into other
533 utilities, e.g. `grep'.
533 utilities, e.g. `grep'.
534
534
535 Formatted output is triggered by the value of the `ui.formatted'
535 Formatted output is triggered by the value of the `ui.formatted'
536 configuration variable or - if it is unset - when `sys.stdout' points
536 configuration variable or - if it is unset - when `sys.stdout' points
537 to a terminal device. Please note that `ui.formatted' should be
537 to a terminal device. Please note that `ui.formatted' should be
538 considered an implementation detail; it is not intended for use outside
538 considered an implementation detail; it is not intended for use outside
539 Mercurial or its extensions.
539 Mercurial or its extensions.
540
540
541 This function refers to output only; for input, see `ui.interactive()'.
541 This function refers to output only; for input, see `ui.interactive()'.
542 This function always returns false when in plain mode, see `ui.plain()'.
542 This function always returns false when in plain mode, see `ui.plain()'.
543 '''
543 '''
544 if self.plain():
544 if self.plain():
545 return False
545 return False
546
546
547 i = self.configbool("ui", "formatted", None)
547 i = self.configbool("ui", "formatted", None)
548 if i is None:
548 if i is None:
549 # some environments replace stdout without implementing isatty
549 # some environments replace stdout without implementing isatty
550 # usually those are non-interactive
550 # usually those are non-interactive
551 return util.isatty(self.fout)
551 return util.isatty(self.fout)
552
552
553 return i
553 return i
554
554
555 def _readline(self, prompt=''):
555 def _readline(self, prompt=''):
556 if util.isatty(self.fin):
556 if util.isatty(self.fin):
557 try:
557 try:
558 # magically add command line editing support, where
558 # magically add command line editing support, where
559 # available
559 # available
560 import readline
560 import readline
561 # force demandimport to really load the module
561 # force demandimport to really load the module
562 readline.read_history_file
562 readline.read_history_file
563 # windows sometimes raises something other than ImportError
563 # windows sometimes raises something other than ImportError
564 except Exception:
564 except Exception:
565 pass
565 pass
566
566
567 # call write() so output goes through subclassed implementation
567 # call write() so output goes through subclassed implementation
568 # e.g. color extension on Windows
568 # e.g. color extension on Windows
569 self.write(prompt)
569 self.write(prompt)
570
570
571 # instead of trying to emulate raw_input, swap (self.fin,
571 # instead of trying to emulate raw_input, swap (self.fin,
572 # self.fout) with (sys.stdin, sys.stdout)
572 # self.fout) with (sys.stdin, sys.stdout)
573 oldin = sys.stdin
573 oldin = sys.stdin
574 oldout = sys.stdout
574 oldout = sys.stdout
575 sys.stdin = self.fin
575 sys.stdin = self.fin
576 sys.stdout = self.fout
576 sys.stdout = self.fout
577 line = raw_input(' ')
577 line = raw_input(' ')
578 sys.stdin = oldin
578 sys.stdin = oldin
579 sys.stdout = oldout
579 sys.stdout = oldout
580
580
581 # When stdin is in binary mode on Windows, it can cause
581 # When stdin is in binary mode on Windows, it can cause
582 # raw_input() to emit an extra trailing carriage return
582 # raw_input() to emit an extra trailing carriage return
583 if os.linesep == '\r\n' and line and line[-1] == '\r':
583 if os.linesep == '\r\n' and line and line[-1] == '\r':
584 line = line[:-1]
584 line = line[:-1]
585 return line
585 return line
586
586
587 def prompt(self, msg, default="y"):
587 def prompt(self, msg, default="y"):
588 """Prompt user with msg, read response.
588 """Prompt user with msg, read response.
589 If ui is not interactive, the default is returned.
589 If ui is not interactive, the default is returned.
590 """
590 """
591 if not self.interactive():
591 if not self.interactive():
592 self.write(msg, ' ', default, "\n")
592 self.write(msg, ' ', default, "\n")
593 return default
593 return default
594 try:
594 try:
595 r = self._readline(self.label(msg, 'ui.prompt'))
595 r = self._readline(self.label(msg, 'ui.prompt'))
596 if not r:
596 if not r:
597 return default
597 return default
598 return r
598 return r
599 except EOFError:
599 except EOFError:
600 raise util.Abort(_('response expected'))
600 raise util.Abort(_('response expected'))
601
601
602 def promptchoice(self, msg, choices, default=0):
602 def promptchoice(self, msg, choices, default=0):
603 """Prompt user with msg, read response, and ensure it matches
603 """Prompt user with msg, read response, and ensure it matches
604 one of the provided choices. The index of the choice is returned.
604 one of the provided choices. The index of the choice is returned.
605 choices is a sequence of acceptable responses with the format:
605 choices is a sequence of acceptable responses with the format:
606 ('&None', 'E&xec', 'Sym&link') Responses are case insensitive.
606 ('&None', 'E&xec', 'Sym&link') Responses are case insensitive.
607 If ui is not interactive, the default is returned.
607 If ui is not interactive, the default is returned.
608 """
608 """
609 resps = [s[s.index('&')+1].lower() for s in choices]
609 resps = [s[s.index('&')+1].lower() for s in choices]
610 while True:
610 while True:
611 r = self.prompt(msg, resps[default])
611 r = self.prompt(msg, resps[default])
612 if r.lower() in resps:
612 if r.lower() in resps:
613 return resps.index(r.lower())
613 return resps.index(r.lower())
614 self.write(_("unrecognized response\n"))
614 self.write(_("unrecognized response\n"))
615
615
616 def getpass(self, prompt=None, default=None):
616 def getpass(self, prompt=None, default=None):
617 if not self.interactive():
617 if not self.interactive():
618 return default
618 return default
619 try:
619 try:
620 return getpass.getpass(prompt or _('password: '))
620 return getpass.getpass(prompt or _('password: '))
621 except EOFError:
621 except EOFError:
622 raise util.Abort(_('response expected'))
622 raise util.Abort(_('response expected'))
623 def status(self, *msg, **opts):
623 def status(self, *msg, **opts):
624 '''write status message to output (if ui.quiet is False)
624 '''write status message to output (if ui.quiet is False)
625
625
626 This adds an output label of "ui.status".
626 This adds an output label of "ui.status".
627 '''
627 '''
628 if not self.quiet:
628 if not self.quiet:
629 opts['label'] = opts.get('label', '') + ' ui.status'
629 opts['label'] = opts.get('label', '') + ' ui.status'
630 self.write(*msg, **opts)
630 self.write(*msg, **opts)
631 def warn(self, *msg, **opts):
631 def warn(self, *msg, **opts):
632 '''write warning message to output (stderr)
632 '''write warning message to output (stderr)
633
633
634 This adds an output label of "ui.warning".
634 This adds an output label of "ui.warning".
635 '''
635 '''
636 opts['label'] = opts.get('label', '') + ' ui.warning'
636 opts['label'] = opts.get('label', '') + ' ui.warning'
637 self.write_err(*msg, **opts)
637 self.write_err(*msg, **opts)
638 def note(self, *msg, **opts):
638 def note(self, *msg, **opts):
639 '''write note to output (if ui.verbose is True)
639 '''write note to output (if ui.verbose is True)
640
640
641 This adds an output label of "ui.note".
641 This adds an output label of "ui.note".
642 '''
642 '''
643 if self.verbose:
643 if self.verbose:
644 opts['label'] = opts.get('label', '') + ' ui.note'
644 opts['label'] = opts.get('label', '') + ' ui.note'
645 self.write(*msg, **opts)
645 self.write(*msg, **opts)
646 def debug(self, *msg, **opts):
646 def debug(self, *msg, **opts):
647 '''write debug message to output (if ui.debugflag is True)
647 '''write debug message to output (if ui.debugflag is True)
648
648
649 This adds an output label of "ui.debug".
649 This adds an output label of "ui.debug".
650 '''
650 '''
651 if self.debugflag:
651 if self.debugflag:
652 opts['label'] = opts.get('label', '') + ' ui.debug'
652 opts['label'] = opts.get('label', '') + ' ui.debug'
653 self.write(*msg, **opts)
653 self.write(*msg, **opts)
654 def edit(self, text, user):
654 def edit(self, text, user):
655 (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt",
655 (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt",
656 text=True)
656 text=True)
657 try:
657 try:
658 f = os.fdopen(fd, "w")
658 f = os.fdopen(fd, "w")
659 f.write(text)
659 f.write(text)
660 f.close()
660 f.close()
661
661
662 editor = self.geteditor()
662 editor = self.geteditor()
663
663
664 util.system("%s \"%s\"" % (editor, name),
664 util.system("%s \"%s\"" % (editor, name),
665 environ={'HGUSER': user},
665 environ={'HGUSER': user},
666 onerr=util.Abort, errprefix=_("edit failed"),
666 onerr=util.Abort, errprefix=_("edit failed"),
667 out=self.fout)
667 out=self.fout)
668
668
669 f = open(name)
669 f = open(name)
670 t = f.read()
670 t = f.read()
671 f.close()
671 f.close()
672 finally:
672 finally:
673 os.unlink(name)
673 os.unlink(name)
674
674
675 return t
675 return t
676
676
677 def traceback(self, exc=None):
677 def traceback(self, exc=None):
678 '''print exception traceback if traceback printing enabled.
678 '''print exception traceback if traceback printing enabled.
679 only to call in exception handler. returns true if traceback
679 only to call in exception handler. returns true if traceback
680 printed.'''
680 printed.'''
681 if self.tracebackflag:
681 if self.tracebackflag:
682 if exc:
682 if exc:
683 traceback.print_exception(exc[0], exc[1], exc[2], file=self.ferr)
683 traceback.print_exception(exc[0], exc[1], exc[2], file=self.ferr)
684 else:
684 else:
685 traceback.print_exc(file=self.ferr)
685 traceback.print_exc(file=self.ferr)
686 return self.tracebackflag
686 return self.tracebackflag
687
687
688 def geteditor(self):
688 def geteditor(self):
689 '''return editor to use'''
689 '''return editor to use'''
690 return (os.environ.get("HGEDITOR") or
690 return (os.environ.get("HGEDITOR") or
691 self.config("ui", "editor") or
691 self.config("ui", "editor") or
692 os.environ.get("VISUAL") or
692 os.environ.get("VISUAL") or
693 os.environ.get("EDITOR", "vi"))
693 os.environ.get("EDITOR", "vi"))
694
694
695 def progress(self, topic, pos, item="", unit="", total=None):
695 def progress(self, topic, pos, item="", unit="", total=None):
696 '''show a progress message
696 '''show a progress message
697
697
698 With stock hg, this is simply a debug message that is hidden
698 With stock hg, this is simply a debug message that is hidden
699 by default, but with extensions or GUI tools it may be
699 by default, but with extensions or GUI tools it may be
700 visible. 'topic' is the current operation, 'item' is a
700 visible. 'topic' is the current operation, 'item' is a
701 non-numeric marker of the current position (ie the currently
701 non-numeric marker of the current position (ie the currently
702 in-process file), 'pos' is the current numeric position (ie
702 in-process file), 'pos' is the current numeric position (ie
703 revision, bytes, etc.), unit is a corresponding unit label,
703 revision, bytes, etc.), unit is a corresponding unit label,
704 and total is the highest expected pos.
704 and total is the highest expected pos.
705
705
706 Multiple nested topics may be active at a time.
706 Multiple nested topics may be active at a time.
707
707
708 All topics should be marked closed by setting pos to None at
708 All topics should be marked closed by setting pos to None at
709 termination.
709 termination.
710 '''
710 '''
711
711
712 if pos is None or not self.debugflag:
712 if pos is None or not self.debugflag:
713 return
713 return
714
714
715 if unit:
715 if unit:
716 unit = ' ' + unit
716 unit = ' ' + unit
717 if item:
717 if item:
718 item = ' ' + item
718 item = ' ' + item
719
719
720 if total:
720 if total:
721 pct = 100.0 * pos / total
721 pct = 100.0 * pos / total
722 self.debug('%s:%s %s/%s%s (%4.2f%%)\n'
722 self.debug('%s:%s %s/%s%s (%4.2f%%)\n'
723 % (topic, item, pos, total, unit, pct))
723 % (topic, item, pos, total, unit, pct))
724 else:
724 else:
725 self.debug('%s:%s %s%s\n' % (topic, item, pos, unit))
725 self.debug('%s:%s %s%s\n' % (topic, item, pos, unit))
726
726
727 def log(self, service, message):
727 def log(self, service, message):
728 '''hook for logging facility extensions
728 '''hook for logging facility extensions
729
729
730 service should be a readily-identifiable subsystem, which will
730 service should be a readily-identifiable subsystem, which will
731 allow filtering.
731 allow filtering.
732 message should be a newline-terminated string to log.
732 message should be a newline-terminated string to log.
733 '''
733 '''
734 pass
734 pass
735
735
736 def label(self, msg, label):
736 def label(self, msg, label):
737 '''style msg based on supplied label
737 '''style msg based on supplied label
738
738
739 Like ui.write(), this just returns msg unchanged, but extensions
739 Like ui.write(), this just returns msg unchanged, but extensions
740 and GUI tools can override it to allow styling output without
740 and GUI tools can override it to allow styling output without
741 writing it.
741 writing it.
742
742
743 ui.write(s, 'label') is equivalent to
743 ui.write(s, 'label') is equivalent to
744 ui.write(ui.label(s, 'label')).
744 ui.write(ui.label(s, 'label')).
745 '''
745 '''
746 return msg
746 return msg
@@ -1,345 +1,344 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Test the running system for features availability. Exit with zero
2 """Test the running system for features availability. Exit with zero
3 if all features are there, non-zero otherwise. If a feature name is
3 if all features are there, non-zero otherwise. If a feature name is
4 prefixed with "no-", the absence of feature is tested.
4 prefixed with "no-", the absence of feature is tested.
5 """
5 """
6 import optparse
6 import optparse
7 import os, stat
7 import os, stat
8 import re
8 import re
9 import sys
9 import sys
10 import tempfile
10 import tempfile
11
11
12 tempprefix = 'hg-hghave-'
12 tempprefix = 'hg-hghave-'
13
13
14 def matchoutput(cmd, regexp, ignorestatus=False):
14 def matchoutput(cmd, regexp, ignorestatus=False):
15 """Return True if cmd executes successfully and its output
15 """Return True if cmd executes successfully and its output
16 is matched by the supplied regular expression.
16 is matched by the supplied regular expression.
17 """
17 """
18 r = re.compile(regexp)
18 r = re.compile(regexp)
19 fh = os.popen(cmd)
19 fh = os.popen(cmd)
20 s = fh.read()
20 s = fh.read()
21 try:
21 try:
22 ret = fh.close()
22 ret = fh.close()
23 except IOError:
23 except IOError:
24 # Happen in Windows test environment
24 # Happen in Windows test environment
25 ret = 1
25 ret = 1
26 return (ignorestatus or ret is None) and r.search(s)
26 return (ignorestatus or ret is None) and r.search(s)
27
27
28 def has_baz():
28 def has_baz():
29 return matchoutput('baz --version 2>&1', r'baz Bazaar version')
29 return matchoutput('baz --version 2>&1', r'baz Bazaar version')
30
30
31 def has_bzr():
31 def has_bzr():
32 try:
32 try:
33 import bzrlib
33 import bzrlib
34 return bzrlib.__doc__ != None
34 return bzrlib.__doc__ != None
35 except ImportError:
35 except ImportError:
36 return False
36 return False
37
37
38 def has_bzr114():
38 def has_bzr114():
39 try:
39 try:
40 import bzrlib
40 import bzrlib
41 return (bzrlib.__doc__ != None
41 return (bzrlib.__doc__ != None
42 and bzrlib.version_info[:2] >= (1, 14))
42 and bzrlib.version_info[:2] >= (1, 14))
43 except ImportError:
43 except ImportError:
44 return False
44 return False
45
45
46 def has_cvs():
46 def has_cvs():
47 re = r'Concurrent Versions System.*?server'
47 re = r'Concurrent Versions System.*?server'
48 return matchoutput('cvs --version 2>&1', re) and not has_msys()
48 return matchoutput('cvs --version 2>&1', re) and not has_msys()
49
49
50 def has_darcs():
50 def has_darcs():
51 return matchoutput('darcs --version', r'2\.[2-9]', True)
51 return matchoutput('darcs --version', r'2\.[2-9]', True)
52
52
53 def has_mtn():
53 def has_mtn():
54 return matchoutput('mtn --version', r'monotone', True) and not matchoutput(
54 return matchoutput('mtn --version', r'monotone', True) and not matchoutput(
55 'mtn --version', r'monotone 0\.', True)
55 'mtn --version', r'monotone 0\.', True)
56
56
57 def has_eol_in_paths():
57 def has_eol_in_paths():
58 try:
58 try:
59 fd, path = tempfile.mkstemp(prefix=tempprefix, suffix='\n\r')
59 fd, path = tempfile.mkstemp(prefix=tempprefix, suffix='\n\r')
60 os.close(fd)
60 os.close(fd)
61 os.remove(path)
61 os.remove(path)
62 return True
62 return True
63 except:
63 except:
64 return False
64 return False
65
65
66 def has_executablebit():
66 def has_executablebit():
67 try:
67 try:
68 EXECFLAGS = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
68 EXECFLAGS = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
69 fh, fn = tempfile.mkstemp(dir=".", prefix='hg-checkexec-')
69 fh, fn = tempfile.mkstemp(dir=".", prefix='hg-checkexec-')
70 try:
70 try:
71 os.close(fh)
71 os.close(fh)
72 m = os.stat(fn).st_mode & 0777
72 m = os.stat(fn).st_mode & 0777
73 new_file_has_exec = m & EXECFLAGS
73 new_file_has_exec = m & EXECFLAGS
74 os.chmod(fn, m ^ EXECFLAGS)
74 os.chmod(fn, m ^ EXECFLAGS)
75 exec_flags_cannot_flip = ((os.stat(fn).st_mode & 0777) == m)
75 exec_flags_cannot_flip = ((os.stat(fn).st_mode & 0777) == m)
76 finally:
76 finally:
77 os.unlink(fn)
77 os.unlink(fn)
78 except (IOError, OSError):
78 except (IOError, OSError):
79 # we don't care, the user probably won't be able to commit anyway
79 # we don't care, the user probably won't be able to commit anyway
80 return False
80 return False
81 return not (new_file_has_exec or exec_flags_cannot_flip)
81 return not (new_file_has_exec or exec_flags_cannot_flip)
82
82
83 def has_icasefs():
83 def has_icasefs():
84 # Stolen from mercurial.util
84 # Stolen from mercurial.util
85 fd, path = tempfile.mkstemp(prefix=tempprefix, dir='.')
85 fd, path = tempfile.mkstemp(prefix=tempprefix, dir='.')
86 os.close(fd)
86 os.close(fd)
87 try:
87 try:
88 s1 = os.stat(path)
88 s1 = os.stat(path)
89 d, b = os.path.split(path)
89 d, b = os.path.split(path)
90 p2 = os.path.join(d, b.upper())
90 p2 = os.path.join(d, b.upper())
91 if path == p2:
91 if path == p2:
92 p2 = os.path.join(d, b.lower())
92 p2 = os.path.join(d, b.lower())
93 try:
93 try:
94 s2 = os.stat(p2)
94 s2 = os.stat(p2)
95 return s2 == s1
95 return s2 == s1
96 except:
96 except:
97 return False
97 return False
98 finally:
98 finally:
99 os.remove(path)
99 os.remove(path)
100
100
101 def has_inotify():
101 def has_inotify():
102 try:
102 try:
103 import hgext.inotify.linux.watcher
103 import hgext.inotify.linux.watcher
104 return True
104 return True
105 except ImportError:
105 except ImportError:
106 return False
106 return False
107
107
108 def has_fifo():
108 def has_fifo():
109 return hasattr(os, "mkfifo")
109 return hasattr(os, "mkfifo")
110
110
111 def has_cacheable_fs():
111 def has_cacheable_fs():
112 from mercurial import util
112 from mercurial import util
113
113
114 fd, path = tempfile.mkstemp(prefix=tempprefix)
114 fd, path = tempfile.mkstemp(prefix=tempprefix)
115 os.close(fd)
115 os.close(fd)
116 try:
116 try:
117 return util.cachestat(path).cacheable()
117 return util.cachestat(path).cacheable()
118 finally:
118 finally:
119 os.remove(path)
119 os.remove(path)
120
120
121 def has_lsprof():
121 def has_lsprof():
122 try:
122 try:
123 import _lsprof
123 import _lsprof
124 return True
124 return True
125 except ImportError:
125 except ImportError:
126 return False
126 return False
127
127
128 def has_gettext():
128 def has_gettext():
129 return matchoutput('msgfmt --version', 'GNU gettext-tools')
129 return matchoutput('msgfmt --version', 'GNU gettext-tools')
130
130
131 def has_git():
131 def has_git():
132 return matchoutput('git --version 2>&1', r'^git version')
132 return matchoutput('git --version 2>&1', r'^git version')
133
133
134 def has_docutils():
134 def has_docutils():
135 try:
135 try:
136 from docutils.core import publish_cmdline
136 from docutils.core import publish_cmdline
137 return True
137 return True
138 except ImportError:
138 except ImportError:
139 return False
139 return False
140
140
141 def getsvnversion():
141 def getsvnversion():
142 m = matchoutput('svn --version 2>&1', r'^svn,\s+version\s+(\d+)\.(\d+)')
142 m = matchoutput('svn --version 2>&1', r'^svn,\s+version\s+(\d+)\.(\d+)')
143 if not m:
143 if not m:
144 return (0, 0)
144 return (0, 0)
145 return (int(m.group(1)), int(m.group(2)))
145 return (int(m.group(1)), int(m.group(2)))
146
146
147 def has_svn15():
147 def has_svn15():
148 return getsvnversion() >= (1, 5)
148 return getsvnversion() >= (1, 5)
149
149
150 def has_svn13():
150 def has_svn13():
151 return getsvnversion() >= (1, 3)
151 return getsvnversion() >= (1, 3)
152
152
153 def has_svn():
153 def has_svn():
154 return matchoutput('svn --version 2>&1', r'^svn, version') and \
154 return matchoutput('svn --version 2>&1', r'^svn, version') and \
155 matchoutput('svnadmin --version 2>&1', r'^svnadmin, version')
155 matchoutput('svnadmin --version 2>&1', r'^svnadmin, version')
156
156
157 def has_svn_bindings():
157 def has_svn_bindings():
158 try:
158 try:
159 import svn.core
159 import svn.core
160 version = svn.core.SVN_VER_MAJOR, svn.core.SVN_VER_MINOR
160 version = svn.core.SVN_VER_MAJOR, svn.core.SVN_VER_MINOR
161 if version < (1, 4):
161 if version < (1, 4):
162 return False
162 return False
163 return True
163 return True
164 except ImportError:
164 except ImportError:
165 return False
165 return False
166
166
167 def has_p4():
167 def has_p4():
168 return matchoutput('p4 -V', r'Rev\. P4/') and matchoutput('p4d -V', r'Rev\. P4D/')
168 return matchoutput('p4 -V', r'Rev\. P4/') and matchoutput('p4d -V', r'Rev\. P4D/')
169
169
170 def has_symlink():
170 def has_symlink():
171 if not hasattr(os, "symlink"):
171 if not hasattr(os, "symlink"):
172 return False
172 return False
173 name = tempfile.mktemp(dir=".", prefix='hg-checklink-')
173 name = tempfile.mktemp(dir=".", prefix='hg-checklink-')
174 try:
174 try:
175 os.symlink(".", name)
175 os.symlink(".", name)
176 os.unlink(name)
176 os.unlink(name)
177 return True
177 return True
178 except (OSError, AttributeError):
178 except (OSError, AttributeError):
179 return False
179 return False
180 return hasattr(os, "symlink") # FIXME: should also check file system and os
181
180
182 def has_tla():
181 def has_tla():
183 return matchoutput('tla --version 2>&1', r'The GNU Arch Revision')
182 return matchoutput('tla --version 2>&1', r'The GNU Arch Revision')
184
183
185 def has_gpg():
184 def has_gpg():
186 return matchoutput('gpg --version 2>&1', r'GnuPG')
185 return matchoutput('gpg --version 2>&1', r'GnuPG')
187
186
188 def has_unix_permissions():
187 def has_unix_permissions():
189 d = tempfile.mkdtemp(prefix=tempprefix, dir=".")
188 d = tempfile.mkdtemp(prefix=tempprefix, dir=".")
190 try:
189 try:
191 fname = os.path.join(d, 'foo')
190 fname = os.path.join(d, 'foo')
192 for umask in (077, 007, 022):
191 for umask in (077, 007, 022):
193 os.umask(umask)
192 os.umask(umask)
194 f = open(fname, 'w')
193 f = open(fname, 'w')
195 f.close()
194 f.close()
196 mode = os.stat(fname).st_mode
195 mode = os.stat(fname).st_mode
197 os.unlink(fname)
196 os.unlink(fname)
198 if mode & 0777 != ~umask & 0666:
197 if mode & 0777 != ~umask & 0666:
199 return False
198 return False
200 return True
199 return True
201 finally:
200 finally:
202 os.rmdir(d)
201 os.rmdir(d)
203
202
204 def has_pyflakes():
203 def has_pyflakes():
205 return matchoutput('echo "import re" 2>&1 | pyflakes',
204 return matchoutput('echo "import re" 2>&1 | pyflakes',
206 r"<stdin>:1: 're' imported but unused",
205 r"<stdin>:1: 're' imported but unused",
207 True)
206 True)
208
207
209 def has_pygments():
208 def has_pygments():
210 try:
209 try:
211 import pygments
210 import pygments
212 return True
211 return True
213 except ImportError:
212 except ImportError:
214 return False
213 return False
215
214
216 def has_outer_repo():
215 def has_outer_repo():
217 return matchoutput('hg root 2>&1', r'')
216 return matchoutput('hg root 2>&1', r'')
218
217
219 def has_ssl():
218 def has_ssl():
220 try:
219 try:
221 import ssl
220 import ssl
222 import OpenSSL
221 import OpenSSL
223 OpenSSL.SSL.Context
222 OpenSSL.SSL.Context
224 return True
223 return True
225 except ImportError:
224 except ImportError:
226 return False
225 return False
227
226
228 def has_windows():
227 def has_windows():
229 return os.name == 'nt'
228 return os.name == 'nt'
230
229
231 def has_system_sh():
230 def has_system_sh():
232 return os.name != 'nt'
231 return os.name != 'nt'
233
232
234 def has_serve():
233 def has_serve():
235 return os.name != 'nt' # gross approximation
234 return os.name != 'nt' # gross approximation
236
235
237 def has_tic():
236 def has_tic():
238 return matchoutput('test -x "`which tic`"', '')
237 return matchoutput('test -x "`which tic`"', '')
239
238
240 def has_msys():
239 def has_msys():
241 return os.getenv('MSYSTEM')
240 return os.getenv('MSYSTEM')
242
241
243 checks = {
242 checks = {
244 "baz": (has_baz, "GNU Arch baz client"),
243 "baz": (has_baz, "GNU Arch baz client"),
245 "bzr": (has_bzr, "Canonical's Bazaar client"),
244 "bzr": (has_bzr, "Canonical's Bazaar client"),
246 "bzr114": (has_bzr114, "Canonical's Bazaar client >= 1.14"),
245 "bzr114": (has_bzr114, "Canonical's Bazaar client >= 1.14"),
247 "cacheable": (has_cacheable_fs, "cacheable filesystem"),
246 "cacheable": (has_cacheable_fs, "cacheable filesystem"),
248 "cvs": (has_cvs, "cvs client/server"),
247 "cvs": (has_cvs, "cvs client/server"),
249 "darcs": (has_darcs, "darcs client"),
248 "darcs": (has_darcs, "darcs client"),
250 "docutils": (has_docutils, "Docutils text processing library"),
249 "docutils": (has_docutils, "Docutils text processing library"),
251 "eol-in-paths": (has_eol_in_paths, "end-of-lines in paths"),
250 "eol-in-paths": (has_eol_in_paths, "end-of-lines in paths"),
252 "execbit": (has_executablebit, "executable bit"),
251 "execbit": (has_executablebit, "executable bit"),
253 "fifo": (has_fifo, "named pipes"),
252 "fifo": (has_fifo, "named pipes"),
254 "gettext": (has_gettext, "GNU Gettext (msgfmt)"),
253 "gettext": (has_gettext, "GNU Gettext (msgfmt)"),
255 "git": (has_git, "git command line client"),
254 "git": (has_git, "git command line client"),
256 "gpg": (has_gpg, "gpg client"),
255 "gpg": (has_gpg, "gpg client"),
257 "icasefs": (has_icasefs, "case insensitive file system"),
256 "icasefs": (has_icasefs, "case insensitive file system"),
258 "inotify": (has_inotify, "inotify extension support"),
257 "inotify": (has_inotify, "inotify extension support"),
259 "lsprof": (has_lsprof, "python lsprof module"),
258 "lsprof": (has_lsprof, "python lsprof module"),
260 "mtn": (has_mtn, "monotone client (>= 1.0)"),
259 "mtn": (has_mtn, "monotone client (>= 1.0)"),
261 "outer-repo": (has_outer_repo, "outer repo"),
260 "outer-repo": (has_outer_repo, "outer repo"),
262 "p4": (has_p4, "Perforce server and client"),
261 "p4": (has_p4, "Perforce server and client"),
263 "pyflakes": (has_pyflakes, "Pyflakes python linter"),
262 "pyflakes": (has_pyflakes, "Pyflakes python linter"),
264 "pygments": (has_pygments, "Pygments source highlighting library"),
263 "pygments": (has_pygments, "Pygments source highlighting library"),
265 "serve": (has_serve, "platform and python can manage 'hg serve -d'"),
264 "serve": (has_serve, "platform and python can manage 'hg serve -d'"),
266 "ssl": (has_ssl, "python >= 2.6 ssl module and python OpenSSL"),
265 "ssl": (has_ssl, "python >= 2.6 ssl module and python OpenSSL"),
267 "svn": (has_svn, "subversion client and admin tools"),
266 "svn": (has_svn, "subversion client and admin tools"),
268 "svn13": (has_svn13, "subversion client and admin tools >= 1.3"),
267 "svn13": (has_svn13, "subversion client and admin tools >= 1.3"),
269 "svn15": (has_svn15, "subversion client and admin tools >= 1.5"),
268 "svn15": (has_svn15, "subversion client and admin tools >= 1.5"),
270 "svn-bindings": (has_svn_bindings, "subversion python bindings"),
269 "svn-bindings": (has_svn_bindings, "subversion python bindings"),
271 "symlink": (has_symlink, "symbolic links"),
270 "symlink": (has_symlink, "symbolic links"),
272 "system-sh": (has_system_sh, "system() uses sh"),
271 "system-sh": (has_system_sh, "system() uses sh"),
273 "tic": (has_tic, "terminfo compiler"),
272 "tic": (has_tic, "terminfo compiler"),
274 "tla": (has_tla, "GNU Arch tla client"),
273 "tla": (has_tla, "GNU Arch tla client"),
275 "unix-permissions": (has_unix_permissions, "unix-style permissions"),
274 "unix-permissions": (has_unix_permissions, "unix-style permissions"),
276 "windows": (has_windows, "Windows"),
275 "windows": (has_windows, "Windows"),
277 "msys": (has_msys, "Windows with MSYS"),
276 "msys": (has_msys, "Windows with MSYS"),
278 }
277 }
279
278
280 def list_features():
279 def list_features():
281 for name, feature in checks.iteritems():
280 for name, feature in checks.iteritems():
282 desc = feature[1]
281 desc = feature[1]
283 print name + ':', desc
282 print name + ':', desc
284
283
285 def test_features():
284 def test_features():
286 failed = 0
285 failed = 0
287 for name, feature in checks.iteritems():
286 for name, feature in checks.iteritems():
288 check, _ = feature
287 check, _ = feature
289 try:
288 try:
290 check()
289 check()
291 except Exception, e:
290 except Exception, e:
292 print "feature %s failed: %s" % (name, e)
291 print "feature %s failed: %s" % (name, e)
293 failed += 1
292 failed += 1
294 return failed
293 return failed
295
294
296 parser = optparse.OptionParser("%prog [options] [features]")
295 parser = optparse.OptionParser("%prog [options] [features]")
297 parser.add_option("--test-features", action="store_true",
296 parser.add_option("--test-features", action="store_true",
298 help="test available features")
297 help="test available features")
299 parser.add_option("--list-features", action="store_true",
298 parser.add_option("--list-features", action="store_true",
300 help="list available features")
299 help="list available features")
301 parser.add_option("-q", "--quiet", action="store_true",
300 parser.add_option("-q", "--quiet", action="store_true",
302 help="check features silently")
301 help="check features silently")
303
302
304 if __name__ == '__main__':
303 if __name__ == '__main__':
305 options, args = parser.parse_args()
304 options, args = parser.parse_args()
306 if options.list_features:
305 if options.list_features:
307 list_features()
306 list_features()
308 sys.exit(0)
307 sys.exit(0)
309
308
310 if options.test_features:
309 if options.test_features:
311 sys.exit(test_features())
310 sys.exit(test_features())
312
311
313 quiet = options.quiet
312 quiet = options.quiet
314
313
315 failures = 0
314 failures = 0
316
315
317 def error(msg):
316 def error(msg):
318 global failures
317 global failures
319 if not quiet:
318 if not quiet:
320 sys.stderr.write(msg + '\n')
319 sys.stderr.write(msg + '\n')
321 failures += 1
320 failures += 1
322
321
323 for feature in args:
322 for feature in args:
324 negate = feature.startswith('no-')
323 negate = feature.startswith('no-')
325 if negate:
324 if negate:
326 feature = feature[3:]
325 feature = feature[3:]
327
326
328 if feature not in checks:
327 if feature not in checks:
329 error('skipped: unknown feature: ' + feature)
328 error('skipped: unknown feature: ' + feature)
330 continue
329 continue
331
330
332 check, desc = checks[feature]
331 check, desc = checks[feature]
333 try:
332 try:
334 available = check()
333 available = check()
335 except Exception, e:
334 except Exception, e:
336 error('hghave check failed: ' + feature)
335 error('hghave check failed: ' + feature)
337 continue
336 continue
338
337
339 if not negate and not available:
338 if not negate and not available:
340 error('skipped: missing feature: ' + desc)
339 error('skipped: missing feature: ' + desc)
341 elif negate and available:
340 elif negate and available:
342 error('skipped: system supports %s' % desc)
341 error('skipped: system supports %s' % desc)
343
342
344 if failures != 0:
343 if failures != 0:
345 sys.exit(1)
344 sys.exit(1)
@@ -1,349 +1,350 b''
1 $ echo "[extensions]" >> $HGRCPATH
1 $ echo "[extensions]" >> $HGRCPATH
2 $ echo "graphlog=" >> $HGRCPATH
2 $ echo "graphlog=" >> $HGRCPATH
3
3
4 plain
4 plain
5
5
6 $ hg init
6 $ hg init
7 $ hg debugbuilddag '+2:f +3:p2 @temp <f+4 @default /p2 +2' \
7 $ hg debugbuilddag '+2:f +3:p2 @temp <f+4 @default /p2 +2' \
8 > --config extensions.progress= --config progress.assume-tty=1 \
8 > --config extensions.progress= --config progress.assume-tty=1 \
9 > --config progress.delay=0 --config progress.refresh=0 \
9 > --config progress.delay=0 --config progress.refresh=0 \
10 > --config progress.format=topic,bar,number \
10 > --config progress.width=60 2>&1 | \
11 > --config progress.width=60 2>&1 | \
11 > python "$TESTDIR/filtercr.py"
12 > python "$TESTDIR/filtercr.py"
12
13
13 building [ ] 0/12
14 building [ ] 0/12
14 building [ ] 0/12
15 building [ ] 0/12
15 building [ ] 0/12
16 building [ ] 0/12
16 building [ ] 0/12
17 building [ ] 0/12
17 building [==> ] 1/12
18 building [==> ] 1/12
18 building [==> ] 1/12
19 building [==> ] 1/12
19 building [==> ] 1/12
20 building [==> ] 1/12
20 building [==> ] 1/12
21 building [==> ] 1/12
21 building [======> ] 2/12
22 building [======> ] 2/12
22 building [======> ] 2/12
23 building [======> ] 2/12
23 building [=========> ] 3/12
24 building [=========> ] 3/12
24 building [=========> ] 3/12
25 building [=========> ] 3/12
25 building [=============> ] 4/12
26 building [=============> ] 4/12
26 building [=============> ] 4/12
27 building [=============> ] 4/12
27 building [=============> ] 4/12
28 building [=============> ] 4/12
28 building [=============> ] 4/12
29 building [=============> ] 4/12
29 building [=============> ] 4/12
30 building [=============> ] 4/12
30 building [=============> ] 4/12
31 building [=============> ] 4/12
31 building [================> ] 5/12
32 building [================> ] 5/12
32 building [================> ] 5/12
33 building [================> ] 5/12
33 building [====================> ] 6/12
34 building [====================> ] 6/12
34 building [====================> ] 6/12
35 building [====================> ] 6/12
35 building [=======================> ] 7/12
36 building [=======================> ] 7/12
36 building [=======================> ] 7/12
37 building [=======================> ] 7/12
37 building [===========================> ] 8/12
38 building [===========================> ] 8/12
38 building [===========================> ] 8/12
39 building [===========================> ] 8/12
39 building [===========================> ] 8/12
40 building [===========================> ] 8/12
40 building [===========================> ] 8/12
41 building [===========================> ] 8/12
41 building [==============================> ] 9/12
42 building [==============================> ] 9/12
42 building [==============================> ] 9/12
43 building [==============================> ] 9/12
43 building [==================================> ] 10/12
44 building [==================================> ] 10/12
44 building [==================================> ] 10/12
45 building [==================================> ] 10/12
45 building [=====================================> ] 11/12
46 building [=====================================> ] 11/12
46 building [=====================================> ] 11/12
47 building [=====================================> ] 11/12
47 \r (esc)
48 \r (esc)
48
49
49 tags
50 tags
50 $ cat .hg/localtags
51 $ cat .hg/localtags
51 66f7d451a68b85ed82ff5fcc254daf50c74144bd f
52 66f7d451a68b85ed82ff5fcc254daf50c74144bd f
52 bebd167eb94d257ace0e814aeb98e6972ed2970d p2
53 bebd167eb94d257ace0e814aeb98e6972ed2970d p2
53 dag
54 dag
54 $ hg debugdag -t -b
55 $ hg debugdag -t -b
55 +2:f
56 +2:f
56 +3:p2
57 +3:p2
57 @temp*f+3
58 @temp*f+3
58 @default*/p2+2:tip
59 @default*/p2+2:tip
59 tip
60 tip
60 $ hg id
61 $ hg id
61 000000000000
62 000000000000
62 glog
63 glog
63 $ hg glog --template '{rev}: {desc} [{branches}] @ {date}\n'
64 $ hg glog --template '{rev}: {desc} [{branches}] @ {date}\n'
64 o 11: r11 [] @ 11.00
65 o 11: r11 [] @ 11.00
65 |
66 |
66 o 10: r10 [] @ 10.00
67 o 10: r10 [] @ 10.00
67 |
68 |
68 o 9: r9 [] @ 9.00
69 o 9: r9 [] @ 9.00
69 |\
70 |\
70 | o 8: r8 [temp] @ 8.00
71 | o 8: r8 [temp] @ 8.00
71 | |
72 | |
72 | o 7: r7 [temp] @ 7.00
73 | o 7: r7 [temp] @ 7.00
73 | |
74 | |
74 | o 6: r6 [temp] @ 6.00
75 | o 6: r6 [temp] @ 6.00
75 | |
76 | |
76 | o 5: r5 [temp] @ 5.00
77 | o 5: r5 [temp] @ 5.00
77 | |
78 | |
78 o | 4: r4 [] @ 4.00
79 o | 4: r4 [] @ 4.00
79 | |
80 | |
80 o | 3: r3 [] @ 3.00
81 o | 3: r3 [] @ 3.00
81 | |
82 | |
82 o | 2: r2 [] @ 2.00
83 o | 2: r2 [] @ 2.00
83 |/
84 |/
84 o 1: r1 [] @ 1.00
85 o 1: r1 [] @ 1.00
85 |
86 |
86 o 0: r0 [] @ 0.00
87 o 0: r0 [] @ 0.00
87
88
88
89
89 overwritten files, starting on a non-default branch
90 overwritten files, starting on a non-default branch
90
91
91 $ rm -r .hg
92 $ rm -r .hg
92 $ hg init
93 $ hg init
93 $ hg debugbuilddag '@start.@default.:f +3:p2 @temp <f+4 @default /p2 +2' -q -o
94 $ hg debugbuilddag '@start.@default.:f +3:p2 @temp <f+4 @default /p2 +2' -q -o
94 tags
95 tags
95 $ cat .hg/localtags
96 $ cat .hg/localtags
96 f778700ebd50fcf282b23a4446bd155da6453eb6 f
97 f778700ebd50fcf282b23a4446bd155da6453eb6 f
97 bbccf169769006e2490efd2a02f11c3d38d462bd p2
98 bbccf169769006e2490efd2a02f11c3d38d462bd p2
98 dag
99 dag
99 $ hg debugdag -t -b
100 $ hg debugdag -t -b
100 @start+1
101 @start+1
101 @default+1:f
102 @default+1:f
102 +3:p2
103 +3:p2
103 @temp*f+3
104 @temp*f+3
104 @default*/p2+2:tip
105 @default*/p2+2:tip
105 tip
106 tip
106 $ hg id
107 $ hg id
107 000000000000
108 000000000000
108 glog
109 glog
109 $ hg glog --template '{rev}: {desc} [{branches}] @ {date}\n'
110 $ hg glog --template '{rev}: {desc} [{branches}] @ {date}\n'
110 o 11: r11 [] @ 11.00
111 o 11: r11 [] @ 11.00
111 |
112 |
112 o 10: r10 [] @ 10.00
113 o 10: r10 [] @ 10.00
113 |
114 |
114 o 9: r9 [] @ 9.00
115 o 9: r9 [] @ 9.00
115 |\
116 |\
116 | o 8: r8 [temp] @ 8.00
117 | o 8: r8 [temp] @ 8.00
117 | |
118 | |
118 | o 7: r7 [temp] @ 7.00
119 | o 7: r7 [temp] @ 7.00
119 | |
120 | |
120 | o 6: r6 [temp] @ 6.00
121 | o 6: r6 [temp] @ 6.00
121 | |
122 | |
122 | o 5: r5 [temp] @ 5.00
123 | o 5: r5 [temp] @ 5.00
123 | |
124 | |
124 o | 4: r4 [] @ 4.00
125 o | 4: r4 [] @ 4.00
125 | |
126 | |
126 o | 3: r3 [] @ 3.00
127 o | 3: r3 [] @ 3.00
127 | |
128 | |
128 o | 2: r2 [] @ 2.00
129 o | 2: r2 [] @ 2.00
129 |/
130 |/
130 o 1: r1 [] @ 1.00
131 o 1: r1 [] @ 1.00
131 |
132 |
132 o 0: r0 [start] @ 0.00
133 o 0: r0 [start] @ 0.00
133
134
134 glog of
135 glog of
135 $ hg glog --template '{rev}: {desc} [{branches}]\n' of
136 $ hg glog --template '{rev}: {desc} [{branches}]\n' of
136 o 11: r11 []
137 o 11: r11 []
137 |
138 |
138 o 10: r10 []
139 o 10: r10 []
139 |
140 |
140 o 9: r9 []
141 o 9: r9 []
141 |\
142 |\
142 | o 8: r8 [temp]
143 | o 8: r8 [temp]
143 | |
144 | |
144 | o 7: r7 [temp]
145 | o 7: r7 [temp]
145 | |
146 | |
146 | o 6: r6 [temp]
147 | o 6: r6 [temp]
147 | |
148 | |
148 | o 5: r5 [temp]
149 | o 5: r5 [temp]
149 | |
150 | |
150 o | 4: r4 []
151 o | 4: r4 []
151 | |
152 | |
152 o | 3: r3 []
153 o | 3: r3 []
153 | |
154 | |
154 o | 2: r2 []
155 o | 2: r2 []
155 |/
156 |/
156 o 1: r1 []
157 o 1: r1 []
157 |
158 |
158 o 0: r0 [start]
159 o 0: r0 [start]
159
160
160 tags
161 tags
161 $ hg tags -v
162 $ hg tags -v
162 tip 11:9ffe238a67a2
163 tip 11:9ffe238a67a2
163 p2 4:bbccf1697690 local
164 p2 4:bbccf1697690 local
164 f 1:f778700ebd50 local
165 f 1:f778700ebd50 local
165 cat of
166 cat of
166 $ hg cat of --rev tip
167 $ hg cat of --rev tip
167 r11
168 r11
168
169
169
170
170 new and mergeable files
171 new and mergeable files
171
172
172 $ rm -r .hg
173 $ rm -r .hg
173 $ hg init
174 $ hg init
174 $ hg debugbuilddag '+2:f +3:p2 @temp <f+4 @default /p2 +2' -q -mn
175 $ hg debugbuilddag '+2:f +3:p2 @temp <f+4 @default /p2 +2' -q -mn
175 dag
176 dag
176 $ hg debugdag -t -b
177 $ hg debugdag -t -b
177 +2:f
178 +2:f
178 +3:p2
179 +3:p2
179 @temp*f+3
180 @temp*f+3
180 @default*/p2+2:tip
181 @default*/p2+2:tip
181 tip
182 tip
182 $ hg id
183 $ hg id
183 000000000000
184 000000000000
184 glog
185 glog
185 $ hg glog --template '{rev}: {desc} [{branches}] @ {date}\n'
186 $ hg glog --template '{rev}: {desc} [{branches}] @ {date}\n'
186 o 11: r11 [] @ 11.00
187 o 11: r11 [] @ 11.00
187 |
188 |
188 o 10: r10 [] @ 10.00
189 o 10: r10 [] @ 10.00
189 |
190 |
190 o 9: r9 [] @ 9.00
191 o 9: r9 [] @ 9.00
191 |\
192 |\
192 | o 8: r8 [temp] @ 8.00
193 | o 8: r8 [temp] @ 8.00
193 | |
194 | |
194 | o 7: r7 [temp] @ 7.00
195 | o 7: r7 [temp] @ 7.00
195 | |
196 | |
196 | o 6: r6 [temp] @ 6.00
197 | o 6: r6 [temp] @ 6.00
197 | |
198 | |
198 | o 5: r5 [temp] @ 5.00
199 | o 5: r5 [temp] @ 5.00
199 | |
200 | |
200 o | 4: r4 [] @ 4.00
201 o | 4: r4 [] @ 4.00
201 | |
202 | |
202 o | 3: r3 [] @ 3.00
203 o | 3: r3 [] @ 3.00
203 | |
204 | |
204 o | 2: r2 [] @ 2.00
205 o | 2: r2 [] @ 2.00
205 |/
206 |/
206 o 1: r1 [] @ 1.00
207 o 1: r1 [] @ 1.00
207 |
208 |
208 o 0: r0 [] @ 0.00
209 o 0: r0 [] @ 0.00
209
210
210 glog mf
211 glog mf
211 $ hg glog --template '{rev}: {desc} [{branches}]\n' mf
212 $ hg glog --template '{rev}: {desc} [{branches}]\n' mf
212 o 11: r11 []
213 o 11: r11 []
213 |
214 |
214 o 10: r10 []
215 o 10: r10 []
215 |
216 |
216 o 9: r9 []
217 o 9: r9 []
217 |\
218 |\
218 | o 8: r8 [temp]
219 | o 8: r8 [temp]
219 | |
220 | |
220 | o 7: r7 [temp]
221 | o 7: r7 [temp]
221 | |
222 | |
222 | o 6: r6 [temp]
223 | o 6: r6 [temp]
223 | |
224 | |
224 | o 5: r5 [temp]
225 | o 5: r5 [temp]
225 | |
226 | |
226 o | 4: r4 []
227 o | 4: r4 []
227 | |
228 | |
228 o | 3: r3 []
229 o | 3: r3 []
229 | |
230 | |
230 o | 2: r2 []
231 o | 2: r2 []
231 |/
232 |/
232 o 1: r1 []
233 o 1: r1 []
233 |
234 |
234 o 0: r0 []
235 o 0: r0 []
235
236
236
237
237 man r4
238 man r4
238 $ hg manifest -r4
239 $ hg manifest -r4
239 mf
240 mf
240 nf0
241 nf0
241 nf1
242 nf1
242 nf2
243 nf2
243 nf3
244 nf3
244 nf4
245 nf4
245 cat r4 mf
246 cat r4 mf
246 $ hg cat -r4 mf
247 $ hg cat -r4 mf
247 0 r0
248 0 r0
248 1
249 1
249 2 r1
250 2 r1
250 3
251 3
251 4 r2
252 4 r2
252 5
253 5
253 6 r3
254 6 r3
254 7
255 7
255 8 r4
256 8 r4
256 9
257 9
257 10
258 10
258 11
259 11
259 12
260 12
260 13
261 13
261 14
262 14
262 15
263 15
263 16
264 16
264 17
265 17
265 18
266 18
266 19
267 19
267 20
268 20
268 21
269 21
269 22
270 22
270 23
271 23
271 man r8
272 man r8
272 $ hg manifest -r8
273 $ hg manifest -r8
273 mf
274 mf
274 nf0
275 nf0
275 nf1
276 nf1
276 nf5
277 nf5
277 nf6
278 nf6
278 nf7
279 nf7
279 nf8
280 nf8
280 cat r8 mf
281 cat r8 mf
281 $ hg cat -r8 mf
282 $ hg cat -r8 mf
282 0 r0
283 0 r0
283 1
284 1
284 2 r1
285 2 r1
285 3
286 3
286 4
287 4
287 5
288 5
288 6
289 6
289 7
290 7
290 8
291 8
291 9
292 9
292 10 r5
293 10 r5
293 11
294 11
294 12 r6
295 12 r6
295 13
296 13
296 14 r7
297 14 r7
297 15
298 15
298 16 r8
299 16 r8
299 17
300 17
300 18
301 18
301 19
302 19
302 20
303 20
303 21
304 21
304 22
305 22
305 23
306 23
306 man
307 man
307 $ hg manifest --rev tip
308 $ hg manifest --rev tip
308 mf
309 mf
309 nf0
310 nf0
310 nf1
311 nf1
311 nf10
312 nf10
312 nf11
313 nf11
313 nf2
314 nf2
314 nf3
315 nf3
315 nf4
316 nf4
316 nf5
317 nf5
317 nf6
318 nf6
318 nf7
319 nf7
319 nf8
320 nf8
320 nf9
321 nf9
321 cat mf
322 cat mf
322 $ hg cat mf --rev tip
323 $ hg cat mf --rev tip
323 0 r0
324 0 r0
324 1
325 1
325 2 r1
326 2 r1
326 3
327 3
327 4 r2
328 4 r2
328 5
329 5
329 6 r3
330 6 r3
330 7
331 7
331 8 r4
332 8 r4
332 9
333 9
333 10 r5
334 10 r5
334 11
335 11
335 12 r6
336 12 r6
336 13
337 13
337 14 r7
338 14 r7
338 15
339 15
339 16 r8
340 16 r8
340 17
341 17
341 18 r9
342 18 r9
342 19
343 19
343 20 r10
344 20 r10
344 21
345 21
345 22 r11
346 22 r11
346 23
347 23
347
348
348
349
349
350
@@ -1,142 +1,193 b''
1 $ hg init repo
1 $ hg init repo
2 $ cd repo
2 $ cd repo
3 $ cat > a <<EOF
3 $ cat > a <<EOF
4 > c
4 > c
5 > c
5 > c
6 > a
6 > a
7 > a
7 > a
8 > b
8 > b
9 > a
9 > a
10 > a
10 > a
11 > c
11 > c
12 > c
12 > c
13 > EOF
13 > EOF
14 $ hg ci -Am adda
14 $ hg ci -Am adda
15 adding a
15 adding a
16
16
17 $ cat > a <<EOF
17 $ cat > a <<EOF
18 > c
18 > c
19 > c
19 > c
20 > a
20 > a
21 > a
21 > a
22 > dd
22 > dd
23 > a
23 > a
24 > a
24 > a
25 > c
25 > c
26 > c
26 > c
27 > EOF
27 > EOF
28
28
29 default context
29 default context
30
30
31 $ hg diff --nodates
31 $ hg diff --nodates
32 diff -r cf9f4ba66af2 a
32 diff -r cf9f4ba66af2 a
33 --- a/a
33 --- a/a
34 +++ b/a
34 +++ b/a
35 @@ -2,7 +2,7 @@
35 @@ -2,7 +2,7 @@
36 c
36 c
37 a
37 a
38 a
38 a
39 -b
39 -b
40 +dd
40 +dd
41 a
41 a
42 a
42 a
43 c
43 c
44
44
45 invalid --unified
45 invalid --unified
46
46
47 $ hg diff --nodates -U foo
47 $ hg diff --nodates -U foo
48 abort: diff context lines count must be an integer, not 'foo'
48 abort: diff context lines count must be an integer, not 'foo'
49 [255]
49 [255]
50
50
51
51
52 $ hg diff --nodates -U 2
52 $ hg diff --nodates -U 2
53 diff -r cf9f4ba66af2 a
53 diff -r cf9f4ba66af2 a
54 --- a/a
54 --- a/a
55 +++ b/a
55 +++ b/a
56 @@ -3,5 +3,5 @@
56 @@ -3,5 +3,5 @@
57 a
57 a
58 a
58 a
59 -b
59 -b
60 +dd
60 +dd
61 a
61 a
62 a
62 a
63
63
64 $ hg --config diff.unified=2 diff --nodates
64 $ hg --config diff.unified=2 diff --nodates
65 diff -r cf9f4ba66af2 a
65 diff -r cf9f4ba66af2 a
66 --- a/a
66 --- a/a
67 +++ b/a
67 +++ b/a
68 @@ -3,5 +3,5 @@
68 @@ -3,5 +3,5 @@
69 a
69 a
70 a
70 a
71 -b
71 -b
72 +dd
72 +dd
73 a
73 a
74 a
74 a
75
75
76 $ hg diff --nodates -U 1
76 $ hg diff --nodates -U 1
77 diff -r cf9f4ba66af2 a
77 diff -r cf9f4ba66af2 a
78 --- a/a
78 --- a/a
79 +++ b/a
79 +++ b/a
80 @@ -4,3 +4,3 @@
80 @@ -4,3 +4,3 @@
81 a
81 a
82 -b
82 -b
83 +dd
83 +dd
84 a
84 a
85
85
86 invalid diff.unified
86 invalid diff.unified
87
87
88 $ hg --config diff.unified=foo diff --nodates
88 $ hg --config diff.unified=foo diff --nodates
89 abort: diff context lines count must be an integer, not 'foo'
89 abort: diff context lines count must be an integer, not 'foo'
90 [255]
90 [255]
91
91
92 0 lines of context hunk header matches gnu diff hunk header
92 0 lines of context hunk header matches gnu diff hunk header
93
93
94 $ hg init diffzero
94 $ hg init diffzero
95 $ cd diffzero
95 $ cd diffzero
96 $ cat > f1 << EOF
96 $ cat > f1 << EOF
97 > c2
97 > c2
98 > c4
98 > c4
99 > c5
99 > c5
100 > EOF
100 > EOF
101 $ hg commit -Am0
101 $ hg commit -Am0
102 adding f1
102 adding f1
103
103
104 $ cat > f2 << EOF
104 $ cat > f2 << EOF
105 > c1
105 > c1
106 > c2
106 > c2
107 > c3
107 > c3
108 > c4
108 > c4
109 > EOF
109 > EOF
110 $ mv f2 f1
110 $ mv f2 f1
111 $ hg diff -U0 --nodates
111 $ hg diff -U0 --nodates
112 diff -r 55d8ff78db23 f1
112 diff -r 55d8ff78db23 f1
113 --- a/f1
113 --- a/f1
114 +++ b/f1
114 +++ b/f1
115 @@ -0,0 +1,1 @@
115 @@ -0,0 +1,1 @@
116 +c1
116 +c1
117 @@ -1,0 +3,1 @@
117 @@ -1,0 +3,1 @@
118 +c3
118 +c3
119 @@ -3,1 +4,0 @@
119 @@ -3,1 +4,0 @@
120 -c5
120 -c5
121
121
122 $ hg diff -U0 --nodates --git
122 $ hg diff -U0 --nodates --git
123 diff --git a/f1 b/f1
123 diff --git a/f1 b/f1
124 --- a/f1
124 --- a/f1
125 +++ b/f1
125 +++ b/f1
126 @@ -0,0 +1,1 @@
126 @@ -0,0 +1,1 @@
127 +c1
127 +c1
128 @@ -1,0 +3,1 @@
128 @@ -1,0 +3,1 @@
129 +c3
129 +c3
130 @@ -3,1 +4,0 @@
130 @@ -3,1 +4,0 @@
131 -c5
131 -c5
132
132
133 $ hg diff -U0 --nodates -p
133 $ hg diff -U0 --nodates -p
134 diff -r 55d8ff78db23 f1
134 diff -r 55d8ff78db23 f1
135 --- a/f1
135 --- a/f1
136 +++ b/f1
136 +++ b/f1
137 @@ -0,0 +1,1 @@
137 @@ -0,0 +1,1 @@
138 +c1
138 +c1
139 @@ -1,0 +3,1 @@ c2
139 @@ -1,0 +3,1 @@ c2
140 +c3
140 +c3
141 @@ -3,1 +4,0 @@ c4
141 @@ -3,1 +4,0 @@ c4
142 -c5
142 -c5
143
144 $ echo a > f1
145 $ hg ci -m movef2
146
147 Test diff headers terminating with TAB when necessary (issue3357)
148 Regular diff --nodates, file creation
149
150 $ hg mv f1 'f 1'
151 $ echo b > 'f 1'
152 $ hg diff --nodates 'f 1'
153 diff -r 7574207d0d15 f 1
154 --- /dev/null
155 +++ b/f 1
156 @@ -0,0 +1,1 @@
157 +b
158
159 Git diff, adding space
160
161 $ hg diff --git
162 diff --git a/f1 b/f 1
163 rename from f1
164 rename to f 1
165 --- a/f1
166 +++ b/f 1
167 @@ -1,1 +1,1 @@
168 -a
169 +b
170
171 Regular diff --nodates, file deletion
172
173 $ hg ci -m addspace
174 $ hg mv 'f 1' f1
175 $ echo a > f1
176 $ hg diff --nodates 'f 1'
177 diff -r ca50fe67c9c7 f 1
178 --- a/f 1
179 +++ /dev/null
180 @@ -1,1 +0,0 @@
181 -b
182
183 Git diff, removing space
184
185 $ hg diff --git
186 diff --git a/f 1 b/f1
187 rename from f 1
188 rename to f1
189 --- a/f 1
190 +++ b/f1
191 @@ -1,1 +1,1 @@
192 -b
193 +a
@@ -1,131 +1,145 b''
1 $ hg init repo
1 $ hg init repo
2 $ cd repo
2 $ cd repo
3 $ touch foo
3 $ touch foo
4 $ hg add foo
4 $ hg add foo
5 $ for i in 0 1 2 3 4 5 6 7 8 9 10 11; do
5 $ for i in 0 1 2 3 4 5 6 7 8 9 10 11; do
6 > echo "foo-$i" >> foo
6 > echo "foo-$i" >> foo
7 > hg ci -m "foo-$i"
7 > hg ci -m "foo-$i"
8 > done
8 > done
9
9
10 $ for out in "%nof%N" "%%%H" "%b-%R" "%h" "%r" "%m"; do
10 $ for out in "%nof%N" "%%%H" "%b-%R" "%h" "%r" "%m"; do
11 > echo
11 > echo
12 > echo "# foo-$out.patch"
12 > echo "# foo-$out.patch"
13 > hg export -v -o "foo-$out.patch" 2:tip
13 > hg export -v -o "foo-$out.patch" 2:tip
14 > done
14 > done
15
15
16 # foo-%nof%N.patch
16 # foo-%nof%N.patch
17 exporting patches:
17 exporting patches:
18 foo-01of10.patch
18 foo-01of10.patch
19 foo-02of10.patch
19 foo-02of10.patch
20 foo-03of10.patch
20 foo-03of10.patch
21 foo-04of10.patch
21 foo-04of10.patch
22 foo-05of10.patch
22 foo-05of10.patch
23 foo-06of10.patch
23 foo-06of10.patch
24 foo-07of10.patch
24 foo-07of10.patch
25 foo-08of10.patch
25 foo-08of10.patch
26 foo-09of10.patch
26 foo-09of10.patch
27 foo-10of10.patch
27 foo-10of10.patch
28
28
29 # foo-%%%H.patch
29 # foo-%%%H.patch
30 exporting patches:
30 exporting patches:
31 foo-%617188a1c80f869a7b66c85134da88a6fb145f67.patch
31 foo-%617188a1c80f869a7b66c85134da88a6fb145f67.patch
32 foo-%dd41a5ff707a5225204105611ba49cc5c229d55f.patch
32 foo-%dd41a5ff707a5225204105611ba49cc5c229d55f.patch
33 foo-%f95a5410f8664b6e1490a4af654e4b7d41a7b321.patch
33 foo-%f95a5410f8664b6e1490a4af654e4b7d41a7b321.patch
34 foo-%4346bcfde53b4d9042489078bcfa9c3e28201db2.patch
34 foo-%4346bcfde53b4d9042489078bcfa9c3e28201db2.patch
35 foo-%afda8c3a009cc99449a05ad8aa4655648c4ecd34.patch
35 foo-%afda8c3a009cc99449a05ad8aa4655648c4ecd34.patch
36 foo-%35284ce2b6b99c9d2ac66268fe99e68e1974e1aa.patch
36 foo-%35284ce2b6b99c9d2ac66268fe99e68e1974e1aa.patch
37 foo-%9688c41894e6931305fa7165a37f6568050b4e9b.patch
37 foo-%9688c41894e6931305fa7165a37f6568050b4e9b.patch
38 foo-%747d3c68f8ec44bb35816bfcd59aeb50b9654c2f.patch
38 foo-%747d3c68f8ec44bb35816bfcd59aeb50b9654c2f.patch
39 foo-%5f17a83f5fbd9414006a5e563eab4c8a00729efd.patch
39 foo-%5f17a83f5fbd9414006a5e563eab4c8a00729efd.patch
40 foo-%f3acbafac161ec68f1598af38f794f28847ca5d3.patch
40 foo-%f3acbafac161ec68f1598af38f794f28847ca5d3.patch
41
41
42 # foo-%b-%R.patch
42 # foo-%b-%R.patch
43 exporting patches:
43 exporting patches:
44 foo-repo-2.patch
44 foo-repo-2.patch
45 foo-repo-3.patch
45 foo-repo-3.patch
46 foo-repo-4.patch
46 foo-repo-4.patch
47 foo-repo-5.patch
47 foo-repo-5.patch
48 foo-repo-6.patch
48 foo-repo-6.patch
49 foo-repo-7.patch
49 foo-repo-7.patch
50 foo-repo-8.patch
50 foo-repo-8.patch
51 foo-repo-9.patch
51 foo-repo-9.patch
52 foo-repo-10.patch
52 foo-repo-10.patch
53 foo-repo-11.patch
53 foo-repo-11.patch
54
54
55 # foo-%h.patch
55 # foo-%h.patch
56 exporting patches:
56 exporting patches:
57 foo-617188a1c80f.patch
57 foo-617188a1c80f.patch
58 foo-dd41a5ff707a.patch
58 foo-dd41a5ff707a.patch
59 foo-f95a5410f866.patch
59 foo-f95a5410f866.patch
60 foo-4346bcfde53b.patch
60 foo-4346bcfde53b.patch
61 foo-afda8c3a009c.patch
61 foo-afda8c3a009c.patch
62 foo-35284ce2b6b9.patch
62 foo-35284ce2b6b9.patch
63 foo-9688c41894e6.patch
63 foo-9688c41894e6.patch
64 foo-747d3c68f8ec.patch
64 foo-747d3c68f8ec.patch
65 foo-5f17a83f5fbd.patch
65 foo-5f17a83f5fbd.patch
66 foo-f3acbafac161.patch
66 foo-f3acbafac161.patch
67
67
68 # foo-%r.patch
68 # foo-%r.patch
69 exporting patches:
69 exporting patches:
70 foo-02.patch
70 foo-02.patch
71 foo-03.patch
71 foo-03.patch
72 foo-04.patch
72 foo-04.patch
73 foo-05.patch
73 foo-05.patch
74 foo-06.patch
74 foo-06.patch
75 foo-07.patch
75 foo-07.patch
76 foo-08.patch
76 foo-08.patch
77 foo-09.patch
77 foo-09.patch
78 foo-10.patch
78 foo-10.patch
79 foo-11.patch
79 foo-11.patch
80
80
81 # foo-%m.patch
81 # foo-%m.patch
82 exporting patches:
82 exporting patches:
83 foo-foo_2.patch
83 foo-foo_2.patch
84 foo-foo_3.patch
84 foo-foo_3.patch
85 foo-foo_4.patch
85 foo-foo_4.patch
86 foo-foo_5.patch
86 foo-foo_5.patch
87 foo-foo_6.patch
87 foo-foo_6.patch
88 foo-foo_7.patch
88 foo-foo_7.patch
89 foo-foo_8.patch
89 foo-foo_8.patch
90 foo-foo_9.patch
90 foo-foo_9.patch
91 foo-foo_10.patch
91 foo-foo_10.patch
92 foo-foo_11.patch
92 foo-foo_11.patch
93
93
94 Exporting 4 changesets to a file:
94 Exporting 4 changesets to a file:
95
95
96 $ hg export -o export_internal 1 2 3 4
96 $ hg export -o export_internal 1 2 3 4
97 $ grep HG export_internal | wc -l
97 $ grep HG export_internal | wc -l
98 \s*4 (re)
98 \s*4 (re)
99
99
100 Exporting 4 changesets to a file:
100 Exporting 4 changesets to a file:
101
101
102 $ hg export 1 2 3 4 | grep HG | wc -l
102 $ hg export 1 2 3 4 | grep HG | wc -l
103 \s*4 (re)
103 \s*4 (re)
104
104
105 Exporting revision -2 to a file:
105 Exporting revision -2 to a file:
106
106
107 $ hg export -- -2
107 $ hg export -- -2
108 # HG changeset patch
108 # HG changeset patch
109 # User test
109 # User test
110 # Date 0 0
110 # Date 0 0
111 # Node ID 5f17a83f5fbd9414006a5e563eab4c8a00729efd
111 # Node ID 5f17a83f5fbd9414006a5e563eab4c8a00729efd
112 # Parent 747d3c68f8ec44bb35816bfcd59aeb50b9654c2f
112 # Parent 747d3c68f8ec44bb35816bfcd59aeb50b9654c2f
113 foo-10
113 foo-10
114
114
115 diff -r 747d3c68f8ec -r 5f17a83f5fbd foo
115 diff -r 747d3c68f8ec -r 5f17a83f5fbd foo
116 --- a/foo Thu Jan 01 00:00:00 1970 +0000
116 --- a/foo Thu Jan 01 00:00:00 1970 +0000
117 +++ b/foo Thu Jan 01 00:00:00 1970 +0000
117 +++ b/foo Thu Jan 01 00:00:00 1970 +0000
118 @@ -8,3 +8,4 @@
118 @@ -8,3 +8,4 @@
119 foo-7
119 foo-7
120 foo-8
120 foo-8
121 foo-9
121 foo-9
122 +foo-10
122 +foo-10
123
123
124 Checking if only alphanumeric characters are used in the file name (%m option):
124 Checking if only alphanumeric characters are used in the file name (%m option):
125
125
126 $ echo "line" >> foo
126 $ echo "line" >> foo
127 $ hg commit -m " !\"#$%&(,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~"
127 $ hg commit -m " !\"#$%&(,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~"
128 $ hg export -v -o %m.patch tip
128 $ hg export -v -o %m.patch tip
129 exporting patch:
129 exporting patch:
130 ____________0123456789_______ABCDEFGHIJKLMNOPQRSTUVWXYZ______abcdefghijklmnopqrstuvwxyz____.patch
130 ____________0123456789_______ABCDEFGHIJKLMNOPQRSTUVWXYZ______abcdefghijklmnopqrstuvwxyz____.patch
131
131
132 Catch exporting unknown revisions (especially empty revsets, see issue3353)
133
134 $ hg export
135 abort: export requires at least one changeset
136 [255]
137 $ hg export ""
138 hg: parse error: empty query
139 [255]
140 $ hg export 999
141 abort: unknown revision '999'!
142 [255]
143 $ hg export "not all()"
144 abort: export requires at least one changeset
145 [255]
@@ -1,28 +1,28 b''
1 Test hangup signal in the middle of transaction
1 Test hangup signal in the middle of transaction
2
2
3 $ "$TESTDIR/hghave" serve fifo || exit 80
3 $ "$TESTDIR/hghave" serve fifo || exit 80
4 $ hg init
4 $ hg init
5 $ mkfifo p
5 $ mkfifo p
6 $ hg serve --stdio < p 1>out 2>&1 &
6 $ hg serve --stdio < p 1>out 2>&1 &
7 $ P=$!
7 $ P=$!
8
8
9 Do test while holding fifo open
9 Do test while holding fifo open
10
10
11 $ (
11 $ (
12 > echo lock
12 > echo lock
13 > echo addchangegroup
13 > echo addchangegroup
14 > while [ ! -s .hg/store/journal ]; do true; done
14 > while [ ! -s .hg/store/journal ]; do sleep 0; done
15 > kill -HUP $P
15 > kill -HUP $P
16 > ) > p
16 > ) > p
17
17
18 $ wait
18 $ wait
19 $ cat out
19 $ cat out
20 0
20 0
21 0
21 0
22 adding changesets
22 adding changesets
23 transaction abort!
23 transaction abort!
24 rollback completed
24 rollback completed
25 killed!
25 killed!
26
26
27 $ echo .hg/* .hg/store/*
27 $ echo .hg/* .hg/store/*
28 .hg/00changelog.i .hg/journal.bookmarks .hg/journal.branch .hg/journal.desc .hg/journal.dirstate .hg/requires .hg/store .hg/store/00changelog.i .hg/store/00changelog.i.a .hg/store/journal.phaseroots
28 .hg/00changelog.i .hg/journal.bookmarks .hg/journal.branch .hg/journal.desc .hg/journal.dirstate .hg/requires .hg/store .hg/store/00changelog.i .hg/store/00changelog.i.a .hg/store/journal.phaseroots
@@ -1,264 +1,272 b''
1 $ "$TESTDIR/hghave" serve || exit 80
1 $ "$TESTDIR/hghave" serve || exit 80
2
2
3 $ cat > writelines.py <<EOF
3 $ cat > writelines.py <<EOF
4 > import sys
4 > import sys
5 > path = sys.argv[1]
5 > path = sys.argv[1]
6 > args = sys.argv[2:]
6 > args = sys.argv[2:]
7 > assert (len(args) % 2) == 0
7 > assert (len(args) % 2) == 0
8 >
8 >
9 > f = file(path, 'wb')
9 > f = file(path, 'wb')
10 > for i in xrange(len(args)/2):
10 > for i in xrange(len(args)/2):
11 > count, s = args[2*i:2*i+2]
11 > count, s = args[2*i:2*i+2]
12 > count = int(count)
12 > count = int(count)
13 > s = s.decode('string_escape')
13 > s = s.decode('string_escape')
14 > f.write(s*count)
14 > f.write(s*count)
15 > f.close()
15 > f.close()
16 >
16 >
17 > EOF
17 > EOF
18 $ echo "[extensions]" >> $HGRCPATH
18 $ echo "[extensions]" >> $HGRCPATH
19 $ echo "mq=" >> $HGRCPATH
19 $ echo "mq=" >> $HGRCPATH
20 $ echo "[diff]" >> $HGRCPATH
20 $ echo "[diff]" >> $HGRCPATH
21 $ echo "git=1" >> $HGRCPATH
21 $ echo "git=1" >> $HGRCPATH
22 $ hg init repo
22 $ hg init repo
23 $ cd repo
23 $ cd repo
24
24
25 qimport non-existing-file
25 qimport non-existing-file
26
26
27 $ hg qimport non-existing-file
27 $ hg qimport non-existing-file
28 abort: unable to read file non-existing-file
28 abort: unable to read file non-existing-file
29 [255]
29 [255]
30
30
31 qimport null revision
32
33 $ hg qimport -r null
34 abort: revision -1 is not mutable
35 (see "hg help phases" for details)
36 [255]
37 $ hg qseries
38
31 import email
39 import email
32
40
33 $ hg qimport --push -n email - <<EOF
41 $ hg qimport --push -n email - <<EOF
34 > From: Username in email <test@example.net>
42 > From: Username in email <test@example.net>
35 > Subject: [PATCH] Message in email
43 > Subject: [PATCH] Message in email
36 > Date: Fri, 02 Jan 1970 00:00:00 +0000
44 > Date: Fri, 02 Jan 1970 00:00:00 +0000
37 >
45 >
38 > Text before patch.
46 > Text before patch.
39 >
47 >
40 > # HG changeset patch
48 > # HG changeset patch
41 > # User Username in patch <test@example.net>
49 > # User Username in patch <test@example.net>
42 > # Date 0 0
50 > # Date 0 0
43 > # Node ID 1a706973a7d84cb549823634a821d9bdf21c6220
51 > # Node ID 1a706973a7d84cb549823634a821d9bdf21c6220
44 > # Parent 0000000000000000000000000000000000000000
52 > # Parent 0000000000000000000000000000000000000000
45 > First line of commit message.
53 > First line of commit message.
46 >
54 >
47 > More text in commit message.
55 > More text in commit message.
48 > --- confuse the diff detection
56 > --- confuse the diff detection
49 >
57 >
50 > diff --git a/x b/x
58 > diff --git a/x b/x
51 > new file mode 100644
59 > new file mode 100644
52 > --- /dev/null
60 > --- /dev/null
53 > +++ b/x
61 > +++ b/x
54 > @@ -0,0 +1,1 @@
62 > @@ -0,0 +1,1 @@
55 > +new file
63 > +new file
56 > Text after patch.
64 > Text after patch.
57 >
65 >
58 > EOF
66 > EOF
59 adding email to series file
67 adding email to series file
60 applying email
68 applying email
61 now at: email
69 now at: email
62
70
63 hg tip -v
71 hg tip -v
64
72
65 $ hg tip -v
73 $ hg tip -v
66 changeset: 0:1a706973a7d8
74 changeset: 0:1a706973a7d8
67 tag: email
75 tag: email
68 tag: qbase
76 tag: qbase
69 tag: qtip
77 tag: qtip
70 tag: tip
78 tag: tip
71 user: Username in patch <test@example.net>
79 user: Username in patch <test@example.net>
72 date: Thu Jan 01 00:00:00 1970 +0000
80 date: Thu Jan 01 00:00:00 1970 +0000
73 files: x
81 files: x
74 description:
82 description:
75 First line of commit message.
83 First line of commit message.
76
84
77 More text in commit message.
85 More text in commit message.
78
86
79
87
80 $ hg qpop
88 $ hg qpop
81 popping email
89 popping email
82 patch queue now empty
90 patch queue now empty
83 $ hg qdelete email
91 $ hg qdelete email
84
92
85 import URL
93 import URL
86
94
87 $ echo foo >> foo
95 $ echo foo >> foo
88 $ hg add foo
96 $ hg add foo
89 $ hg diff > url.diff
97 $ hg diff > url.diff
90 $ hg revert --no-backup foo
98 $ hg revert --no-backup foo
91 $ rm foo
99 $ rm foo
92
100
93 Under unix: file:///foobar/blah
101 Under unix: file:///foobar/blah
94 Under windows: file:///c:/foobar/blah
102 Under windows: file:///c:/foobar/blah
95
103
96 $ patchurl=`pwd | tr '\\\\' /`/url.diff
104 $ patchurl=`pwd | tr '\\\\' /`/url.diff
97 $ expr "$patchurl" : "\/" > /dev/null || patchurl="/$patchurl"
105 $ expr "$patchurl" : "\/" > /dev/null || patchurl="/$patchurl"
98 $ hg qimport file://"$patchurl"
106 $ hg qimport file://"$patchurl"
99 adding url.diff to series file
107 adding url.diff to series file
100 $ rm url.diff
108 $ rm url.diff
101 $ hg qun
109 $ hg qun
102 url.diff
110 url.diff
103
111
104 import patch that already exists
112 import patch that already exists
105
113
106 $ echo foo2 >> foo
114 $ echo foo2 >> foo
107 $ hg add foo
115 $ hg add foo
108 $ hg diff > ../url.diff
116 $ hg diff > ../url.diff
109 $ hg revert --no-backup foo
117 $ hg revert --no-backup foo
110 $ rm foo
118 $ rm foo
111 $ hg qimport ../url.diff
119 $ hg qimport ../url.diff
112 abort: patch "url.diff" already exists
120 abort: patch "url.diff" already exists
113 [255]
121 [255]
114 $ hg qpush
122 $ hg qpush
115 applying url.diff
123 applying url.diff
116 now at: url.diff
124 now at: url.diff
117 $ cat foo
125 $ cat foo
118 foo
126 foo
119 $ hg qpop
127 $ hg qpop
120 popping url.diff
128 popping url.diff
121 patch queue now empty
129 patch queue now empty
122
130
123 qimport -f
131 qimport -f
124
132
125 $ hg qimport -f ../url.diff
133 $ hg qimport -f ../url.diff
126 adding url.diff to series file
134 adding url.diff to series file
127 $ hg qpush
135 $ hg qpush
128 applying url.diff
136 applying url.diff
129 now at: url.diff
137 now at: url.diff
130 $ cat foo
138 $ cat foo
131 foo2
139 foo2
132 $ hg qpop
140 $ hg qpop
133 popping url.diff
141 popping url.diff
134 patch queue now empty
142 patch queue now empty
135
143
136 build diff with CRLF
144 build diff with CRLF
137
145
138 $ python ../writelines.py b 5 'a\n' 5 'a\r\n'
146 $ python ../writelines.py b 5 'a\n' 5 'a\r\n'
139 $ hg ci -Am addb
147 $ hg ci -Am addb
140 adding b
148 adding b
141 $ python ../writelines.py b 2 'a\n' 10 'b\n' 2 'a\r\n'
149 $ python ../writelines.py b 2 'a\n' 10 'b\n' 2 'a\r\n'
142 $ hg diff > b.diff
150 $ hg diff > b.diff
143 $ hg up -C
151 $ hg up -C
144 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
152 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
145
153
146 qimport CRLF diff
154 qimport CRLF diff
147
155
148 $ hg qimport b.diff
156 $ hg qimport b.diff
149 adding b.diff to series file
157 adding b.diff to series file
150 $ hg qpush
158 $ hg qpush
151 applying b.diff
159 applying b.diff
152 now at: b.diff
160 now at: b.diff
153
161
154 try to import --push
162 try to import --push
155
163
156 $ cat > appendfoo.diff <<EOF
164 $ cat > appendfoo.diff <<EOF
157 > append foo
165 > append foo
158 >
166 >
159 > diff -r 07f494440405 -r 261500830e46 baz
167 > diff -r 07f494440405 -r 261500830e46 baz
160 > --- /dev/null Thu Jan 01 00:00:00 1970 +0000
168 > --- /dev/null Thu Jan 01 00:00:00 1970 +0000
161 > +++ b/baz Thu Jan 01 00:00:00 1970 +0000
169 > +++ b/baz Thu Jan 01 00:00:00 1970 +0000
162 > @@ -0,0 +1,1 @@
170 > @@ -0,0 +1,1 @@
163 > +foo
171 > +foo
164 > EOF
172 > EOF
165
173
166 $ cat > appendbar.diff <<EOF
174 $ cat > appendbar.diff <<EOF
167 > append bar
175 > append bar
168 >
176 >
169 > diff -r 07f494440405 -r 261500830e46 baz
177 > diff -r 07f494440405 -r 261500830e46 baz
170 > --- a/baz Thu Jan 01 00:00:00 1970 +0000
178 > --- a/baz Thu Jan 01 00:00:00 1970 +0000
171 > +++ b/baz Thu Jan 01 00:00:00 1970 +0000
179 > +++ b/baz Thu Jan 01 00:00:00 1970 +0000
172 > @@ -1,1 +1,2 @@
180 > @@ -1,1 +1,2 @@
173 > foo
181 > foo
174 > +bar
182 > +bar
175 > EOF
183 > EOF
176
184
177 $ hg qimport --push appendfoo.diff appendbar.diff
185 $ hg qimport --push appendfoo.diff appendbar.diff
178 adding appendfoo.diff to series file
186 adding appendfoo.diff to series file
179 adding appendbar.diff to series file
187 adding appendbar.diff to series file
180 applying appendfoo.diff
188 applying appendfoo.diff
181 applying appendbar.diff
189 applying appendbar.diff
182 now at: appendbar.diff
190 now at: appendbar.diff
183 $ hg qfin -a
191 $ hg qfin -a
184 patch b.diff finalized without changeset message
192 patch b.diff finalized without changeset message
185 $ hg qimport -r 'p1(.)::' -P
193 $ hg qimport -r 'p1(.)::' -P
186 $ hg qpop -a
194 $ hg qpop -a
187 popping 3.diff
195 popping 3.diff
188 popping 2.diff
196 popping 2.diff
189 patch queue now empty
197 patch queue now empty
190 $ hg qdel 3.diff
198 $ hg qdel 3.diff
191 $ hg qdel -k 2.diff
199 $ hg qdel -k 2.diff
192
200
193 qimport -e
201 qimport -e
194
202
195 $ hg qimport -e 2.diff
203 $ hg qimport -e 2.diff
196 adding 2.diff to series file
204 adding 2.diff to series file
197 $ hg qdel -k 2.diff
205 $ hg qdel -k 2.diff
198
206
199 qimport -e --name newname oldexisitingpatch
207 qimport -e --name newname oldexisitingpatch
200
208
201 $ hg qimport -e --name this-name-is-better 2.diff
209 $ hg qimport -e --name this-name-is-better 2.diff
202 renaming 2.diff to this-name-is-better
210 renaming 2.diff to this-name-is-better
203 adding this-name-is-better to series file
211 adding this-name-is-better to series file
204 $ hg qser
212 $ hg qser
205 this-name-is-better
213 this-name-is-better
206 url.diff
214 url.diff
207
215
208 qimport -e --name without --force
216 qimport -e --name without --force
209
217
210 $ cp .hg/patches/this-name-is-better .hg/patches/3.diff
218 $ cp .hg/patches/this-name-is-better .hg/patches/3.diff
211 $ hg qimport -e --name this-name-is-better 3.diff
219 $ hg qimport -e --name this-name-is-better 3.diff
212 abort: patch "this-name-is-better" already exists
220 abort: patch "this-name-is-better" already exists
213 [255]
221 [255]
214 $ hg qser
222 $ hg qser
215 this-name-is-better
223 this-name-is-better
216 url.diff
224 url.diff
217
225
218 qimport -e --name with --force
226 qimport -e --name with --force
219
227
220 $ hg qimport --force -e --name this-name-is-better 3.diff
228 $ hg qimport --force -e --name this-name-is-better 3.diff
221 renaming 3.diff to this-name-is-better
229 renaming 3.diff to this-name-is-better
222 adding this-name-is-better to series file
230 adding this-name-is-better to series file
223 $ hg qser
231 $ hg qser
224 this-name-is-better
232 this-name-is-better
225 url.diff
233 url.diff
226
234
227 qimport with bad name, should abort before reading file
235 qimport with bad name, should abort before reading file
228
236
229 $ hg qimport non-existant-file --name .hg
237 $ hg qimport non-existant-file --name .hg
230 abort: patch name cannot begin with ".hg"
238 abort: patch name cannot begin with ".hg"
231 [255]
239 [255]
232
240
233 qimport http:// patch with leading slashes in url
241 qimport http:// patch with leading slashes in url
234
242
235 set up hgweb
243 set up hgweb
236
244
237 $ cd ..
245 $ cd ..
238 $ hg init served
246 $ hg init served
239 $ cd served
247 $ cd served
240 $ echo a > a
248 $ echo a > a
241 $ hg ci -Am patch
249 $ hg ci -Am patch
242 adding a
250 adding a
243 $ hg serve -p $HGPORT -d --pid-file=hg.pid -A access.log -E errors.log
251 $ hg serve -p $HGPORT -d --pid-file=hg.pid -A access.log -E errors.log
244 $ cat hg.pid >> $DAEMON_PIDS
252 $ cat hg.pid >> $DAEMON_PIDS
245
253
246 $ cd ../repo
254 $ cd ../repo
247 $ hg qimport http://localhost:$HGPORT/raw-rev/0///
255 $ hg qimport http://localhost:$HGPORT/raw-rev/0///
248 adding 0 to series file
256 adding 0 to series file
249
257
250 check qimport phase:
258 check qimport phase:
251
259
252 $ hg -q qpush
260 $ hg -q qpush
253 now at: 0
261 now at: 0
254 $ hg phase qparent
262 $ hg phase qparent
255 1: draft
263 1: draft
256 $ hg qimport -r qparent
264 $ hg qimport -r qparent
257 $ hg phase qbase
265 $ hg phase qbase
258 1: draft
266 1: draft
259 $ hg qfinish qbase
267 $ hg qfinish qbase
260 $ echo '[mq]' >> $HGRCPATH
268 $ echo '[mq]' >> $HGRCPATH
261 $ echo 'secret=true' >> $HGRCPATH
269 $ echo 'secret=true' >> $HGRCPATH
262 $ hg qimport -r qparent
270 $ hg qimport -r qparent
263 $ hg phase qbase
271 $ hg phase qbase
264 1: secret
272 1: secret
@@ -1,82 +1,82 b''
1 $ "$TESTDIR/hghave" serve || exit 80
1 $ "$TESTDIR/hghave" serve || exit 80
2
2
3 $ hgserve()
3 $ hgserve()
4 > {
4 > {
5 > hg serve -a localhost -d --pid-file=hg.pid -E errors.log -v $@ \
5 > hg serve -a localhost -d --pid-file=hg.pid -E errors.log -v $@ \
6 > | sed -e "s/:$HGPORT1\\([^0-9]\\)/:HGPORT1\1/g" \
6 > | sed -e "s/:$HGPORT1\\([^0-9]\\)/:HGPORT1\1/g" \
7 > -e "s/:$HGPORT2\\([^0-9]\\)/:HGPORT2\1/g" \
7 > -e "s/:$HGPORT2\\([^0-9]\\)/:HGPORT2\1/g" \
8 > -e 's/http:\/\/[^/]*\//http:\/\/localhost\//'
8 > -e 's/http:\/\/[^/]*\//http:\/\/localhost\//'
9 > cat hg.pid >> "$DAEMON_PIDS"
9 > cat hg.pid >> "$DAEMON_PIDS"
10 > echo % errors
10 > echo % errors
11 > cat errors.log
11 > cat errors.log
12 > if [ "$KILLQUIETLY" = "Y" ]; then
12 > if [ "$KILLQUIETLY" = "Y" ]; then
13 > kill `cat hg.pid` 2>/dev/null
13 > kill `cat hg.pid` 2>/dev/null
14 > else
14 > else
15 > kill `cat hg.pid`
15 > kill `cat hg.pid`
16 > fi
16 > fi
17 > while kill -0 `cat hg.pid` 2>/dev/null; do true; done
17 > while kill -0 `cat hg.pid` 2>/dev/null; do sleep 0; done
18 > }
18 > }
19
19
20 $ hg init test
20 $ hg init test
21 $ cd test
21 $ cd test
22 $ echo '[web]' > .hg/hgrc
22 $ echo '[web]' > .hg/hgrc
23 $ echo 'accesslog = access.log' >> .hg/hgrc
23 $ echo 'accesslog = access.log' >> .hg/hgrc
24 $ echo "port = $HGPORT1" >> .hg/hgrc
24 $ echo "port = $HGPORT1" >> .hg/hgrc
25
25
26 Without -v
26 Without -v
27
27
28 $ hg serve -a localhost -p $HGPORT -d --pid-file=hg.pid -E errors.log
28 $ hg serve -a localhost -p $HGPORT -d --pid-file=hg.pid -E errors.log
29 $ cat hg.pid >> "$DAEMON_PIDS"
29 $ cat hg.pid >> "$DAEMON_PIDS"
30 $ if [ -f access.log ]; then
30 $ if [ -f access.log ]; then
31 $ echo 'access log created - .hg/hgrc respected'
31 $ echo 'access log created - .hg/hgrc respected'
32 access log created - .hg/hgrc respected
32 access log created - .hg/hgrc respected
33 $ fi
33 $ fi
34
34
35 errors
35 errors
36
36
37 $ cat errors.log
37 $ cat errors.log
38
38
39 With -v
39 With -v
40
40
41 $ hgserve
41 $ hgserve
42 listening at http://localhost/ (bound to 127.0.0.1:HGPORT1)
42 listening at http://localhost/ (bound to 127.0.0.1:HGPORT1)
43 % errors
43 % errors
44
44
45 With -v and -p HGPORT2
45 With -v and -p HGPORT2
46
46
47 $ hgserve -p "$HGPORT2"
47 $ hgserve -p "$HGPORT2"
48 listening at http://localhost/ (bound to 127.0.0.1:HGPORT2)
48 listening at http://localhost/ (bound to 127.0.0.1:HGPORT2)
49 % errors
49 % errors
50
50
51 With -v and -p daytime (should fail because low port)
51 With -v and -p daytime (should fail because low port)
52
52
53 $ KILLQUIETLY=Y
53 $ KILLQUIETLY=Y
54 $ hgserve -p daytime
54 $ hgserve -p daytime
55 abort: cannot start server at 'localhost:13': Permission denied
55 abort: cannot start server at 'localhost:13': Permission denied
56 abort: child process failed to start
56 abort: child process failed to start
57 % errors
57 % errors
58 $ KILLQUIETLY=N
58 $ KILLQUIETLY=N
59
59
60 With --prefix foo
60 With --prefix foo
61
61
62 $ hgserve --prefix foo
62 $ hgserve --prefix foo
63 listening at http://localhost/foo/ (bound to 127.0.0.1:HGPORT1)
63 listening at http://localhost/foo/ (bound to 127.0.0.1:HGPORT1)
64 % errors
64 % errors
65
65
66 With --prefix /foo
66 With --prefix /foo
67
67
68 $ hgserve --prefix /foo
68 $ hgserve --prefix /foo
69 listening at http://localhost/foo/ (bound to 127.0.0.1:HGPORT1)
69 listening at http://localhost/foo/ (bound to 127.0.0.1:HGPORT1)
70 % errors
70 % errors
71
71
72 With --prefix foo/
72 With --prefix foo/
73
73
74 $ hgserve --prefix foo/
74 $ hgserve --prefix foo/
75 listening at http://localhost/foo/ (bound to 127.0.0.1:HGPORT1)
75 listening at http://localhost/foo/ (bound to 127.0.0.1:HGPORT1)
76 % errors
76 % errors
77
77
78 With --prefix /foo/
78 With --prefix /foo/
79
79
80 $ hgserve --prefix /foo/
80 $ hgserve --prefix /foo/
81 listening at http://localhost/foo/ (bound to 127.0.0.1:HGPORT1)
81 listening at http://localhost/foo/ (bound to 127.0.0.1:HGPORT1)
82 % errors
82 % errors
General Comments 0
You need to be logged in to leave comments. Login now