Show More
@@ -1,3267 +1,3268 | |||||
1 | # cmdutil.py - help for command processing in mercurial |
|
1 | # cmdutil.py - help for command processing in 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 __future__ import absolute_import |
|
8 | from __future__ import absolute_import | |
9 |
|
9 | |||
10 | import errno |
|
10 | import errno | |
11 | import os |
|
11 | import os | |
12 | import re |
|
12 | import re | |
13 |
|
13 | |||
14 | from .i18n import _ |
|
14 | from .i18n import _ | |
15 | from .node import ( |
|
15 | from .node import ( | |
16 | hex, |
|
16 | hex, | |
17 | nullid, |
|
17 | nullid, | |
18 | nullrev, |
|
18 | nullrev, | |
19 | short, |
|
19 | short, | |
20 | ) |
|
20 | ) | |
21 |
|
21 | |||
22 | from . import ( |
|
22 | from . import ( | |
23 | bookmarks, |
|
23 | bookmarks, | |
24 | changelog, |
|
24 | changelog, | |
25 | copies, |
|
25 | copies, | |
26 | crecord as crecordmod, |
|
26 | crecord as crecordmod, | |
27 | dirstateguard, |
|
27 | dirstateguard, | |
28 | encoding, |
|
28 | encoding, | |
29 | error, |
|
29 | error, | |
30 | formatter, |
|
30 | formatter, | |
31 | logcmdutil, |
|
31 | logcmdutil, | |
32 | match as matchmod, |
|
32 | match as matchmod, | |
33 | merge as mergemod, |
|
33 | merge as mergemod, | |
34 | mergeutil, |
|
34 | mergeutil, | |
35 | obsolete, |
|
35 | obsolete, | |
36 | patch, |
|
36 | patch, | |
37 | pathutil, |
|
37 | pathutil, | |
38 | phases, |
|
38 | phases, | |
39 | pycompat, |
|
39 | pycompat, | |
40 | revlog, |
|
40 | revlog, | |
41 | rewriteutil, |
|
41 | rewriteutil, | |
42 | scmutil, |
|
42 | scmutil, | |
43 | smartset, |
|
43 | smartset, | |
44 | subrepoutil, |
|
44 | subrepoutil, | |
45 | templatekw, |
|
45 | templatekw, | |
46 | templater, |
|
46 | templater, | |
47 | util, |
|
47 | util, | |
48 | vfs as vfsmod, |
|
48 | vfs as vfsmod, | |
49 | ) |
|
49 | ) | |
50 |
|
50 | |||
51 | from .utils import ( |
|
51 | from .utils import ( | |
52 | dateutil, |
|
52 | dateutil, | |
53 | stringutil, |
|
53 | stringutil, | |
54 | ) |
|
54 | ) | |
55 |
|
55 | |||
56 | stringio = util.stringio |
|
56 | stringio = util.stringio | |
57 |
|
57 | |||
58 | # templates of common command options |
|
58 | # templates of common command options | |
59 |
|
59 | |||
60 | dryrunopts = [ |
|
60 | dryrunopts = [ | |
61 | ('n', 'dry-run', None, |
|
61 | ('n', 'dry-run', None, | |
62 | _('do not perform actions, just print output')), |
|
62 | _('do not perform actions, just print output')), | |
63 | ] |
|
63 | ] | |
64 |
|
64 | |||
65 | confirmopts = [ |
|
65 | confirmopts = [ | |
66 | ('', 'confirm', None, |
|
66 | ('', 'confirm', None, | |
67 | _('ask before applying actions')), |
|
67 | _('ask before applying actions')), | |
68 | ] |
|
68 | ] | |
69 |
|
69 | |||
70 | remoteopts = [ |
|
70 | remoteopts = [ | |
71 | ('e', 'ssh', '', |
|
71 | ('e', 'ssh', '', | |
72 | _('specify ssh command to use'), _('CMD')), |
|
72 | _('specify ssh command to use'), _('CMD')), | |
73 | ('', 'remotecmd', '', |
|
73 | ('', 'remotecmd', '', | |
74 | _('specify hg command to run on the remote side'), _('CMD')), |
|
74 | _('specify hg command to run on the remote side'), _('CMD')), | |
75 | ('', 'insecure', None, |
|
75 | ('', 'insecure', None, | |
76 | _('do not verify server certificate (ignoring web.cacerts config)')), |
|
76 | _('do not verify server certificate (ignoring web.cacerts config)')), | |
77 | ] |
|
77 | ] | |
78 |
|
78 | |||
79 | walkopts = [ |
|
79 | walkopts = [ | |
80 | ('I', 'include', [], |
|
80 | ('I', 'include', [], | |
81 | _('include names matching the given patterns'), _('PATTERN')), |
|
81 | _('include names matching the given patterns'), _('PATTERN')), | |
82 | ('X', 'exclude', [], |
|
82 | ('X', 'exclude', [], | |
83 | _('exclude names matching the given patterns'), _('PATTERN')), |
|
83 | _('exclude names matching the given patterns'), _('PATTERN')), | |
84 | ] |
|
84 | ] | |
85 |
|
85 | |||
86 | commitopts = [ |
|
86 | commitopts = [ | |
87 | ('m', 'message', '', |
|
87 | ('m', 'message', '', | |
88 | _('use text as commit message'), _('TEXT')), |
|
88 | _('use text as commit message'), _('TEXT')), | |
89 | ('l', 'logfile', '', |
|
89 | ('l', 'logfile', '', | |
90 | _('read commit message from file'), _('FILE')), |
|
90 | _('read commit message from file'), _('FILE')), | |
91 | ] |
|
91 | ] | |
92 |
|
92 | |||
93 | commitopts2 = [ |
|
93 | commitopts2 = [ | |
94 | ('d', 'date', '', |
|
94 | ('d', 'date', '', | |
95 | _('record the specified date as commit date'), _('DATE')), |
|
95 | _('record the specified date as commit date'), _('DATE')), | |
96 | ('u', 'user', '', |
|
96 | ('u', 'user', '', | |
97 | _('record the specified user as committer'), _('USER')), |
|
97 | _('record the specified user as committer'), _('USER')), | |
98 | ] |
|
98 | ] | |
99 |
|
99 | |||
100 | # hidden for now |
|
100 | # hidden for now | |
101 | formatteropts = [ |
|
101 | formatteropts = [ | |
102 | ('T', 'template', '', |
|
102 | ('T', 'template', '', | |
103 | _('display with template (EXPERIMENTAL)'), _('TEMPLATE')), |
|
103 | _('display with template (EXPERIMENTAL)'), _('TEMPLATE')), | |
104 | ] |
|
104 | ] | |
105 |
|
105 | |||
106 | templateopts = [ |
|
106 | templateopts = [ | |
107 | ('', 'style', '', |
|
107 | ('', 'style', '', | |
108 | _('display using template map file (DEPRECATED)'), _('STYLE')), |
|
108 | _('display using template map file (DEPRECATED)'), _('STYLE')), | |
109 | ('T', 'template', '', |
|
109 | ('T', 'template', '', | |
110 | _('display with template'), _('TEMPLATE')), |
|
110 | _('display with template'), _('TEMPLATE')), | |
111 | ] |
|
111 | ] | |
112 |
|
112 | |||
113 | logopts = [ |
|
113 | logopts = [ | |
114 | ('p', 'patch', None, _('show patch')), |
|
114 | ('p', 'patch', None, _('show patch')), | |
115 | ('g', 'git', None, _('use git extended diff format')), |
|
115 | ('g', 'git', None, _('use git extended diff format')), | |
116 | ('l', 'limit', '', |
|
116 | ('l', 'limit', '', | |
117 | _('limit number of changes displayed'), _('NUM')), |
|
117 | _('limit number of changes displayed'), _('NUM')), | |
118 | ('M', 'no-merges', None, _('do not show merges')), |
|
118 | ('M', 'no-merges', None, _('do not show merges')), | |
119 | ('', 'stat', None, _('output diffstat-style summary of changes')), |
|
119 | ('', 'stat', None, _('output diffstat-style summary of changes')), | |
120 | ('G', 'graph', None, _("show the revision DAG")), |
|
120 | ('G', 'graph', None, _("show the revision DAG")), | |
121 | ] + templateopts |
|
121 | ] + templateopts | |
122 |
|
122 | |||
123 | diffopts = [ |
|
123 | diffopts = [ | |
124 | ('a', 'text', None, _('treat all files as text')), |
|
124 | ('a', 'text', None, _('treat all files as text')), | |
125 | ('g', 'git', None, _('use git extended diff format')), |
|
125 | ('g', 'git', None, _('use git extended diff format')), | |
126 | ('', 'binary', None, _('generate binary diffs in git mode (default)')), |
|
126 | ('', 'binary', None, _('generate binary diffs in git mode (default)')), | |
127 | ('', 'nodates', None, _('omit dates from diff headers')) |
|
127 | ('', 'nodates', None, _('omit dates from diff headers')) | |
128 | ] |
|
128 | ] | |
129 |
|
129 | |||
130 | diffwsopts = [ |
|
130 | diffwsopts = [ | |
131 | ('w', 'ignore-all-space', None, |
|
131 | ('w', 'ignore-all-space', None, | |
132 | _('ignore white space when comparing lines')), |
|
132 | _('ignore white space when comparing lines')), | |
133 | ('b', 'ignore-space-change', None, |
|
133 | ('b', 'ignore-space-change', None, | |
134 | _('ignore changes in the amount of white space')), |
|
134 | _('ignore changes in the amount of white space')), | |
135 | ('B', 'ignore-blank-lines', None, |
|
135 | ('B', 'ignore-blank-lines', None, | |
136 | _('ignore changes whose lines are all blank')), |
|
136 | _('ignore changes whose lines are all blank')), | |
137 | ('Z', 'ignore-space-at-eol', None, |
|
137 | ('Z', 'ignore-space-at-eol', None, | |
138 | _('ignore changes in whitespace at EOL')), |
|
138 | _('ignore changes in whitespace at EOL')), | |
139 | ] |
|
139 | ] | |
140 |
|
140 | |||
141 | diffopts2 = [ |
|
141 | diffopts2 = [ | |
142 | ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')), |
|
142 | ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')), | |
143 | ('p', 'show-function', None, _('show which function each change is in')), |
|
143 | ('p', 'show-function', None, _('show which function each change is in')), | |
144 | ('', 'reverse', None, _('produce a diff that undoes the changes')), |
|
144 | ('', 'reverse', None, _('produce a diff that undoes the changes')), | |
145 | ] + diffwsopts + [ |
|
145 | ] + diffwsopts + [ | |
146 | ('U', 'unified', '', |
|
146 | ('U', 'unified', '', | |
147 | _('number of lines of context to show'), _('NUM')), |
|
147 | _('number of lines of context to show'), _('NUM')), | |
148 | ('', 'stat', None, _('output diffstat-style summary of changes')), |
|
148 | ('', 'stat', None, _('output diffstat-style summary of changes')), | |
149 | ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')), |
|
149 | ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')), | |
150 | ] |
|
150 | ] | |
151 |
|
151 | |||
152 | mergetoolopts = [ |
|
152 | mergetoolopts = [ | |
153 | ('t', 'tool', '', _('specify merge tool')), |
|
153 | ('t', 'tool', '', _('specify merge tool')), | |
154 | ] |
|
154 | ] | |
155 |
|
155 | |||
156 | similarityopts = [ |
|
156 | similarityopts = [ | |
157 | ('s', 'similarity', '', |
|
157 | ('s', 'similarity', '', | |
158 | _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY')) |
|
158 | _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY')) | |
159 | ] |
|
159 | ] | |
160 |
|
160 | |||
161 | subrepoopts = [ |
|
161 | subrepoopts = [ | |
162 | ('S', 'subrepos', None, |
|
162 | ('S', 'subrepos', None, | |
163 | _('recurse into subrepositories')) |
|
163 | _('recurse into subrepositories')) | |
164 | ] |
|
164 | ] | |
165 |
|
165 | |||
166 | debugrevlogopts = [ |
|
166 | debugrevlogopts = [ | |
167 | ('c', 'changelog', False, _('open changelog')), |
|
167 | ('c', 'changelog', False, _('open changelog')), | |
168 | ('m', 'manifest', False, _('open manifest')), |
|
168 | ('m', 'manifest', False, _('open manifest')), | |
169 | ('', 'dir', '', _('open directory manifest')), |
|
169 | ('', 'dir', '', _('open directory manifest')), | |
170 | ] |
|
170 | ] | |
171 |
|
171 | |||
172 | # special string such that everything below this line will be ingored in the |
|
172 | # special string such that everything below this line will be ingored in the | |
173 | # editor text |
|
173 | # editor text | |
174 | _linebelow = "^HG: ------------------------ >8 ------------------------$" |
|
174 | _linebelow = "^HG: ------------------------ >8 ------------------------$" | |
175 |
|
175 | |||
176 | def ishunk(x): |
|
176 | def ishunk(x): | |
177 | hunkclasses = (crecordmod.uihunk, patch.recordhunk) |
|
177 | hunkclasses = (crecordmod.uihunk, patch.recordhunk) | |
178 | return isinstance(x, hunkclasses) |
|
178 | return isinstance(x, hunkclasses) | |
179 |
|
179 | |||
180 | def newandmodified(chunks, originalchunks): |
|
180 | def newandmodified(chunks, originalchunks): | |
181 | newlyaddedandmodifiedfiles = set() |
|
181 | newlyaddedandmodifiedfiles = set() | |
182 | for chunk in chunks: |
|
182 | for chunk in chunks: | |
183 | if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \ |
|
183 | if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \ | |
184 | originalchunks: |
|
184 | originalchunks: | |
185 | newlyaddedandmodifiedfiles.add(chunk.header.filename()) |
|
185 | newlyaddedandmodifiedfiles.add(chunk.header.filename()) | |
186 | return newlyaddedandmodifiedfiles |
|
186 | return newlyaddedandmodifiedfiles | |
187 |
|
187 | |||
188 | def parsealiases(cmd): |
|
188 | def parsealiases(cmd): | |
189 | return cmd.lstrip("^").split("|") |
|
189 | return cmd.lstrip("^").split("|") | |
190 |
|
190 | |||
191 | def setupwrapcolorwrite(ui): |
|
191 | def setupwrapcolorwrite(ui): | |
192 | # wrap ui.write so diff output can be labeled/colorized |
|
192 | # wrap ui.write so diff output can be labeled/colorized | |
193 | def wrapwrite(orig, *args, **kw): |
|
193 | def wrapwrite(orig, *args, **kw): | |
194 | label = kw.pop(r'label', '') |
|
194 | label = kw.pop(r'label', '') | |
195 | for chunk, l in patch.difflabel(lambda: args): |
|
195 | for chunk, l in patch.difflabel(lambda: args): | |
196 | orig(chunk, label=label + l) |
|
196 | orig(chunk, label=label + l) | |
197 |
|
197 | |||
198 | oldwrite = ui.write |
|
198 | oldwrite = ui.write | |
199 | def wrap(*args, **kwargs): |
|
199 | def wrap(*args, **kwargs): | |
200 | return wrapwrite(oldwrite, *args, **kwargs) |
|
200 | return wrapwrite(oldwrite, *args, **kwargs) | |
201 | setattr(ui, 'write', wrap) |
|
201 | setattr(ui, 'write', wrap) | |
202 | return oldwrite |
|
202 | return oldwrite | |
203 |
|
203 | |||
204 | def filterchunks(ui, originalhunks, usecurses, testfile, operation=None): |
|
204 | def filterchunks(ui, originalhunks, usecurses, testfile, operation=None): | |
205 | try: |
|
205 | try: | |
206 | if usecurses: |
|
206 | if usecurses: | |
207 | if testfile: |
|
207 | if testfile: | |
208 | recordfn = crecordmod.testdecorator( |
|
208 | recordfn = crecordmod.testdecorator( | |
209 | testfile, crecordmod.testchunkselector) |
|
209 | testfile, crecordmod.testchunkselector) | |
210 | else: |
|
210 | else: | |
211 | recordfn = crecordmod.chunkselector |
|
211 | recordfn = crecordmod.chunkselector | |
212 |
|
212 | |||
213 | return crecordmod.filterpatch(ui, originalhunks, recordfn, |
|
213 | return crecordmod.filterpatch(ui, originalhunks, recordfn, | |
214 | operation) |
|
214 | operation) | |
215 | except crecordmod.fallbackerror as e: |
|
215 | except crecordmod.fallbackerror as e: | |
216 | ui.warn('%s\n' % e.message) |
|
216 | ui.warn('%s\n' % e.message) | |
217 | ui.warn(_('falling back to text mode\n')) |
|
217 | ui.warn(_('falling back to text mode\n')) | |
218 |
|
218 | |||
219 | return patch.filterpatch(ui, originalhunks, operation) |
|
219 | return patch.filterpatch(ui, originalhunks, operation) | |
220 |
|
220 | |||
221 | def recordfilter(ui, originalhunks, operation=None): |
|
221 | def recordfilter(ui, originalhunks, operation=None): | |
222 | """ Prompts the user to filter the originalhunks and return a list of |
|
222 | """ Prompts the user to filter the originalhunks and return a list of | |
223 | selected hunks. |
|
223 | selected hunks. | |
224 | *operation* is used for to build ui messages to indicate the user what |
|
224 | *operation* is used for to build ui messages to indicate the user what | |
225 | kind of filtering they are doing: reverting, committing, shelving, etc. |
|
225 | kind of filtering they are doing: reverting, committing, shelving, etc. | |
226 | (see patch.filterpatch). |
|
226 | (see patch.filterpatch). | |
227 | """ |
|
227 | """ | |
228 | usecurses = crecordmod.checkcurses(ui) |
|
228 | usecurses = crecordmod.checkcurses(ui) | |
229 | testfile = ui.config('experimental', 'crecordtest') |
|
229 | testfile = ui.config('experimental', 'crecordtest') | |
230 | oldwrite = setupwrapcolorwrite(ui) |
|
230 | oldwrite = setupwrapcolorwrite(ui) | |
231 | try: |
|
231 | try: | |
232 | newchunks, newopts = filterchunks(ui, originalhunks, usecurses, |
|
232 | newchunks, newopts = filterchunks(ui, originalhunks, usecurses, | |
233 | testfile, operation) |
|
233 | testfile, operation) | |
234 | finally: |
|
234 | finally: | |
235 | ui.write = oldwrite |
|
235 | ui.write = oldwrite | |
236 | return newchunks, newopts |
|
236 | return newchunks, newopts | |
237 |
|
237 | |||
238 | def dorecord(ui, repo, commitfunc, cmdsuggest, backupall, |
|
238 | def dorecord(ui, repo, commitfunc, cmdsuggest, backupall, | |
239 | filterfn, *pats, **opts): |
|
239 | filterfn, *pats, **opts): | |
240 | opts = pycompat.byteskwargs(opts) |
|
240 | opts = pycompat.byteskwargs(opts) | |
241 | if not ui.interactive(): |
|
241 | if not ui.interactive(): | |
242 | if cmdsuggest: |
|
242 | if cmdsuggest: | |
243 | msg = _('running non-interactively, use %s instead') % cmdsuggest |
|
243 | msg = _('running non-interactively, use %s instead') % cmdsuggest | |
244 | else: |
|
244 | else: | |
245 | msg = _('running non-interactively') |
|
245 | msg = _('running non-interactively') | |
246 | raise error.Abort(msg) |
|
246 | raise error.Abort(msg) | |
247 |
|
247 | |||
248 | # make sure username is set before going interactive |
|
248 | # make sure username is set before going interactive | |
249 | if not opts.get('user'): |
|
249 | if not opts.get('user'): | |
250 | ui.username() # raise exception, username not provided |
|
250 | ui.username() # raise exception, username not provided | |
251 |
|
251 | |||
252 | def recordfunc(ui, repo, message, match, opts): |
|
252 | def recordfunc(ui, repo, message, match, opts): | |
253 | """This is generic record driver. |
|
253 | """This is generic record driver. | |
254 |
|
254 | |||
255 | Its job is to interactively filter local changes, and |
|
255 | Its job is to interactively filter local changes, and | |
256 | accordingly prepare working directory into a state in which the |
|
256 | accordingly prepare working directory into a state in which the | |
257 | job can be delegated to a non-interactive commit command such as |
|
257 | job can be delegated to a non-interactive commit command such as | |
258 | 'commit' or 'qrefresh'. |
|
258 | 'commit' or 'qrefresh'. | |
259 |
|
259 | |||
260 | After the actual job is done by non-interactive command, the |
|
260 | After the actual job is done by non-interactive command, the | |
261 | working directory is restored to its original state. |
|
261 | working directory is restored to its original state. | |
262 |
|
262 | |||
263 | In the end we'll record interesting changes, and everything else |
|
263 | In the end we'll record interesting changes, and everything else | |
264 | will be left in place, so the user can continue working. |
|
264 | will be left in place, so the user can continue working. | |
265 | """ |
|
265 | """ | |
266 |
|
266 | |||
267 | checkunfinished(repo, commit=True) |
|
267 | checkunfinished(repo, commit=True) | |
268 | wctx = repo[None] |
|
268 | wctx = repo[None] | |
269 | merge = len(wctx.parents()) > 1 |
|
269 | merge = len(wctx.parents()) > 1 | |
270 | if merge: |
|
270 | if merge: | |
271 | raise error.Abort(_('cannot partially commit a merge ' |
|
271 | raise error.Abort(_('cannot partially commit a merge ' | |
272 | '(use "hg commit" instead)')) |
|
272 | '(use "hg commit" instead)')) | |
273 |
|
273 | |||
274 | def fail(f, msg): |
|
274 | def fail(f, msg): | |
275 | raise error.Abort('%s: %s' % (f, msg)) |
|
275 | raise error.Abort('%s: %s' % (f, msg)) | |
276 |
|
276 | |||
277 | force = opts.get('force') |
|
277 | force = opts.get('force') | |
278 | if not force: |
|
278 | if not force: | |
279 | vdirs = [] |
|
279 | vdirs = [] | |
280 | match.explicitdir = vdirs.append |
|
280 | match.explicitdir = vdirs.append | |
281 | match.bad = fail |
|
281 | match.bad = fail | |
282 |
|
282 | |||
283 | status = repo.status(match=match) |
|
283 | status = repo.status(match=match) | |
284 | if not force: |
|
284 | if not force: | |
285 | repo.checkcommitpatterns(wctx, vdirs, match, status, fail) |
|
285 | repo.checkcommitpatterns(wctx, vdirs, match, status, fail) | |
286 | diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True) |
|
286 | diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True) | |
287 | diffopts.nodates = True |
|
287 | diffopts.nodates = True | |
288 | diffopts.git = True |
|
288 | diffopts.git = True | |
289 | diffopts.showfunc = True |
|
289 | diffopts.showfunc = True | |
290 | originaldiff = patch.diff(repo, changes=status, opts=diffopts) |
|
290 | originaldiff = patch.diff(repo, changes=status, opts=diffopts) | |
291 | originalchunks = patch.parsepatch(originaldiff) |
|
291 | originalchunks = patch.parsepatch(originaldiff) | |
292 |
|
292 | |||
293 | # 1. filter patch, since we are intending to apply subset of it |
|
293 | # 1. filter patch, since we are intending to apply subset of it | |
294 | try: |
|
294 | try: | |
295 | chunks, newopts = filterfn(ui, originalchunks) |
|
295 | chunks, newopts = filterfn(ui, originalchunks) | |
296 | except error.PatchError as err: |
|
296 | except error.PatchError as err: | |
297 | raise error.Abort(_('error parsing patch: %s') % err) |
|
297 | raise error.Abort(_('error parsing patch: %s') % err) | |
298 | opts.update(newopts) |
|
298 | opts.update(newopts) | |
299 |
|
299 | |||
300 | # We need to keep a backup of files that have been newly added and |
|
300 | # We need to keep a backup of files that have been newly added and | |
301 | # modified during the recording process because there is a previous |
|
301 | # modified during the recording process because there is a previous | |
302 | # version without the edit in the workdir |
|
302 | # version without the edit in the workdir | |
303 | newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks) |
|
303 | newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks) | |
304 | contenders = set() |
|
304 | contenders = set() | |
305 | for h in chunks: |
|
305 | for h in chunks: | |
306 | try: |
|
306 | try: | |
307 | contenders.update(set(h.files())) |
|
307 | contenders.update(set(h.files())) | |
308 | except AttributeError: |
|
308 | except AttributeError: | |
309 | pass |
|
309 | pass | |
310 |
|
310 | |||
311 | changed = status.modified + status.added + status.removed |
|
311 | changed = status.modified + status.added + status.removed | |
312 | newfiles = [f for f in changed if f in contenders] |
|
312 | newfiles = [f for f in changed if f in contenders] | |
313 | if not newfiles: |
|
313 | if not newfiles: | |
314 | ui.status(_('no changes to record\n')) |
|
314 | ui.status(_('no changes to record\n')) | |
315 | return 0 |
|
315 | return 0 | |
316 |
|
316 | |||
317 | modified = set(status.modified) |
|
317 | modified = set(status.modified) | |
318 |
|
318 | |||
319 | # 2. backup changed files, so we can restore them in the end |
|
319 | # 2. backup changed files, so we can restore them in the end | |
320 |
|
320 | |||
321 | if backupall: |
|
321 | if backupall: | |
322 | tobackup = changed |
|
322 | tobackup = changed | |
323 | else: |
|
323 | else: | |
324 | tobackup = [f for f in newfiles if f in modified or f in \ |
|
324 | tobackup = [f for f in newfiles if f in modified or f in \ | |
325 | newlyaddedandmodifiedfiles] |
|
325 | newlyaddedandmodifiedfiles] | |
326 | backups = {} |
|
326 | backups = {} | |
327 | if tobackup: |
|
327 | if tobackup: | |
328 | backupdir = repo.vfs.join('record-backups') |
|
328 | backupdir = repo.vfs.join('record-backups') | |
329 | try: |
|
329 | try: | |
330 | os.mkdir(backupdir) |
|
330 | os.mkdir(backupdir) | |
331 | except OSError as err: |
|
331 | except OSError as err: | |
332 | if err.errno != errno.EEXIST: |
|
332 | if err.errno != errno.EEXIST: | |
333 | raise |
|
333 | raise | |
334 | try: |
|
334 | try: | |
335 | # backup continues |
|
335 | # backup continues | |
336 | for f in tobackup: |
|
336 | for f in tobackup: | |
337 | fd, tmpname = pycompat.mkstemp(prefix=f.replace('/', '_') + '.', |
|
337 | fd, tmpname = pycompat.mkstemp(prefix=f.replace('/', '_') + '.', | |
338 | dir=backupdir) |
|
338 | dir=backupdir) | |
339 | os.close(fd) |
|
339 | os.close(fd) | |
340 | ui.debug('backup %r as %r\n' % (f, tmpname)) |
|
340 | ui.debug('backup %r as %r\n' % (f, tmpname)) | |
341 | util.copyfile(repo.wjoin(f), tmpname, copystat=True) |
|
341 | util.copyfile(repo.wjoin(f), tmpname, copystat=True) | |
342 | backups[f] = tmpname |
|
342 | backups[f] = tmpname | |
343 |
|
343 | |||
344 | fp = stringio() |
|
344 | fp = stringio() | |
345 | for c in chunks: |
|
345 | for c in chunks: | |
346 | fname = c.filename() |
|
346 | fname = c.filename() | |
347 | if fname in backups: |
|
347 | if fname in backups: | |
348 | c.write(fp) |
|
348 | c.write(fp) | |
349 | dopatch = fp.tell() |
|
349 | dopatch = fp.tell() | |
350 | fp.seek(0) |
|
350 | fp.seek(0) | |
351 |
|
351 | |||
352 | # 2.5 optionally review / modify patch in text editor |
|
352 | # 2.5 optionally review / modify patch in text editor | |
353 | if opts.get('review', False): |
|
353 | if opts.get('review', False): | |
354 | patchtext = (crecordmod.diffhelptext |
|
354 | patchtext = (crecordmod.diffhelptext | |
355 | + crecordmod.patchhelptext |
|
355 | + crecordmod.patchhelptext | |
356 | + fp.read()) |
|
356 | + fp.read()) | |
357 | reviewedpatch = ui.edit(patchtext, "", |
|
357 | reviewedpatch = ui.edit(patchtext, "", | |
358 | action="diff", |
|
358 | action="diff", | |
359 | repopath=repo.path) |
|
359 | repopath=repo.path) | |
360 | fp.truncate(0) |
|
360 | fp.truncate(0) | |
361 | fp.write(reviewedpatch) |
|
361 | fp.write(reviewedpatch) | |
362 | fp.seek(0) |
|
362 | fp.seek(0) | |
363 |
|
363 | |||
364 | [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles] |
|
364 | [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles] | |
365 | # 3a. apply filtered patch to clean repo (clean) |
|
365 | # 3a. apply filtered patch to clean repo (clean) | |
366 | if backups: |
|
366 | if backups: | |
367 | # Equivalent to hg.revert |
|
367 | # Equivalent to hg.revert | |
368 | m = scmutil.matchfiles(repo, backups.keys()) |
|
368 | m = scmutil.matchfiles(repo, backups.keys()) | |
369 | mergemod.update(repo, repo.dirstate.p1(), |
|
369 | mergemod.update(repo, repo.dirstate.p1(), | |
370 | False, True, matcher=m) |
|
370 | False, True, matcher=m) | |
371 |
|
371 | |||
372 | # 3b. (apply) |
|
372 | # 3b. (apply) | |
373 | if dopatch: |
|
373 | if dopatch: | |
374 | try: |
|
374 | try: | |
375 | ui.debug('applying patch\n') |
|
375 | ui.debug('applying patch\n') | |
376 | ui.debug(fp.getvalue()) |
|
376 | ui.debug(fp.getvalue()) | |
377 | patch.internalpatch(ui, repo, fp, 1, eolmode=None) |
|
377 | patch.internalpatch(ui, repo, fp, 1, eolmode=None) | |
378 | except error.PatchError as err: |
|
378 | except error.PatchError as err: | |
379 | raise error.Abort(pycompat.bytestr(err)) |
|
379 | raise error.Abort(pycompat.bytestr(err)) | |
380 | del fp |
|
380 | del fp | |
381 |
|
381 | |||
382 | # 4. We prepared working directory according to filtered |
|
382 | # 4. We prepared working directory according to filtered | |
383 | # patch. Now is the time to delegate the job to |
|
383 | # patch. Now is the time to delegate the job to | |
384 | # commit/qrefresh or the like! |
|
384 | # commit/qrefresh or the like! | |
385 |
|
385 | |||
386 | # Make all of the pathnames absolute. |
|
386 | # Make all of the pathnames absolute. | |
387 | newfiles = [repo.wjoin(nf) for nf in newfiles] |
|
387 | newfiles = [repo.wjoin(nf) for nf in newfiles] | |
388 | return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts)) |
|
388 | return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts)) | |
389 | finally: |
|
389 | finally: | |
390 | # 5. finally restore backed-up files |
|
390 | # 5. finally restore backed-up files | |
391 | try: |
|
391 | try: | |
392 | dirstate = repo.dirstate |
|
392 | dirstate = repo.dirstate | |
393 | for realname, tmpname in backups.iteritems(): |
|
393 | for realname, tmpname in backups.iteritems(): | |
394 | ui.debug('restoring %r to %r\n' % (tmpname, realname)) |
|
394 | ui.debug('restoring %r to %r\n' % (tmpname, realname)) | |
395 |
|
395 | |||
396 | if dirstate[realname] == 'n': |
|
396 | if dirstate[realname] == 'n': | |
397 | # without normallookup, restoring timestamp |
|
397 | # without normallookup, restoring timestamp | |
398 | # may cause partially committed files |
|
398 | # may cause partially committed files | |
399 | # to be treated as unmodified |
|
399 | # to be treated as unmodified | |
400 | dirstate.normallookup(realname) |
|
400 | dirstate.normallookup(realname) | |
401 |
|
401 | |||
402 | # copystat=True here and above are a hack to trick any |
|
402 | # copystat=True here and above are a hack to trick any | |
403 | # editors that have f open that we haven't modified them. |
|
403 | # editors that have f open that we haven't modified them. | |
404 | # |
|
404 | # | |
405 | # Also note that this racy as an editor could notice the |
|
405 | # Also note that this racy as an editor could notice the | |
406 | # file's mtime before we've finished writing it. |
|
406 | # file's mtime before we've finished writing it. | |
407 | util.copyfile(tmpname, repo.wjoin(realname), copystat=True) |
|
407 | util.copyfile(tmpname, repo.wjoin(realname), copystat=True) | |
408 | os.unlink(tmpname) |
|
408 | os.unlink(tmpname) | |
409 | if tobackup: |
|
409 | if tobackup: | |
410 | os.rmdir(backupdir) |
|
410 | os.rmdir(backupdir) | |
411 | except OSError: |
|
411 | except OSError: | |
412 | pass |
|
412 | pass | |
413 |
|
413 | |||
414 | def recordinwlock(ui, repo, message, match, opts): |
|
414 | def recordinwlock(ui, repo, message, match, opts): | |
415 | with repo.wlock(): |
|
415 | with repo.wlock(): | |
416 | return recordfunc(ui, repo, message, match, opts) |
|
416 | return recordfunc(ui, repo, message, match, opts) | |
417 |
|
417 | |||
418 | return commit(ui, repo, recordinwlock, pats, opts) |
|
418 | return commit(ui, repo, recordinwlock, pats, opts) | |
419 |
|
419 | |||
420 | class dirnode(object): |
|
420 | class dirnode(object): | |
421 | """ |
|
421 | """ | |
422 | Represent a directory in user working copy with information required for |
|
422 | Represent a directory in user working copy with information required for | |
423 | the purpose of tersing its status. |
|
423 | the purpose of tersing its status. | |
424 |
|
424 | |||
425 | path is the path to the directory, without a trailing '/' |
|
425 | path is the path to the directory, without a trailing '/' | |
426 |
|
426 | |||
427 | statuses is a set of statuses of all files in this directory (this includes |
|
427 | statuses is a set of statuses of all files in this directory (this includes | |
428 | all the files in all the subdirectories too) |
|
428 | all the files in all the subdirectories too) | |
429 |
|
429 | |||
430 | files is a list of files which are direct child of this directory |
|
430 | files is a list of files which are direct child of this directory | |
431 |
|
431 | |||
432 | subdirs is a dictionary of sub-directory name as the key and it's own |
|
432 | subdirs is a dictionary of sub-directory name as the key and it's own | |
433 | dirnode object as the value |
|
433 | dirnode object as the value | |
434 | """ |
|
434 | """ | |
435 |
|
435 | |||
436 | def __init__(self, dirpath): |
|
436 | def __init__(self, dirpath): | |
437 | self.path = dirpath |
|
437 | self.path = dirpath | |
438 | self.statuses = set([]) |
|
438 | self.statuses = set([]) | |
439 | self.files = [] |
|
439 | self.files = [] | |
440 | self.subdirs = {} |
|
440 | self.subdirs = {} | |
441 |
|
441 | |||
442 | def _addfileindir(self, filename, status): |
|
442 | def _addfileindir(self, filename, status): | |
443 | """Add a file in this directory as a direct child.""" |
|
443 | """Add a file in this directory as a direct child.""" | |
444 | self.files.append((filename, status)) |
|
444 | self.files.append((filename, status)) | |
445 |
|
445 | |||
446 | def addfile(self, filename, status): |
|
446 | def addfile(self, filename, status): | |
447 | """ |
|
447 | """ | |
448 | Add a file to this directory or to its direct parent directory. |
|
448 | Add a file to this directory or to its direct parent directory. | |
449 |
|
449 | |||
450 | If the file is not direct child of this directory, we traverse to the |
|
450 | If the file is not direct child of this directory, we traverse to the | |
451 | directory of which this file is a direct child of and add the file |
|
451 | directory of which this file is a direct child of and add the file | |
452 | there. |
|
452 | there. | |
453 | """ |
|
453 | """ | |
454 |
|
454 | |||
455 | # the filename contains a path separator, it means it's not the direct |
|
455 | # the filename contains a path separator, it means it's not the direct | |
456 | # child of this directory |
|
456 | # child of this directory | |
457 | if '/' in filename: |
|
457 | if '/' in filename: | |
458 | subdir, filep = filename.split('/', 1) |
|
458 | subdir, filep = filename.split('/', 1) | |
459 |
|
459 | |||
460 | # does the dirnode object for subdir exists |
|
460 | # does the dirnode object for subdir exists | |
461 | if subdir not in self.subdirs: |
|
461 | if subdir not in self.subdirs: | |
462 | subdirpath = pathutil.join(self.path, subdir) |
|
462 | subdirpath = pathutil.join(self.path, subdir) | |
463 | self.subdirs[subdir] = dirnode(subdirpath) |
|
463 | self.subdirs[subdir] = dirnode(subdirpath) | |
464 |
|
464 | |||
465 | # try adding the file in subdir |
|
465 | # try adding the file in subdir | |
466 | self.subdirs[subdir].addfile(filep, status) |
|
466 | self.subdirs[subdir].addfile(filep, status) | |
467 |
|
467 | |||
468 | else: |
|
468 | else: | |
469 | self._addfileindir(filename, status) |
|
469 | self._addfileindir(filename, status) | |
470 |
|
470 | |||
471 | if status not in self.statuses: |
|
471 | if status not in self.statuses: | |
472 | self.statuses.add(status) |
|
472 | self.statuses.add(status) | |
473 |
|
473 | |||
474 | def iterfilepaths(self): |
|
474 | def iterfilepaths(self): | |
475 | """Yield (status, path) for files directly under this directory.""" |
|
475 | """Yield (status, path) for files directly under this directory.""" | |
476 | for f, st in self.files: |
|
476 | for f, st in self.files: | |
477 | yield st, pathutil.join(self.path, f) |
|
477 | yield st, pathutil.join(self.path, f) | |
478 |
|
478 | |||
479 | def tersewalk(self, terseargs): |
|
479 | def tersewalk(self, terseargs): | |
480 | """ |
|
480 | """ | |
481 | Yield (status, path) obtained by processing the status of this |
|
481 | Yield (status, path) obtained by processing the status of this | |
482 | dirnode. |
|
482 | dirnode. | |
483 |
|
483 | |||
484 | terseargs is the string of arguments passed by the user with `--terse` |
|
484 | terseargs is the string of arguments passed by the user with `--terse` | |
485 | flag. |
|
485 | flag. | |
486 |
|
486 | |||
487 | Following are the cases which can happen: |
|
487 | Following are the cases which can happen: | |
488 |
|
488 | |||
489 | 1) All the files in the directory (including all the files in its |
|
489 | 1) All the files in the directory (including all the files in its | |
490 | subdirectories) share the same status and the user has asked us to terse |
|
490 | subdirectories) share the same status and the user has asked us to terse | |
491 | that status. -> yield (status, dirpath). dirpath will end in '/'. |
|
491 | that status. -> yield (status, dirpath). dirpath will end in '/'. | |
492 |
|
492 | |||
493 | 2) Otherwise, we do following: |
|
493 | 2) Otherwise, we do following: | |
494 |
|
494 | |||
495 | a) Yield (status, filepath) for all the files which are in this |
|
495 | a) Yield (status, filepath) for all the files which are in this | |
496 | directory (only the ones in this directory, not the subdirs) |
|
496 | directory (only the ones in this directory, not the subdirs) | |
497 |
|
497 | |||
498 | b) Recurse the function on all the subdirectories of this |
|
498 | b) Recurse the function on all the subdirectories of this | |
499 | directory |
|
499 | directory | |
500 | """ |
|
500 | """ | |
501 |
|
501 | |||
502 | if len(self.statuses) == 1: |
|
502 | if len(self.statuses) == 1: | |
503 | onlyst = self.statuses.pop() |
|
503 | onlyst = self.statuses.pop() | |
504 |
|
504 | |||
505 | # Making sure we terse only when the status abbreviation is |
|
505 | # Making sure we terse only when the status abbreviation is | |
506 | # passed as terse argument |
|
506 | # passed as terse argument | |
507 | if onlyst in terseargs: |
|
507 | if onlyst in terseargs: | |
508 | yield onlyst, self.path + '/' |
|
508 | yield onlyst, self.path + '/' | |
509 | return |
|
509 | return | |
510 |
|
510 | |||
511 | # add the files to status list |
|
511 | # add the files to status list | |
512 | for st, fpath in self.iterfilepaths(): |
|
512 | for st, fpath in self.iterfilepaths(): | |
513 | yield st, fpath |
|
513 | yield st, fpath | |
514 |
|
514 | |||
515 | #recurse on the subdirs |
|
515 | #recurse on the subdirs | |
516 | for dirobj in self.subdirs.values(): |
|
516 | for dirobj in self.subdirs.values(): | |
517 | for st, fpath in dirobj.tersewalk(terseargs): |
|
517 | for st, fpath in dirobj.tersewalk(terseargs): | |
518 | yield st, fpath |
|
518 | yield st, fpath | |
519 |
|
519 | |||
520 | def tersedir(statuslist, terseargs): |
|
520 | def tersedir(statuslist, terseargs): | |
521 | """ |
|
521 | """ | |
522 | Terse the status if all the files in a directory shares the same status. |
|
522 | Terse the status if all the files in a directory shares the same status. | |
523 |
|
523 | |||
524 | statuslist is scmutil.status() object which contains a list of files for |
|
524 | statuslist is scmutil.status() object which contains a list of files for | |
525 | each status. |
|
525 | each status. | |
526 | terseargs is string which is passed by the user as the argument to `--terse` |
|
526 | terseargs is string which is passed by the user as the argument to `--terse` | |
527 | flag. |
|
527 | flag. | |
528 |
|
528 | |||
529 | The function makes a tree of objects of dirnode class, and at each node it |
|
529 | The function makes a tree of objects of dirnode class, and at each node it | |
530 | stores the information required to know whether we can terse a certain |
|
530 | stores the information required to know whether we can terse a certain | |
531 | directory or not. |
|
531 | directory or not. | |
532 | """ |
|
532 | """ | |
533 | # the order matters here as that is used to produce final list |
|
533 | # the order matters here as that is used to produce final list | |
534 | allst = ('m', 'a', 'r', 'd', 'u', 'i', 'c') |
|
534 | allst = ('m', 'a', 'r', 'd', 'u', 'i', 'c') | |
535 |
|
535 | |||
536 | # checking the argument validity |
|
536 | # checking the argument validity | |
537 | for s in pycompat.bytestr(terseargs): |
|
537 | for s in pycompat.bytestr(terseargs): | |
538 | if s not in allst: |
|
538 | if s not in allst: | |
539 | raise error.Abort(_("'%s' not recognized") % s) |
|
539 | raise error.Abort(_("'%s' not recognized") % s) | |
540 |
|
540 | |||
541 | # creating a dirnode object for the root of the repo |
|
541 | # creating a dirnode object for the root of the repo | |
542 | rootobj = dirnode('') |
|
542 | rootobj = dirnode('') | |
543 | pstatus = ('modified', 'added', 'deleted', 'clean', 'unknown', |
|
543 | pstatus = ('modified', 'added', 'deleted', 'clean', 'unknown', | |
544 | 'ignored', 'removed') |
|
544 | 'ignored', 'removed') | |
545 |
|
545 | |||
546 | tersedict = {} |
|
546 | tersedict = {} | |
547 | for attrname in pstatus: |
|
547 | for attrname in pstatus: | |
548 | statuschar = attrname[0:1] |
|
548 | statuschar = attrname[0:1] | |
549 | for f in getattr(statuslist, attrname): |
|
549 | for f in getattr(statuslist, attrname): | |
550 | rootobj.addfile(f, statuschar) |
|
550 | rootobj.addfile(f, statuschar) | |
551 | tersedict[statuschar] = [] |
|
551 | tersedict[statuschar] = [] | |
552 |
|
552 | |||
553 | # we won't be tersing the root dir, so add files in it |
|
553 | # we won't be tersing the root dir, so add files in it | |
554 | for st, fpath in rootobj.iterfilepaths(): |
|
554 | for st, fpath in rootobj.iterfilepaths(): | |
555 | tersedict[st].append(fpath) |
|
555 | tersedict[st].append(fpath) | |
556 |
|
556 | |||
557 | # process each sub-directory and build tersedict |
|
557 | # process each sub-directory and build tersedict | |
558 | for subdir in rootobj.subdirs.values(): |
|
558 | for subdir in rootobj.subdirs.values(): | |
559 | for st, f in subdir.tersewalk(terseargs): |
|
559 | for st, f in subdir.tersewalk(terseargs): | |
560 | tersedict[st].append(f) |
|
560 | tersedict[st].append(f) | |
561 |
|
561 | |||
562 | tersedlist = [] |
|
562 | tersedlist = [] | |
563 | for st in allst: |
|
563 | for st in allst: | |
564 | tersedict[st].sort() |
|
564 | tersedict[st].sort() | |
565 | tersedlist.append(tersedict[st]) |
|
565 | tersedlist.append(tersedict[st]) | |
566 |
|
566 | |||
567 | return tersedlist |
|
567 | return tersedlist | |
568 |
|
568 | |||
569 | def _commentlines(raw): |
|
569 | def _commentlines(raw): | |
570 | '''Surround lineswith a comment char and a new line''' |
|
570 | '''Surround lineswith a comment char and a new line''' | |
571 | lines = raw.splitlines() |
|
571 | lines = raw.splitlines() | |
572 | commentedlines = ['# %s' % line for line in lines] |
|
572 | commentedlines = ['# %s' % line for line in lines] | |
573 | return '\n'.join(commentedlines) + '\n' |
|
573 | return '\n'.join(commentedlines) + '\n' | |
574 |
|
574 | |||
575 | def _conflictsmsg(repo): |
|
575 | def _conflictsmsg(repo): | |
576 | mergestate = mergemod.mergestate.read(repo) |
|
576 | mergestate = mergemod.mergestate.read(repo) | |
577 | if not mergestate.active(): |
|
577 | if not mergestate.active(): | |
578 | return |
|
578 | return | |
579 |
|
579 | |||
580 | m = scmutil.match(repo[None]) |
|
580 | m = scmutil.match(repo[None]) | |
581 | unresolvedlist = [f for f in mergestate.unresolved() if m(f)] |
|
581 | unresolvedlist = [f for f in mergestate.unresolved() if m(f)] | |
582 | if unresolvedlist: |
|
582 | if unresolvedlist: | |
583 | mergeliststr = '\n'.join( |
|
583 | mergeliststr = '\n'.join( | |
584 | [' %s' % util.pathto(repo.root, pycompat.getcwd(), path) |
|
584 | [' %s' % util.pathto(repo.root, pycompat.getcwd(), path) | |
585 | for path in unresolvedlist]) |
|
585 | for path in unresolvedlist]) | |
586 | msg = _('''Unresolved merge conflicts: |
|
586 | msg = _('''Unresolved merge conflicts: | |
587 |
|
587 | |||
588 | %s |
|
588 | %s | |
589 |
|
589 | |||
590 | To mark files as resolved: hg resolve --mark FILE''') % mergeliststr |
|
590 | To mark files as resolved: hg resolve --mark FILE''') % mergeliststr | |
591 | else: |
|
591 | else: | |
592 | msg = _('No unresolved merge conflicts.') |
|
592 | msg = _('No unresolved merge conflicts.') | |
593 |
|
593 | |||
594 | return _commentlines(msg) |
|
594 | return _commentlines(msg) | |
595 |
|
595 | |||
596 | def _helpmessage(continuecmd, abortcmd): |
|
596 | def _helpmessage(continuecmd, abortcmd): | |
597 | msg = _('To continue: %s\n' |
|
597 | msg = _('To continue: %s\n' | |
598 | 'To abort: %s') % (continuecmd, abortcmd) |
|
598 | 'To abort: %s') % (continuecmd, abortcmd) | |
599 | return _commentlines(msg) |
|
599 | return _commentlines(msg) | |
600 |
|
600 | |||
601 | def _rebasemsg(): |
|
601 | def _rebasemsg(): | |
602 | return _helpmessage('hg rebase --continue', 'hg rebase --abort') |
|
602 | return _helpmessage('hg rebase --continue', 'hg rebase --abort') | |
603 |
|
603 | |||
604 | def _histeditmsg(): |
|
604 | def _histeditmsg(): | |
605 | return _helpmessage('hg histedit --continue', 'hg histedit --abort') |
|
605 | return _helpmessage('hg histedit --continue', 'hg histedit --abort') | |
606 |
|
606 | |||
607 | def _unshelvemsg(): |
|
607 | def _unshelvemsg(): | |
608 | return _helpmessage('hg unshelve --continue', 'hg unshelve --abort') |
|
608 | return _helpmessage('hg unshelve --continue', 'hg unshelve --abort') | |
609 |
|
609 | |||
610 | def _graftmsg(): |
|
610 | def _graftmsg(): | |
611 | # tweakdefaults requires `update` to have a rev hence the `.` |
|
611 | # tweakdefaults requires `update` to have a rev hence the `.` | |
612 | return _helpmessage('hg graft --continue', 'hg graft --abort') |
|
612 | return _helpmessage('hg graft --continue', 'hg graft --abort') | |
613 |
|
613 | |||
614 | def _mergemsg(): |
|
614 | def _mergemsg(): | |
615 | # tweakdefaults requires `update` to have a rev hence the `.` |
|
615 | # tweakdefaults requires `update` to have a rev hence the `.` | |
616 | return _helpmessage('hg commit', 'hg merge --abort') |
|
616 | return _helpmessage('hg commit', 'hg merge --abort') | |
617 |
|
617 | |||
618 | def _bisectmsg(): |
|
618 | def _bisectmsg(): | |
619 | msg = _('To mark the changeset good: hg bisect --good\n' |
|
619 | msg = _('To mark the changeset good: hg bisect --good\n' | |
620 | 'To mark the changeset bad: hg bisect --bad\n' |
|
620 | 'To mark the changeset bad: hg bisect --bad\n' | |
621 | 'To abort: hg bisect --reset\n') |
|
621 | 'To abort: hg bisect --reset\n') | |
622 | return _commentlines(msg) |
|
622 | return _commentlines(msg) | |
623 |
|
623 | |||
624 | def fileexistspredicate(filename): |
|
624 | def fileexistspredicate(filename): | |
625 | return lambda repo: repo.vfs.exists(filename) |
|
625 | return lambda repo: repo.vfs.exists(filename) | |
626 |
|
626 | |||
627 | def _mergepredicate(repo): |
|
627 | def _mergepredicate(repo): | |
628 | return len(repo[None].parents()) > 1 |
|
628 | return len(repo[None].parents()) > 1 | |
629 |
|
629 | |||
630 | STATES = ( |
|
630 | STATES = ( | |
631 | # (state, predicate to detect states, helpful message function) |
|
631 | # (state, predicate to detect states, helpful message function) | |
632 | ('histedit', fileexistspredicate('histedit-state'), _histeditmsg), |
|
632 | ('histedit', fileexistspredicate('histedit-state'), _histeditmsg), | |
633 | ('bisect', fileexistspredicate('bisect.state'), _bisectmsg), |
|
633 | ('bisect', fileexistspredicate('bisect.state'), _bisectmsg), | |
634 | ('graft', fileexistspredicate('graftstate'), _graftmsg), |
|
634 | ('graft', fileexistspredicate('graftstate'), _graftmsg), | |
635 | ('unshelve', fileexistspredicate('shelvedstate'), _unshelvemsg), |
|
635 | ('unshelve', fileexistspredicate('shelvedstate'), _unshelvemsg), | |
636 | ('rebase', fileexistspredicate('rebasestate'), _rebasemsg), |
|
636 | ('rebase', fileexistspredicate('rebasestate'), _rebasemsg), | |
637 | # The merge state is part of a list that will be iterated over. |
|
637 | # The merge state is part of a list that will be iterated over. | |
638 | # They need to be last because some of the other unfinished states may also |
|
638 | # They need to be last because some of the other unfinished states may also | |
639 | # be in a merge or update state (eg. rebase, histedit, graft, etc). |
|
639 | # be in a merge or update state (eg. rebase, histedit, graft, etc). | |
640 | # We want those to have priority. |
|
640 | # We want those to have priority. | |
641 | ('merge', _mergepredicate, _mergemsg), |
|
641 | ('merge', _mergepredicate, _mergemsg), | |
642 | ) |
|
642 | ) | |
643 |
|
643 | |||
644 | def _getrepostate(repo): |
|
644 | def _getrepostate(repo): | |
645 | # experimental config: commands.status.skipstates |
|
645 | # experimental config: commands.status.skipstates | |
646 | skip = set(repo.ui.configlist('commands', 'status.skipstates')) |
|
646 | skip = set(repo.ui.configlist('commands', 'status.skipstates')) | |
647 | for state, statedetectionpredicate, msgfn in STATES: |
|
647 | for state, statedetectionpredicate, msgfn in STATES: | |
648 | if state in skip: |
|
648 | if state in skip: | |
649 | continue |
|
649 | continue | |
650 | if statedetectionpredicate(repo): |
|
650 | if statedetectionpredicate(repo): | |
651 | return (state, statedetectionpredicate, msgfn) |
|
651 | return (state, statedetectionpredicate, msgfn) | |
652 |
|
652 | |||
653 | def morestatus(repo, fm): |
|
653 | def morestatus(repo, fm): | |
654 | statetuple = _getrepostate(repo) |
|
654 | statetuple = _getrepostate(repo) | |
655 | label = 'status.morestatus' |
|
655 | label = 'status.morestatus' | |
656 | if statetuple: |
|
656 | if statetuple: | |
657 | fm.startitem() |
|
657 | fm.startitem() | |
658 | state, statedetectionpredicate, helpfulmsg = statetuple |
|
658 | state, statedetectionpredicate, helpfulmsg = statetuple | |
659 | statemsg = _('The repository is in an unfinished *%s* state.') % state |
|
659 | statemsg = _('The repository is in an unfinished *%s* state.') % state | |
660 | fm.write('statemsg', '%s\n', _commentlines(statemsg), label=label) |
|
660 | fm.write('statemsg', '%s\n', _commentlines(statemsg), label=label) | |
661 | conmsg = _conflictsmsg(repo) |
|
661 | conmsg = _conflictsmsg(repo) | |
662 | if conmsg: |
|
662 | if conmsg: | |
663 | fm.write('conflictsmsg', '%s\n', conmsg, label=label) |
|
663 | fm.write('conflictsmsg', '%s\n', conmsg, label=label) | |
664 | if helpfulmsg: |
|
664 | if helpfulmsg: | |
665 | helpmsg = helpfulmsg() |
|
665 | helpmsg = helpfulmsg() | |
666 | fm.write('helpmsg', '%s\n', helpmsg, label=label) |
|
666 | fm.write('helpmsg', '%s\n', helpmsg, label=label) | |
667 |
|
667 | |||
668 | def findpossible(cmd, table, strict=False): |
|
668 | def findpossible(cmd, table, strict=False): | |
669 | """ |
|
669 | """ | |
670 | Return cmd -> (aliases, command table entry) |
|
670 | Return cmd -> (aliases, command table entry) | |
671 | for each matching command. |
|
671 | for each matching command. | |
672 | Return debug commands (or their aliases) only if no normal command matches. |
|
672 | Return debug commands (or their aliases) only if no normal command matches. | |
673 | """ |
|
673 | """ | |
674 | choice = {} |
|
674 | choice = {} | |
675 | debugchoice = {} |
|
675 | debugchoice = {} | |
676 |
|
676 | |||
677 | if cmd in table: |
|
677 | if cmd in table: | |
678 | # short-circuit exact matches, "log" alias beats "^log|history" |
|
678 | # short-circuit exact matches, "log" alias beats "^log|history" | |
679 | keys = [cmd] |
|
679 | keys = [cmd] | |
680 | else: |
|
680 | else: | |
681 | keys = table.keys() |
|
681 | keys = table.keys() | |
682 |
|
682 | |||
683 | allcmds = [] |
|
683 | allcmds = [] | |
684 | for e in keys: |
|
684 | for e in keys: | |
685 | aliases = parsealiases(e) |
|
685 | aliases = parsealiases(e) | |
686 | allcmds.extend(aliases) |
|
686 | allcmds.extend(aliases) | |
687 | found = None |
|
687 | found = None | |
688 | if cmd in aliases: |
|
688 | if cmd in aliases: | |
689 | found = cmd |
|
689 | found = cmd | |
690 | elif not strict: |
|
690 | elif not strict: | |
691 | for a in aliases: |
|
691 | for a in aliases: | |
692 | if a.startswith(cmd): |
|
692 | if a.startswith(cmd): | |
693 | found = a |
|
693 | found = a | |
694 | break |
|
694 | break | |
695 | if found is not None: |
|
695 | if found is not None: | |
696 | if aliases[0].startswith("debug") or found.startswith("debug"): |
|
696 | if aliases[0].startswith("debug") or found.startswith("debug"): | |
697 | debugchoice[found] = (aliases, table[e]) |
|
697 | debugchoice[found] = (aliases, table[e]) | |
698 | else: |
|
698 | else: | |
699 | choice[found] = (aliases, table[e]) |
|
699 | choice[found] = (aliases, table[e]) | |
700 |
|
700 | |||
701 | if not choice and debugchoice: |
|
701 | if not choice and debugchoice: | |
702 | choice = debugchoice |
|
702 | choice = debugchoice | |
703 |
|
703 | |||
704 | return choice, allcmds |
|
704 | return choice, allcmds | |
705 |
|
705 | |||
706 | def findcmd(cmd, table, strict=True): |
|
706 | def findcmd(cmd, table, strict=True): | |
707 | """Return (aliases, command table entry) for command string.""" |
|
707 | """Return (aliases, command table entry) for command string.""" | |
708 | choice, allcmds = findpossible(cmd, table, strict) |
|
708 | choice, allcmds = findpossible(cmd, table, strict) | |
709 |
|
709 | |||
710 | if cmd in choice: |
|
710 | if cmd in choice: | |
711 | return choice[cmd] |
|
711 | return choice[cmd] | |
712 |
|
712 | |||
713 | if len(choice) > 1: |
|
713 | if len(choice) > 1: | |
714 | clist = sorted(choice) |
|
714 | clist = sorted(choice) | |
715 | raise error.AmbiguousCommand(cmd, clist) |
|
715 | raise error.AmbiguousCommand(cmd, clist) | |
716 |
|
716 | |||
717 | if choice: |
|
717 | if choice: | |
718 | return list(choice.values())[0] |
|
718 | return list(choice.values())[0] | |
719 |
|
719 | |||
720 | raise error.UnknownCommand(cmd, allcmds) |
|
720 | raise error.UnknownCommand(cmd, allcmds) | |
721 |
|
721 | |||
722 | def changebranch(ui, repo, revs, label): |
|
722 | def changebranch(ui, repo, revs, label): | |
723 | """ Change the branch name of given revs to label """ |
|
723 | """ Change the branch name of given revs to label """ | |
724 |
|
724 | |||
725 | with repo.wlock(), repo.lock(), repo.transaction('branches'): |
|
725 | with repo.wlock(), repo.lock(), repo.transaction('branches'): | |
726 | # abort in case of uncommitted merge or dirty wdir |
|
726 | # abort in case of uncommitted merge or dirty wdir | |
727 | bailifchanged(repo) |
|
727 | bailifchanged(repo) | |
728 | revs = scmutil.revrange(repo, revs) |
|
728 | revs = scmutil.revrange(repo, revs) | |
729 | if not revs: |
|
729 | if not revs: | |
730 | raise error.Abort("empty revision set") |
|
730 | raise error.Abort("empty revision set") | |
731 | roots = repo.revs('roots(%ld)', revs) |
|
731 | roots = repo.revs('roots(%ld)', revs) | |
732 | if len(roots) > 1: |
|
732 | if len(roots) > 1: | |
733 | raise error.Abort(_("cannot change branch of non-linear revisions")) |
|
733 | raise error.Abort(_("cannot change branch of non-linear revisions")) | |
734 | rewriteutil.precheck(repo, revs, 'change branch of') |
|
734 | rewriteutil.precheck(repo, revs, 'change branch of') | |
735 |
|
735 | |||
736 | root = repo[roots.first()] |
|
736 | root = repo[roots.first()] | |
737 | if not root.p1().branch() == label and label in repo.branchmap(): |
|
737 | if not root.p1().branch() == label and label in repo.branchmap(): | |
738 | raise error.Abort(_("a branch of the same name already exists")) |
|
738 | raise error.Abort(_("a branch of the same name already exists")) | |
739 |
|
739 | |||
740 | if repo.revs('merge() and %ld', revs): |
|
740 | if repo.revs('merge() and %ld', revs): | |
741 | raise error.Abort(_("cannot change branch of a merge commit")) |
|
741 | raise error.Abort(_("cannot change branch of a merge commit")) | |
742 | if repo.revs('obsolete() and %ld', revs): |
|
742 | if repo.revs('obsolete() and %ld', revs): | |
743 | raise error.Abort(_("cannot change branch of a obsolete changeset")) |
|
743 | raise error.Abort(_("cannot change branch of a obsolete changeset")) | |
744 |
|
744 | |||
745 | # make sure only topological heads |
|
745 | # make sure only topological heads | |
746 | if repo.revs('heads(%ld) - head()', revs): |
|
746 | if repo.revs('heads(%ld) - head()', revs): | |
747 | raise error.Abort(_("cannot change branch in middle of a stack")) |
|
747 | raise error.Abort(_("cannot change branch in middle of a stack")) | |
748 |
|
748 | |||
749 | replacements = {} |
|
749 | replacements = {} | |
750 | # avoid import cycle mercurial.cmdutil -> mercurial.context -> |
|
750 | # avoid import cycle mercurial.cmdutil -> mercurial.context -> | |
751 | # mercurial.subrepo -> mercurial.cmdutil |
|
751 | # mercurial.subrepo -> mercurial.cmdutil | |
752 | from . import context |
|
752 | from . import context | |
753 | for rev in revs: |
|
753 | for rev in revs: | |
754 | ctx = repo[rev] |
|
754 | ctx = repo[rev] | |
755 | oldbranch = ctx.branch() |
|
755 | oldbranch = ctx.branch() | |
756 | # check if ctx has same branch |
|
756 | # check if ctx has same branch | |
757 | if oldbranch == label: |
|
757 | if oldbranch == label: | |
758 | continue |
|
758 | continue | |
759 |
|
759 | |||
760 | def filectxfn(repo, newctx, path): |
|
760 | def filectxfn(repo, newctx, path): | |
761 | try: |
|
761 | try: | |
762 | return ctx[path] |
|
762 | return ctx[path] | |
763 | except error.ManifestLookupError: |
|
763 | except error.ManifestLookupError: | |
764 | return None |
|
764 | return None | |
765 |
|
765 | |||
766 | ui.debug("changing branch of '%s' from '%s' to '%s'\n" |
|
766 | ui.debug("changing branch of '%s' from '%s' to '%s'\n" | |
767 | % (hex(ctx.node()), oldbranch, label)) |
|
767 | % (hex(ctx.node()), oldbranch, label)) | |
768 | extra = ctx.extra() |
|
768 | extra = ctx.extra() | |
769 | extra['branch_change'] = hex(ctx.node()) |
|
769 | extra['branch_change'] = hex(ctx.node()) | |
770 | # While changing branch of set of linear commits, make sure that |
|
770 | # While changing branch of set of linear commits, make sure that | |
771 | # we base our commits on new parent rather than old parent which |
|
771 | # we base our commits on new parent rather than old parent which | |
772 | # was obsoleted while changing the branch |
|
772 | # was obsoleted while changing the branch | |
773 | p1 = ctx.p1().node() |
|
773 | p1 = ctx.p1().node() | |
774 | p2 = ctx.p2().node() |
|
774 | p2 = ctx.p2().node() | |
775 | if p1 in replacements: |
|
775 | if p1 in replacements: | |
776 | p1 = replacements[p1][0] |
|
776 | p1 = replacements[p1][0] | |
777 | if p2 in replacements: |
|
777 | if p2 in replacements: | |
778 | p2 = replacements[p2][0] |
|
778 | p2 = replacements[p2][0] | |
779 |
|
779 | |||
780 | mc = context.memctx(repo, (p1, p2), |
|
780 | mc = context.memctx(repo, (p1, p2), | |
781 | ctx.description(), |
|
781 | ctx.description(), | |
782 | ctx.files(), |
|
782 | ctx.files(), | |
783 | filectxfn, |
|
783 | filectxfn, | |
784 | user=ctx.user(), |
|
784 | user=ctx.user(), | |
785 | date=ctx.date(), |
|
785 | date=ctx.date(), | |
786 | extra=extra, |
|
786 | extra=extra, | |
787 | branch=label) |
|
787 | branch=label) | |
788 |
|
788 | |||
789 | newnode = repo.commitctx(mc) |
|
789 | newnode = repo.commitctx(mc) | |
790 | replacements[ctx.node()] = (newnode,) |
|
790 | replacements[ctx.node()] = (newnode,) | |
791 | ui.debug('new node id is %s\n' % hex(newnode)) |
|
791 | ui.debug('new node id is %s\n' % hex(newnode)) | |
792 |
|
792 | |||
793 | # create obsmarkers and move bookmarks |
|
793 | # create obsmarkers and move bookmarks | |
794 | scmutil.cleanupnodes(repo, replacements, 'branch-change', fixphase=True) |
|
794 | scmutil.cleanupnodes(repo, replacements, 'branch-change', fixphase=True) | |
795 |
|
795 | |||
796 | # move the working copy too |
|
796 | # move the working copy too | |
797 | wctx = repo[None] |
|
797 | wctx = repo[None] | |
798 | # in-progress merge is a bit too complex for now. |
|
798 | # in-progress merge is a bit too complex for now. | |
799 | if len(wctx.parents()) == 1: |
|
799 | if len(wctx.parents()) == 1: | |
800 | newid = replacements.get(wctx.p1().node()) |
|
800 | newid = replacements.get(wctx.p1().node()) | |
801 | if newid is not None: |
|
801 | if newid is not None: | |
802 | # avoid import cycle mercurial.cmdutil -> mercurial.hg -> |
|
802 | # avoid import cycle mercurial.cmdutil -> mercurial.hg -> | |
803 | # mercurial.cmdutil |
|
803 | # mercurial.cmdutil | |
804 | from . import hg |
|
804 | from . import hg | |
805 | hg.update(repo, newid[0], quietempty=True) |
|
805 | hg.update(repo, newid[0], quietempty=True) | |
806 |
|
806 | |||
807 | ui.status(_("changed branch on %d changesets\n") % len(replacements)) |
|
807 | ui.status(_("changed branch on %d changesets\n") % len(replacements)) | |
808 |
|
808 | |||
809 | def findrepo(p): |
|
809 | def findrepo(p): | |
810 | while not os.path.isdir(os.path.join(p, ".hg")): |
|
810 | while not os.path.isdir(os.path.join(p, ".hg")): | |
811 | oldp, p = p, os.path.dirname(p) |
|
811 | oldp, p = p, os.path.dirname(p) | |
812 | if p == oldp: |
|
812 | if p == oldp: | |
813 | return None |
|
813 | return None | |
814 |
|
814 | |||
815 | return p |
|
815 | return p | |
816 |
|
816 | |||
817 | def bailifchanged(repo, merge=True, hint=None): |
|
817 | def bailifchanged(repo, merge=True, hint=None): | |
818 | """ enforce the precondition that working directory must be clean. |
|
818 | """ enforce the precondition that working directory must be clean. | |
819 |
|
819 | |||
820 | 'merge' can be set to false if a pending uncommitted merge should be |
|
820 | 'merge' can be set to false if a pending uncommitted merge should be | |
821 | ignored (such as when 'update --check' runs). |
|
821 | ignored (such as when 'update --check' runs). | |
822 |
|
822 | |||
823 | 'hint' is the usual hint given to Abort exception. |
|
823 | 'hint' is the usual hint given to Abort exception. | |
824 | """ |
|
824 | """ | |
825 |
|
825 | |||
826 | if merge and repo.dirstate.p2() != nullid: |
|
826 | if merge and repo.dirstate.p2() != nullid: | |
827 | raise error.Abort(_('outstanding uncommitted merge'), hint=hint) |
|
827 | raise error.Abort(_('outstanding uncommitted merge'), hint=hint) | |
828 | modified, added, removed, deleted = repo.status()[:4] |
|
828 | modified, added, removed, deleted = repo.status()[:4] | |
829 | if modified or added or removed or deleted: |
|
829 | if modified or added or removed or deleted: | |
830 | raise error.Abort(_('uncommitted changes'), hint=hint) |
|
830 | raise error.Abort(_('uncommitted changes'), hint=hint) | |
831 | ctx = repo[None] |
|
831 | ctx = repo[None] | |
832 | for s in sorted(ctx.substate): |
|
832 | for s in sorted(ctx.substate): | |
833 | ctx.sub(s).bailifchanged(hint=hint) |
|
833 | ctx.sub(s).bailifchanged(hint=hint) | |
834 |
|
834 | |||
835 | def logmessage(ui, opts): |
|
835 | def logmessage(ui, opts): | |
836 | """ get the log message according to -m and -l option """ |
|
836 | """ get the log message according to -m and -l option """ | |
837 | message = opts.get('message') |
|
837 | message = opts.get('message') | |
838 | logfile = opts.get('logfile') |
|
838 | logfile = opts.get('logfile') | |
839 |
|
839 | |||
840 | if message and logfile: |
|
840 | if message and logfile: | |
841 | raise error.Abort(_('options --message and --logfile are mutually ' |
|
841 | raise error.Abort(_('options --message and --logfile are mutually ' | |
842 | 'exclusive')) |
|
842 | 'exclusive')) | |
843 | if not message and logfile: |
|
843 | if not message and logfile: | |
844 | try: |
|
844 | try: | |
845 | if isstdiofilename(logfile): |
|
845 | if isstdiofilename(logfile): | |
846 | message = ui.fin.read() |
|
846 | message = ui.fin.read() | |
847 | else: |
|
847 | else: | |
848 | message = '\n'.join(util.readfile(logfile).splitlines()) |
|
848 | message = '\n'.join(util.readfile(logfile).splitlines()) | |
849 | except IOError as inst: |
|
849 | except IOError as inst: | |
850 | raise error.Abort(_("can't read commit message '%s': %s") % |
|
850 | raise error.Abort(_("can't read commit message '%s': %s") % | |
851 | (logfile, encoding.strtolocal(inst.strerror))) |
|
851 | (logfile, encoding.strtolocal(inst.strerror))) | |
852 | return message |
|
852 | return message | |
853 |
|
853 | |||
854 | def mergeeditform(ctxorbool, baseformname): |
|
854 | def mergeeditform(ctxorbool, baseformname): | |
855 | """return appropriate editform name (referencing a committemplate) |
|
855 | """return appropriate editform name (referencing a committemplate) | |
856 |
|
856 | |||
857 | 'ctxorbool' is either a ctx to be committed, or a bool indicating whether |
|
857 | 'ctxorbool' is either a ctx to be committed, or a bool indicating whether | |
858 | merging is committed. |
|
858 | merging is committed. | |
859 |
|
859 | |||
860 | This returns baseformname with '.merge' appended if it is a merge, |
|
860 | This returns baseformname with '.merge' appended if it is a merge, | |
861 | otherwise '.normal' is appended. |
|
861 | otherwise '.normal' is appended. | |
862 | """ |
|
862 | """ | |
863 | if isinstance(ctxorbool, bool): |
|
863 | if isinstance(ctxorbool, bool): | |
864 | if ctxorbool: |
|
864 | if ctxorbool: | |
865 | return baseformname + ".merge" |
|
865 | return baseformname + ".merge" | |
866 | elif 1 < len(ctxorbool.parents()): |
|
866 | elif 1 < len(ctxorbool.parents()): | |
867 | return baseformname + ".merge" |
|
867 | return baseformname + ".merge" | |
868 |
|
868 | |||
869 | return baseformname + ".normal" |
|
869 | return baseformname + ".normal" | |
870 |
|
870 | |||
871 | def getcommiteditor(edit=False, finishdesc=None, extramsg=None, |
|
871 | def getcommiteditor(edit=False, finishdesc=None, extramsg=None, | |
872 | editform='', **opts): |
|
872 | editform='', **opts): | |
873 | """get appropriate commit message editor according to '--edit' option |
|
873 | """get appropriate commit message editor according to '--edit' option | |
874 |
|
874 | |||
875 | 'finishdesc' is a function to be called with edited commit message |
|
875 | 'finishdesc' is a function to be called with edited commit message | |
876 | (= 'description' of the new changeset) just after editing, but |
|
876 | (= 'description' of the new changeset) just after editing, but | |
877 | before checking empty-ness. It should return actual text to be |
|
877 | before checking empty-ness. It should return actual text to be | |
878 | stored into history. This allows to change description before |
|
878 | stored into history. This allows to change description before | |
879 | storing. |
|
879 | storing. | |
880 |
|
880 | |||
881 | 'extramsg' is a extra message to be shown in the editor instead of |
|
881 | 'extramsg' is a extra message to be shown in the editor instead of | |
882 | 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL |
|
882 | 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL | |
883 | is automatically added. |
|
883 | is automatically added. | |
884 |
|
884 | |||
885 | 'editform' is a dot-separated list of names, to distinguish |
|
885 | 'editform' is a dot-separated list of names, to distinguish | |
886 | the purpose of commit text editing. |
|
886 | the purpose of commit text editing. | |
887 |
|
887 | |||
888 | 'getcommiteditor' returns 'commitforceeditor' regardless of |
|
888 | 'getcommiteditor' returns 'commitforceeditor' regardless of | |
889 | 'edit', if one of 'finishdesc' or 'extramsg' is specified, because |
|
889 | 'edit', if one of 'finishdesc' or 'extramsg' is specified, because | |
890 | they are specific for usage in MQ. |
|
890 | they are specific for usage in MQ. | |
891 | """ |
|
891 | """ | |
892 | if edit or finishdesc or extramsg: |
|
892 | if edit or finishdesc or extramsg: | |
893 | return lambda r, c, s: commitforceeditor(r, c, s, |
|
893 | return lambda r, c, s: commitforceeditor(r, c, s, | |
894 | finishdesc=finishdesc, |
|
894 | finishdesc=finishdesc, | |
895 | extramsg=extramsg, |
|
895 | extramsg=extramsg, | |
896 | editform=editform) |
|
896 | editform=editform) | |
897 | elif editform: |
|
897 | elif editform: | |
898 | return lambda r, c, s: commiteditor(r, c, s, editform=editform) |
|
898 | return lambda r, c, s: commiteditor(r, c, s, editform=editform) | |
899 | else: |
|
899 | else: | |
900 | return commiteditor |
|
900 | return commiteditor | |
901 |
|
901 | |||
902 | def _escapecommandtemplate(tmpl): |
|
902 | def _escapecommandtemplate(tmpl): | |
903 | parts = [] |
|
903 | parts = [] | |
904 | for typ, start, end in templater.scantemplate(tmpl, raw=True): |
|
904 | for typ, start, end in templater.scantemplate(tmpl, raw=True): | |
905 | if typ == b'string': |
|
905 | if typ == b'string': | |
906 | parts.append(stringutil.escapestr(tmpl[start:end])) |
|
906 | parts.append(stringutil.escapestr(tmpl[start:end])) | |
907 | else: |
|
907 | else: | |
908 | parts.append(tmpl[start:end]) |
|
908 | parts.append(tmpl[start:end]) | |
909 | return b''.join(parts) |
|
909 | return b''.join(parts) | |
910 |
|
910 | |||
911 | def rendercommandtemplate(ui, tmpl, props): |
|
911 | def rendercommandtemplate(ui, tmpl, props): | |
912 | r"""Expand a literal template 'tmpl' in a way suitable for command line |
|
912 | r"""Expand a literal template 'tmpl' in a way suitable for command line | |
913 |
|
913 | |||
914 | '\' in outermost string is not taken as an escape character because it |
|
914 | '\' in outermost string is not taken as an escape character because it | |
915 | is a directory separator on Windows. |
|
915 | is a directory separator on Windows. | |
916 |
|
916 | |||
917 | >>> from . import ui as uimod |
|
917 | >>> from . import ui as uimod | |
918 | >>> ui = uimod.ui() |
|
918 | >>> ui = uimod.ui() | |
919 | >>> rendercommandtemplate(ui, b'c:\\{path}', {b'path': b'foo'}) |
|
919 | >>> rendercommandtemplate(ui, b'c:\\{path}', {b'path': b'foo'}) | |
920 | 'c:\\foo' |
|
920 | 'c:\\foo' | |
921 | >>> rendercommandtemplate(ui, b'{"c:\\{path}"}', {'path': b'foo'}) |
|
921 | >>> rendercommandtemplate(ui, b'{"c:\\{path}"}', {'path': b'foo'}) | |
922 | 'c:{path}' |
|
922 | 'c:{path}' | |
923 | """ |
|
923 | """ | |
924 | if not tmpl: |
|
924 | if not tmpl: | |
925 | return tmpl |
|
925 | return tmpl | |
926 | t = formatter.maketemplater(ui, _escapecommandtemplate(tmpl)) |
|
926 | t = formatter.maketemplater(ui, _escapecommandtemplate(tmpl)) | |
927 | return t.renderdefault(props) |
|
927 | return t.renderdefault(props) | |
928 |
|
928 | |||
929 | def rendertemplate(ctx, tmpl, props=None): |
|
929 | def rendertemplate(ctx, tmpl, props=None): | |
930 | """Expand a literal template 'tmpl' byte-string against one changeset |
|
930 | """Expand a literal template 'tmpl' byte-string against one changeset | |
931 |
|
931 | |||
932 | Each props item must be a stringify-able value or a callable returning |
|
932 | Each props item must be a stringify-able value or a callable returning | |
933 | such value, i.e. no bare list nor dict should be passed. |
|
933 | such value, i.e. no bare list nor dict should be passed. | |
934 | """ |
|
934 | """ | |
935 | repo = ctx.repo() |
|
935 | repo = ctx.repo() | |
936 | tres = formatter.templateresources(repo.ui, repo) |
|
936 | tres = formatter.templateresources(repo.ui, repo) | |
937 | t = formatter.maketemplater(repo.ui, tmpl, defaults=templatekw.keywords, |
|
937 | t = formatter.maketemplater(repo.ui, tmpl, defaults=templatekw.keywords, | |
938 | resources=tres) |
|
938 | resources=tres) | |
939 | mapping = {'ctx': ctx} |
|
939 | mapping = {'ctx': ctx} | |
940 | if props: |
|
940 | if props: | |
941 | mapping.update(props) |
|
941 | mapping.update(props) | |
942 | return t.renderdefault(mapping) |
|
942 | return t.renderdefault(mapping) | |
943 |
|
943 | |||
944 | def _buildfntemplate(pat, total=None, seqno=None, revwidth=None, pathname=None): |
|
944 | def _buildfntemplate(pat, total=None, seqno=None, revwidth=None, pathname=None): | |
945 | r"""Convert old-style filename format string to template string |
|
945 | r"""Convert old-style filename format string to template string | |
946 |
|
946 | |||
947 | >>> _buildfntemplate(b'foo-%b-%n.patch', seqno=0) |
|
947 | >>> _buildfntemplate(b'foo-%b-%n.patch', seqno=0) | |
948 | 'foo-{reporoot|basename}-{seqno}.patch' |
|
948 | 'foo-{reporoot|basename}-{seqno}.patch' | |
949 | >>> _buildfntemplate(b'%R{tags % "{tag}"}%H') |
|
949 | >>> _buildfntemplate(b'%R{tags % "{tag}"}%H') | |
950 | '{rev}{tags % "{tag}"}{node}' |
|
950 | '{rev}{tags % "{tag}"}{node}' | |
951 |
|
951 | |||
952 | '\' in outermost strings has to be escaped because it is a directory |
|
952 | '\' in outermost strings has to be escaped because it is a directory | |
953 | separator on Windows: |
|
953 | separator on Windows: | |
954 |
|
954 | |||
955 | >>> _buildfntemplate(b'c:\\tmp\\%R\\%n.patch', seqno=0) |
|
955 | >>> _buildfntemplate(b'c:\\tmp\\%R\\%n.patch', seqno=0) | |
956 | 'c:\\\\tmp\\\\{rev}\\\\{seqno}.patch' |
|
956 | 'c:\\\\tmp\\\\{rev}\\\\{seqno}.patch' | |
957 | >>> _buildfntemplate(b'\\\\foo\\bar.patch') |
|
957 | >>> _buildfntemplate(b'\\\\foo\\bar.patch') | |
958 | '\\\\\\\\foo\\\\bar.patch' |
|
958 | '\\\\\\\\foo\\\\bar.patch' | |
959 | >>> _buildfntemplate(b'\\{tags % "{tag}"}') |
|
959 | >>> _buildfntemplate(b'\\{tags % "{tag}"}') | |
960 | '\\\\{tags % "{tag}"}' |
|
960 | '\\\\{tags % "{tag}"}' | |
961 |
|
961 | |||
962 | but inner strings follow the template rules (i.e. '\' is taken as an |
|
962 | but inner strings follow the template rules (i.e. '\' is taken as an | |
963 | escape character): |
|
963 | escape character): | |
964 |
|
964 | |||
965 | >>> _buildfntemplate(br'{"c:\tmp"}', seqno=0) |
|
965 | >>> _buildfntemplate(br'{"c:\tmp"}', seqno=0) | |
966 | '{"c:\\tmp"}' |
|
966 | '{"c:\\tmp"}' | |
967 | """ |
|
967 | """ | |
968 | expander = { |
|
968 | expander = { | |
969 | b'H': b'{node}', |
|
969 | b'H': b'{node}', | |
970 | b'R': b'{rev}', |
|
970 | b'R': b'{rev}', | |
971 | b'h': b'{node|short}', |
|
971 | b'h': b'{node|short}', | |
972 | b'm': br'{sub(r"[^\w]", "_", desc|firstline)}', |
|
972 | b'm': br'{sub(r"[^\w]", "_", desc|firstline)}', | |
973 | b'r': b'{if(revwidth, pad(rev, revwidth, "0", left=True), rev)}', |
|
973 | b'r': b'{if(revwidth, pad(rev, revwidth, "0", left=True), rev)}', | |
974 | b'%': b'%', |
|
974 | b'%': b'%', | |
975 | b'b': b'{reporoot|basename}', |
|
975 | b'b': b'{reporoot|basename}', | |
976 | } |
|
976 | } | |
977 | if total is not None: |
|
977 | if total is not None: | |
978 | expander[b'N'] = b'{total}' |
|
978 | expander[b'N'] = b'{total}' | |
979 | if seqno is not None: |
|
979 | if seqno is not None: | |
980 | expander[b'n'] = b'{seqno}' |
|
980 | expander[b'n'] = b'{seqno}' | |
981 | if total is not None and seqno is not None: |
|
981 | if total is not None and seqno is not None: | |
982 | expander[b'n'] = b'{pad(seqno, total|stringify|count, "0", left=True)}' |
|
982 | expander[b'n'] = b'{pad(seqno, total|stringify|count, "0", left=True)}' | |
983 | if pathname is not None: |
|
983 | if pathname is not None: | |
984 | expander[b's'] = b'{pathname|basename}' |
|
984 | expander[b's'] = b'{pathname|basename}' | |
985 | expander[b'd'] = b'{if(pathname|dirname, pathname|dirname, ".")}' |
|
985 | expander[b'd'] = b'{if(pathname|dirname, pathname|dirname, ".")}' | |
986 | expander[b'p'] = b'{pathname}' |
|
986 | expander[b'p'] = b'{pathname}' | |
987 |
|
987 | |||
988 | newname = [] |
|
988 | newname = [] | |
989 | for typ, start, end in templater.scantemplate(pat, raw=True): |
|
989 | for typ, start, end in templater.scantemplate(pat, raw=True): | |
990 | if typ != b'string': |
|
990 | if typ != b'string': | |
991 | newname.append(pat[start:end]) |
|
991 | newname.append(pat[start:end]) | |
992 | continue |
|
992 | continue | |
993 | i = start |
|
993 | i = start | |
994 | while i < end: |
|
994 | while i < end: | |
995 | n = pat.find(b'%', i, end) |
|
995 | n = pat.find(b'%', i, end) | |
996 | if n < 0: |
|
996 | if n < 0: | |
997 | newname.append(stringutil.escapestr(pat[i:end])) |
|
997 | newname.append(stringutil.escapestr(pat[i:end])) | |
998 | break |
|
998 | break | |
999 | newname.append(stringutil.escapestr(pat[i:n])) |
|
999 | newname.append(stringutil.escapestr(pat[i:n])) | |
1000 | if n + 2 > end: |
|
1000 | if n + 2 > end: | |
1001 | raise error.Abort(_("incomplete format spec in output " |
|
1001 | raise error.Abort(_("incomplete format spec in output " | |
1002 | "filename")) |
|
1002 | "filename")) | |
1003 | c = pat[n + 1:n + 2] |
|
1003 | c = pat[n + 1:n + 2] | |
1004 | i = n + 2 |
|
1004 | i = n + 2 | |
1005 | try: |
|
1005 | try: | |
1006 | newname.append(expander[c]) |
|
1006 | newname.append(expander[c]) | |
1007 | except KeyError: |
|
1007 | except KeyError: | |
1008 | raise error.Abort(_("invalid format spec '%%%s' in output " |
|
1008 | raise error.Abort(_("invalid format spec '%%%s' in output " | |
1009 | "filename") % c) |
|
1009 | "filename") % c) | |
1010 | return ''.join(newname) |
|
1010 | return ''.join(newname) | |
1011 |
|
1011 | |||
1012 | def makefilename(ctx, pat, **props): |
|
1012 | def makefilename(ctx, pat, **props): | |
1013 | if not pat: |
|
1013 | if not pat: | |
1014 | return pat |
|
1014 | return pat | |
1015 | tmpl = _buildfntemplate(pat, **props) |
|
1015 | tmpl = _buildfntemplate(pat, **props) | |
1016 | # BUG: alias expansion shouldn't be made against template fragments |
|
1016 | # BUG: alias expansion shouldn't be made against template fragments | |
1017 | # rewritten from %-format strings, but we have no easy way to partially |
|
1017 | # rewritten from %-format strings, but we have no easy way to partially | |
1018 | # disable the expansion. |
|
1018 | # disable the expansion. | |
1019 | return rendertemplate(ctx, tmpl, pycompat.byteskwargs(props)) |
|
1019 | return rendertemplate(ctx, tmpl, pycompat.byteskwargs(props)) | |
1020 |
|
1020 | |||
1021 | def isstdiofilename(pat): |
|
1021 | def isstdiofilename(pat): | |
1022 | """True if the given pat looks like a filename denoting stdin/stdout""" |
|
1022 | """True if the given pat looks like a filename denoting stdin/stdout""" | |
1023 | return not pat or pat == '-' |
|
1023 | return not pat or pat == '-' | |
1024 |
|
1024 | |||
1025 | class _unclosablefile(object): |
|
1025 | class _unclosablefile(object): | |
1026 | def __init__(self, fp): |
|
1026 | def __init__(self, fp): | |
1027 | self._fp = fp |
|
1027 | self._fp = fp | |
1028 |
|
1028 | |||
1029 | def close(self): |
|
1029 | def close(self): | |
1030 | pass |
|
1030 | pass | |
1031 |
|
1031 | |||
1032 | def __iter__(self): |
|
1032 | def __iter__(self): | |
1033 | return iter(self._fp) |
|
1033 | return iter(self._fp) | |
1034 |
|
1034 | |||
1035 | def __getattr__(self, attr): |
|
1035 | def __getattr__(self, attr): | |
1036 | return getattr(self._fp, attr) |
|
1036 | return getattr(self._fp, attr) | |
1037 |
|
1037 | |||
1038 | def __enter__(self): |
|
1038 | def __enter__(self): | |
1039 | return self |
|
1039 | return self | |
1040 |
|
1040 | |||
1041 | def __exit__(self, exc_type, exc_value, exc_tb): |
|
1041 | def __exit__(self, exc_type, exc_value, exc_tb): | |
1042 | pass |
|
1042 | pass | |
1043 |
|
1043 | |||
1044 | def makefileobj(ctx, pat, mode='wb', **props): |
|
1044 | def makefileobj(ctx, pat, mode='wb', **props): | |
1045 | writable = mode not in ('r', 'rb') |
|
1045 | writable = mode not in ('r', 'rb') | |
1046 |
|
1046 | |||
1047 | if isstdiofilename(pat): |
|
1047 | if isstdiofilename(pat): | |
1048 | repo = ctx.repo() |
|
1048 | repo = ctx.repo() | |
1049 | if writable: |
|
1049 | if writable: | |
1050 | fp = repo.ui.fout |
|
1050 | fp = repo.ui.fout | |
1051 | else: |
|
1051 | else: | |
1052 | fp = repo.ui.fin |
|
1052 | fp = repo.ui.fin | |
1053 | return _unclosablefile(fp) |
|
1053 | return _unclosablefile(fp) | |
1054 | fn = makefilename(ctx, pat, **props) |
|
1054 | fn = makefilename(ctx, pat, **props) | |
1055 | return open(fn, mode) |
|
1055 | return open(fn, mode) | |
1056 |
|
1056 | |||
1057 | def openrevlog(repo, cmd, file_, opts): |
|
1057 | def openrevlog(repo, cmd, file_, opts): | |
1058 | """opens the changelog, manifest, a filelog or a given revlog""" |
|
1058 | """opens the changelog, manifest, a filelog or a given revlog""" | |
1059 | cl = opts['changelog'] |
|
1059 | cl = opts['changelog'] | |
1060 | mf = opts['manifest'] |
|
1060 | mf = opts['manifest'] | |
1061 | dir = opts['dir'] |
|
1061 | dir = opts['dir'] | |
1062 | msg = None |
|
1062 | msg = None | |
1063 | if cl and mf: |
|
1063 | if cl and mf: | |
1064 | msg = _('cannot specify --changelog and --manifest at the same time') |
|
1064 | msg = _('cannot specify --changelog and --manifest at the same time') | |
1065 | elif cl and dir: |
|
1065 | elif cl and dir: | |
1066 | msg = _('cannot specify --changelog and --dir at the same time') |
|
1066 | msg = _('cannot specify --changelog and --dir at the same time') | |
1067 | elif cl or mf or dir: |
|
1067 | elif cl or mf or dir: | |
1068 | if file_: |
|
1068 | if file_: | |
1069 | msg = _('cannot specify filename with --changelog or --manifest') |
|
1069 | msg = _('cannot specify filename with --changelog or --manifest') | |
1070 | elif not repo: |
|
1070 | elif not repo: | |
1071 | msg = _('cannot specify --changelog or --manifest or --dir ' |
|
1071 | msg = _('cannot specify --changelog or --manifest or --dir ' | |
1072 | 'without a repository') |
|
1072 | 'without a repository') | |
1073 | if msg: |
|
1073 | if msg: | |
1074 | raise error.Abort(msg) |
|
1074 | raise error.Abort(msg) | |
1075 |
|
1075 | |||
1076 | r = None |
|
1076 | r = None | |
1077 | if repo: |
|
1077 | if repo: | |
1078 | if cl: |
|
1078 | if cl: | |
1079 | r = repo.unfiltered().changelog |
|
1079 | r = repo.unfiltered().changelog | |
1080 | elif dir: |
|
1080 | elif dir: | |
1081 | if 'treemanifest' not in repo.requirements: |
|
1081 | if 'treemanifest' not in repo.requirements: | |
1082 | raise error.Abort(_("--dir can only be used on repos with " |
|
1082 | raise error.Abort(_("--dir can only be used on repos with " | |
1083 | "treemanifest enabled")) |
|
1083 | "treemanifest enabled")) | |
1084 | if not dir.endswith('/'): |
|
1084 | if not dir.endswith('/'): | |
1085 | dir = dir + '/' |
|
1085 | dir = dir + '/' | |
1086 | dirlog = repo.manifestlog._revlog.dirlog(dir) |
|
1086 | dirlog = repo.manifestlog._revlog.dirlog(dir) | |
1087 | if len(dirlog): |
|
1087 | if len(dirlog): | |
1088 | r = dirlog |
|
1088 | r = dirlog | |
1089 | elif mf: |
|
1089 | elif mf: | |
1090 | r = repo.manifestlog._revlog |
|
1090 | r = repo.manifestlog._revlog | |
1091 | elif file_: |
|
1091 | elif file_: | |
1092 | filelog = repo.file(file_) |
|
1092 | filelog = repo.file(file_) | |
1093 | if len(filelog): |
|
1093 | if len(filelog): | |
1094 | r = filelog |
|
1094 | r = filelog | |
1095 | if not r: |
|
1095 | if not r: | |
1096 | if not file_: |
|
1096 | if not file_: | |
1097 | raise error.CommandError(cmd, _('invalid arguments')) |
|
1097 | raise error.CommandError(cmd, _('invalid arguments')) | |
1098 | if not os.path.isfile(file_): |
|
1098 | if not os.path.isfile(file_): | |
1099 | raise error.Abort(_("revlog '%s' not found") % file_) |
|
1099 | raise error.Abort(_("revlog '%s' not found") % file_) | |
1100 | r = revlog.revlog(vfsmod.vfs(pycompat.getcwd(), audit=False), |
|
1100 | r = revlog.revlog(vfsmod.vfs(pycompat.getcwd(), audit=False), | |
1101 | file_[:-2] + ".i") |
|
1101 | file_[:-2] + ".i") | |
1102 | return r |
|
1102 | return r | |
1103 |
|
1103 | |||
1104 | def copy(ui, repo, pats, opts, rename=False): |
|
1104 | def copy(ui, repo, pats, opts, rename=False): | |
1105 | # called with the repo lock held |
|
1105 | # called with the repo lock held | |
1106 | # |
|
1106 | # | |
1107 | # hgsep => pathname that uses "/" to separate directories |
|
1107 | # hgsep => pathname that uses "/" to separate directories | |
1108 | # ossep => pathname that uses os.sep to separate directories |
|
1108 | # ossep => pathname that uses os.sep to separate directories | |
1109 | cwd = repo.getcwd() |
|
1109 | cwd = repo.getcwd() | |
1110 | targets = {} |
|
1110 | targets = {} | |
1111 | after = opts.get("after") |
|
1111 | after = opts.get("after") | |
1112 | dryrun = opts.get("dry_run") |
|
1112 | dryrun = opts.get("dry_run") | |
1113 | wctx = repo[None] |
|
1113 | wctx = repo[None] | |
1114 |
|
1114 | |||
1115 | def walkpat(pat): |
|
1115 | def walkpat(pat): | |
1116 | srcs = [] |
|
1116 | srcs = [] | |
1117 | if after: |
|
1117 | if after: | |
1118 | badstates = '?' |
|
1118 | badstates = '?' | |
1119 | else: |
|
1119 | else: | |
1120 | badstates = '?r' |
|
1120 | badstates = '?r' | |
1121 | m = scmutil.match(wctx, [pat], opts, globbed=True) |
|
1121 | m = scmutil.match(wctx, [pat], opts, globbed=True) | |
1122 | for abs in wctx.walk(m): |
|
1122 | for abs in wctx.walk(m): | |
1123 | state = repo.dirstate[abs] |
|
1123 | state = repo.dirstate[abs] | |
1124 | rel = m.rel(abs) |
|
1124 | rel = m.rel(abs) | |
1125 | exact = m.exact(abs) |
|
1125 | exact = m.exact(abs) | |
1126 | if state in badstates: |
|
1126 | if state in badstates: | |
1127 | if exact and state == '?': |
|
1127 | if exact and state == '?': | |
1128 | ui.warn(_('%s: not copying - file is not managed\n') % rel) |
|
1128 | ui.warn(_('%s: not copying - file is not managed\n') % rel) | |
1129 | if exact and state == 'r': |
|
1129 | if exact and state == 'r': | |
1130 | ui.warn(_('%s: not copying - file has been marked for' |
|
1130 | ui.warn(_('%s: not copying - file has been marked for' | |
1131 | ' remove\n') % rel) |
|
1131 | ' remove\n') % rel) | |
1132 | continue |
|
1132 | continue | |
1133 | # abs: hgsep |
|
1133 | # abs: hgsep | |
1134 | # rel: ossep |
|
1134 | # rel: ossep | |
1135 | srcs.append((abs, rel, exact)) |
|
1135 | srcs.append((abs, rel, exact)) | |
1136 | return srcs |
|
1136 | return srcs | |
1137 |
|
1137 | |||
1138 | # abssrc: hgsep |
|
1138 | # abssrc: hgsep | |
1139 | # relsrc: ossep |
|
1139 | # relsrc: ossep | |
1140 | # otarget: ossep |
|
1140 | # otarget: ossep | |
1141 | def copyfile(abssrc, relsrc, otarget, exact): |
|
1141 | def copyfile(abssrc, relsrc, otarget, exact): | |
1142 | abstarget = pathutil.canonpath(repo.root, cwd, otarget) |
|
1142 | abstarget = pathutil.canonpath(repo.root, cwd, otarget) | |
1143 | if '/' in abstarget: |
|
1143 | if '/' in abstarget: | |
1144 | # We cannot normalize abstarget itself, this would prevent |
|
1144 | # We cannot normalize abstarget itself, this would prevent | |
1145 | # case only renames, like a => A. |
|
1145 | # case only renames, like a => A. | |
1146 | abspath, absname = abstarget.rsplit('/', 1) |
|
1146 | abspath, absname = abstarget.rsplit('/', 1) | |
1147 | abstarget = repo.dirstate.normalize(abspath) + '/' + absname |
|
1147 | abstarget = repo.dirstate.normalize(abspath) + '/' + absname | |
1148 | reltarget = repo.pathto(abstarget, cwd) |
|
1148 | reltarget = repo.pathto(abstarget, cwd) | |
1149 | target = repo.wjoin(abstarget) |
|
1149 | target = repo.wjoin(abstarget) | |
1150 | src = repo.wjoin(abssrc) |
|
1150 | src = repo.wjoin(abssrc) | |
1151 | state = repo.dirstate[abstarget] |
|
1151 | state = repo.dirstate[abstarget] | |
1152 |
|
1152 | |||
1153 | scmutil.checkportable(ui, abstarget) |
|
1153 | scmutil.checkportable(ui, abstarget) | |
1154 |
|
1154 | |||
1155 | # check for collisions |
|
1155 | # check for collisions | |
1156 | prevsrc = targets.get(abstarget) |
|
1156 | prevsrc = targets.get(abstarget) | |
1157 | if prevsrc is not None: |
|
1157 | if prevsrc is not None: | |
1158 | ui.warn(_('%s: not overwriting - %s collides with %s\n') % |
|
1158 | ui.warn(_('%s: not overwriting - %s collides with %s\n') % | |
1159 | (reltarget, repo.pathto(abssrc, cwd), |
|
1159 | (reltarget, repo.pathto(abssrc, cwd), | |
1160 | repo.pathto(prevsrc, cwd))) |
|
1160 | repo.pathto(prevsrc, cwd))) | |
1161 | return |
|
1161 | return | |
1162 |
|
1162 | |||
1163 | # check for overwrites |
|
1163 | # check for overwrites | |
1164 | exists = os.path.lexists(target) |
|
1164 | exists = os.path.lexists(target) | |
1165 | samefile = False |
|
1165 | samefile = False | |
1166 | if exists and abssrc != abstarget: |
|
1166 | if exists and abssrc != abstarget: | |
1167 | if (repo.dirstate.normalize(abssrc) == |
|
1167 | if (repo.dirstate.normalize(abssrc) == | |
1168 | repo.dirstate.normalize(abstarget)): |
|
1168 | repo.dirstate.normalize(abstarget)): | |
1169 | if not rename: |
|
1169 | if not rename: | |
1170 | ui.warn(_("%s: can't copy - same file\n") % reltarget) |
|
1170 | ui.warn(_("%s: can't copy - same file\n") % reltarget) | |
1171 | return |
|
1171 | return | |
1172 | exists = False |
|
1172 | exists = False | |
1173 | samefile = True |
|
1173 | samefile = True | |
1174 |
|
1174 | |||
1175 | if not after and exists or after and state in 'mn': |
|
1175 | if not after and exists or after and state in 'mn': | |
1176 | if not opts['force']: |
|
1176 | if not opts['force']: | |
1177 | if state in 'mn': |
|
1177 | if state in 'mn': | |
1178 | msg = _('%s: not overwriting - file already committed\n') |
|
1178 | msg = _('%s: not overwriting - file already committed\n') | |
1179 | if after: |
|
1179 | if after: | |
1180 | flags = '--after --force' |
|
1180 | flags = '--after --force' | |
1181 | else: |
|
1181 | else: | |
1182 | flags = '--force' |
|
1182 | flags = '--force' | |
1183 | if rename: |
|
1183 | if rename: | |
1184 | hint = _('(hg rename %s to replace the file by ' |
|
1184 | hint = _('(hg rename %s to replace the file by ' | |
1185 | 'recording a rename)\n') % flags |
|
1185 | 'recording a rename)\n') % flags | |
1186 | else: |
|
1186 | else: | |
1187 | hint = _('(hg copy %s to replace the file by ' |
|
1187 | hint = _('(hg copy %s to replace the file by ' | |
1188 | 'recording a copy)\n') % flags |
|
1188 | 'recording a copy)\n') % flags | |
1189 | else: |
|
1189 | else: | |
1190 | msg = _('%s: not overwriting - file exists\n') |
|
1190 | msg = _('%s: not overwriting - file exists\n') | |
1191 | if rename: |
|
1191 | if rename: | |
1192 | hint = _('(hg rename --after to record the rename)\n') |
|
1192 | hint = _('(hg rename --after to record the rename)\n') | |
1193 | else: |
|
1193 | else: | |
1194 | hint = _('(hg copy --after to record the copy)\n') |
|
1194 | hint = _('(hg copy --after to record the copy)\n') | |
1195 | ui.warn(msg % reltarget) |
|
1195 | ui.warn(msg % reltarget) | |
1196 | ui.warn(hint) |
|
1196 | ui.warn(hint) | |
1197 | return |
|
1197 | return | |
1198 |
|
1198 | |||
1199 | if after: |
|
1199 | if after: | |
1200 | if not exists: |
|
1200 | if not exists: | |
1201 | if rename: |
|
1201 | if rename: | |
1202 | ui.warn(_('%s: not recording move - %s does not exist\n') % |
|
1202 | ui.warn(_('%s: not recording move - %s does not exist\n') % | |
1203 | (relsrc, reltarget)) |
|
1203 | (relsrc, reltarget)) | |
1204 | else: |
|
1204 | else: | |
1205 | ui.warn(_('%s: not recording copy - %s does not exist\n') % |
|
1205 | ui.warn(_('%s: not recording copy - %s does not exist\n') % | |
1206 | (relsrc, reltarget)) |
|
1206 | (relsrc, reltarget)) | |
1207 | return |
|
1207 | return | |
1208 | elif not dryrun: |
|
1208 | elif not dryrun: | |
1209 | try: |
|
1209 | try: | |
1210 | if exists: |
|
1210 | if exists: | |
1211 | os.unlink(target) |
|
1211 | os.unlink(target) | |
1212 | targetdir = os.path.dirname(target) or '.' |
|
1212 | targetdir = os.path.dirname(target) or '.' | |
1213 | if not os.path.isdir(targetdir): |
|
1213 | if not os.path.isdir(targetdir): | |
1214 | os.makedirs(targetdir) |
|
1214 | os.makedirs(targetdir) | |
1215 | if samefile: |
|
1215 | if samefile: | |
1216 | tmp = target + "~hgrename" |
|
1216 | tmp = target + "~hgrename" | |
1217 | os.rename(src, tmp) |
|
1217 | os.rename(src, tmp) | |
1218 | os.rename(tmp, target) |
|
1218 | os.rename(tmp, target) | |
1219 | else: |
|
1219 | else: | |
1220 | # Preserve stat info on renames, not on copies; this matches |
|
1220 | # Preserve stat info on renames, not on copies; this matches | |
1221 | # Linux CLI behavior. |
|
1221 | # Linux CLI behavior. | |
1222 | util.copyfile(src, target, copystat=rename) |
|
1222 | util.copyfile(src, target, copystat=rename) | |
1223 | srcexists = True |
|
1223 | srcexists = True | |
1224 | except IOError as inst: |
|
1224 | except IOError as inst: | |
1225 | if inst.errno == errno.ENOENT: |
|
1225 | if inst.errno == errno.ENOENT: | |
1226 | ui.warn(_('%s: deleted in working directory\n') % relsrc) |
|
1226 | ui.warn(_('%s: deleted in working directory\n') % relsrc) | |
1227 | srcexists = False |
|
1227 | srcexists = False | |
1228 | else: |
|
1228 | else: | |
1229 | ui.warn(_('%s: cannot copy - %s\n') % |
|
1229 | ui.warn(_('%s: cannot copy - %s\n') % | |
1230 | (relsrc, encoding.strtolocal(inst.strerror))) |
|
1230 | (relsrc, encoding.strtolocal(inst.strerror))) | |
1231 | return True # report a failure |
|
1231 | return True # report a failure | |
1232 |
|
1232 | |||
1233 | if ui.verbose or not exact: |
|
1233 | if ui.verbose or not exact: | |
1234 | if rename: |
|
1234 | if rename: | |
1235 | ui.status(_('moving %s to %s\n') % (relsrc, reltarget)) |
|
1235 | ui.status(_('moving %s to %s\n') % (relsrc, reltarget)) | |
1236 | else: |
|
1236 | else: | |
1237 | ui.status(_('copying %s to %s\n') % (relsrc, reltarget)) |
|
1237 | ui.status(_('copying %s to %s\n') % (relsrc, reltarget)) | |
1238 |
|
1238 | |||
1239 | targets[abstarget] = abssrc |
|
1239 | targets[abstarget] = abssrc | |
1240 |
|
1240 | |||
1241 | # fix up dirstate |
|
1241 | # fix up dirstate | |
1242 | scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget, |
|
1242 | scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget, | |
1243 | dryrun=dryrun, cwd=cwd) |
|
1243 | dryrun=dryrun, cwd=cwd) | |
1244 | if rename and not dryrun: |
|
1244 | if rename and not dryrun: | |
1245 | if not after and srcexists and not samefile: |
|
1245 | if not after and srcexists and not samefile: | |
1246 | rmdir = repo.ui.configbool('experimental', 'removeemptydirs') |
|
1246 | rmdir = repo.ui.configbool('experimental', 'removeemptydirs') | |
1247 | repo.wvfs.unlinkpath(abssrc, rmdir=rmdir) |
|
1247 | repo.wvfs.unlinkpath(abssrc, rmdir=rmdir) | |
1248 | wctx.forget([abssrc]) |
|
1248 | wctx.forget([abssrc]) | |
1249 |
|
1249 | |||
1250 | # pat: ossep |
|
1250 | # pat: ossep | |
1251 | # dest ossep |
|
1251 | # dest ossep | |
1252 | # srcs: list of (hgsep, hgsep, ossep, bool) |
|
1252 | # srcs: list of (hgsep, hgsep, ossep, bool) | |
1253 | # return: function that takes hgsep and returns ossep |
|
1253 | # return: function that takes hgsep and returns ossep | |
1254 | def targetpathfn(pat, dest, srcs): |
|
1254 | def targetpathfn(pat, dest, srcs): | |
1255 | if os.path.isdir(pat): |
|
1255 | if os.path.isdir(pat): | |
1256 | abspfx = pathutil.canonpath(repo.root, cwd, pat) |
|
1256 | abspfx = pathutil.canonpath(repo.root, cwd, pat) | |
1257 | abspfx = util.localpath(abspfx) |
|
1257 | abspfx = util.localpath(abspfx) | |
1258 | if destdirexists: |
|
1258 | if destdirexists: | |
1259 | striplen = len(os.path.split(abspfx)[0]) |
|
1259 | striplen = len(os.path.split(abspfx)[0]) | |
1260 | else: |
|
1260 | else: | |
1261 | striplen = len(abspfx) |
|
1261 | striplen = len(abspfx) | |
1262 | if striplen: |
|
1262 | if striplen: | |
1263 | striplen += len(pycompat.ossep) |
|
1263 | striplen += len(pycompat.ossep) | |
1264 | res = lambda p: os.path.join(dest, util.localpath(p)[striplen:]) |
|
1264 | res = lambda p: os.path.join(dest, util.localpath(p)[striplen:]) | |
1265 | elif destdirexists: |
|
1265 | elif destdirexists: | |
1266 | res = lambda p: os.path.join(dest, |
|
1266 | res = lambda p: os.path.join(dest, | |
1267 | os.path.basename(util.localpath(p))) |
|
1267 | os.path.basename(util.localpath(p))) | |
1268 | else: |
|
1268 | else: | |
1269 | res = lambda p: dest |
|
1269 | res = lambda p: dest | |
1270 | return res |
|
1270 | return res | |
1271 |
|
1271 | |||
1272 | # pat: ossep |
|
1272 | # pat: ossep | |
1273 | # dest ossep |
|
1273 | # dest ossep | |
1274 | # srcs: list of (hgsep, hgsep, ossep, bool) |
|
1274 | # srcs: list of (hgsep, hgsep, ossep, bool) | |
1275 | # return: function that takes hgsep and returns ossep |
|
1275 | # return: function that takes hgsep and returns ossep | |
1276 | def targetpathafterfn(pat, dest, srcs): |
|
1276 | def targetpathafterfn(pat, dest, srcs): | |
1277 | if matchmod.patkind(pat): |
|
1277 | if matchmod.patkind(pat): | |
1278 | # a mercurial pattern |
|
1278 | # a mercurial pattern | |
1279 | res = lambda p: os.path.join(dest, |
|
1279 | res = lambda p: os.path.join(dest, | |
1280 | os.path.basename(util.localpath(p))) |
|
1280 | os.path.basename(util.localpath(p))) | |
1281 | else: |
|
1281 | else: | |
1282 | abspfx = pathutil.canonpath(repo.root, cwd, pat) |
|
1282 | abspfx = pathutil.canonpath(repo.root, cwd, pat) | |
1283 | if len(abspfx) < len(srcs[0][0]): |
|
1283 | if len(abspfx) < len(srcs[0][0]): | |
1284 | # A directory. Either the target path contains the last |
|
1284 | # A directory. Either the target path contains the last | |
1285 | # component of the source path or it does not. |
|
1285 | # component of the source path or it does not. | |
1286 | def evalpath(striplen): |
|
1286 | def evalpath(striplen): | |
1287 | score = 0 |
|
1287 | score = 0 | |
1288 | for s in srcs: |
|
1288 | for s in srcs: | |
1289 | t = os.path.join(dest, util.localpath(s[0])[striplen:]) |
|
1289 | t = os.path.join(dest, util.localpath(s[0])[striplen:]) | |
1290 | if os.path.lexists(t): |
|
1290 | if os.path.lexists(t): | |
1291 | score += 1 |
|
1291 | score += 1 | |
1292 | return score |
|
1292 | return score | |
1293 |
|
1293 | |||
1294 | abspfx = util.localpath(abspfx) |
|
1294 | abspfx = util.localpath(abspfx) | |
1295 | striplen = len(abspfx) |
|
1295 | striplen = len(abspfx) | |
1296 | if striplen: |
|
1296 | if striplen: | |
1297 | striplen += len(pycompat.ossep) |
|
1297 | striplen += len(pycompat.ossep) | |
1298 | if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])): |
|
1298 | if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])): | |
1299 | score = evalpath(striplen) |
|
1299 | score = evalpath(striplen) | |
1300 | striplen1 = len(os.path.split(abspfx)[0]) |
|
1300 | striplen1 = len(os.path.split(abspfx)[0]) | |
1301 | if striplen1: |
|
1301 | if striplen1: | |
1302 | striplen1 += len(pycompat.ossep) |
|
1302 | striplen1 += len(pycompat.ossep) | |
1303 | if evalpath(striplen1) > score: |
|
1303 | if evalpath(striplen1) > score: | |
1304 | striplen = striplen1 |
|
1304 | striplen = striplen1 | |
1305 | res = lambda p: os.path.join(dest, |
|
1305 | res = lambda p: os.path.join(dest, | |
1306 | util.localpath(p)[striplen:]) |
|
1306 | util.localpath(p)[striplen:]) | |
1307 | else: |
|
1307 | else: | |
1308 | # a file |
|
1308 | # a file | |
1309 | if destdirexists: |
|
1309 | if destdirexists: | |
1310 | res = lambda p: os.path.join(dest, |
|
1310 | res = lambda p: os.path.join(dest, | |
1311 | os.path.basename(util.localpath(p))) |
|
1311 | os.path.basename(util.localpath(p))) | |
1312 | else: |
|
1312 | else: | |
1313 | res = lambda p: dest |
|
1313 | res = lambda p: dest | |
1314 | return res |
|
1314 | return res | |
1315 |
|
1315 | |||
1316 | pats = scmutil.expandpats(pats) |
|
1316 | pats = scmutil.expandpats(pats) | |
1317 | if not pats: |
|
1317 | if not pats: | |
1318 | raise error.Abort(_('no source or destination specified')) |
|
1318 | raise error.Abort(_('no source or destination specified')) | |
1319 | if len(pats) == 1: |
|
1319 | if len(pats) == 1: | |
1320 | raise error.Abort(_('no destination specified')) |
|
1320 | raise error.Abort(_('no destination specified')) | |
1321 | dest = pats.pop() |
|
1321 | dest = pats.pop() | |
1322 | destdirexists = os.path.isdir(dest) and not os.path.islink(dest) |
|
1322 | destdirexists = os.path.isdir(dest) and not os.path.islink(dest) | |
1323 | if not destdirexists: |
|
1323 | if not destdirexists: | |
1324 | if len(pats) > 1 or matchmod.patkind(pats[0]): |
|
1324 | if len(pats) > 1 or matchmod.patkind(pats[0]): | |
1325 | raise error.Abort(_('with multiple sources, destination must be an ' |
|
1325 | raise error.Abort(_('with multiple sources, destination must be an ' | |
1326 | 'existing directory')) |
|
1326 | 'existing directory')) | |
1327 | if util.endswithsep(dest): |
|
1327 | if util.endswithsep(dest): | |
1328 | raise error.Abort(_('destination %s is not a directory') % dest) |
|
1328 | raise error.Abort(_('destination %s is not a directory') % dest) | |
1329 |
|
1329 | |||
1330 | tfn = targetpathfn |
|
1330 | tfn = targetpathfn | |
1331 | if after: |
|
1331 | if after: | |
1332 | tfn = targetpathafterfn |
|
1332 | tfn = targetpathafterfn | |
1333 | copylist = [] |
|
1333 | copylist = [] | |
1334 | for pat in pats: |
|
1334 | for pat in pats: | |
1335 | srcs = walkpat(pat) |
|
1335 | srcs = walkpat(pat) | |
1336 | if not srcs: |
|
1336 | if not srcs: | |
1337 | continue |
|
1337 | continue | |
1338 | copylist.append((tfn(pat, dest, srcs), srcs)) |
|
1338 | copylist.append((tfn(pat, dest, srcs), srcs)) | |
1339 | if not copylist: |
|
1339 | if not copylist: | |
1340 | raise error.Abort(_('no files to copy')) |
|
1340 | raise error.Abort(_('no files to copy')) | |
1341 |
|
1341 | |||
1342 | errors = 0 |
|
1342 | errors = 0 | |
1343 | for targetpath, srcs in copylist: |
|
1343 | for targetpath, srcs in copylist: | |
1344 | for abssrc, relsrc, exact in srcs: |
|
1344 | for abssrc, relsrc, exact in srcs: | |
1345 | if copyfile(abssrc, relsrc, targetpath(abssrc), exact): |
|
1345 | if copyfile(abssrc, relsrc, targetpath(abssrc), exact): | |
1346 | errors += 1 |
|
1346 | errors += 1 | |
1347 |
|
1347 | |||
1348 | if errors: |
|
1348 | if errors: | |
1349 | ui.warn(_('(consider using --after)\n')) |
|
1349 | ui.warn(_('(consider using --after)\n')) | |
1350 |
|
1350 | |||
1351 | return errors != 0 |
|
1351 | return errors != 0 | |
1352 |
|
1352 | |||
1353 | ## facility to let extension process additional data into an import patch |
|
1353 | ## facility to let extension process additional data into an import patch | |
1354 | # list of identifier to be executed in order |
|
1354 | # list of identifier to be executed in order | |
1355 | extrapreimport = [] # run before commit |
|
1355 | extrapreimport = [] # run before commit | |
1356 | extrapostimport = [] # run after commit |
|
1356 | extrapostimport = [] # run after commit | |
1357 | # mapping from identifier to actual import function |
|
1357 | # mapping from identifier to actual import function | |
1358 | # |
|
1358 | # | |
1359 | # 'preimport' are run before the commit is made and are provided the following |
|
1359 | # 'preimport' are run before the commit is made and are provided the following | |
1360 | # arguments: |
|
1360 | # arguments: | |
1361 | # - repo: the localrepository instance, |
|
1361 | # - repo: the localrepository instance, | |
1362 | # - patchdata: data extracted from patch header (cf m.patch.patchheadermap), |
|
1362 | # - patchdata: data extracted from patch header (cf m.patch.patchheadermap), | |
1363 | # - extra: the future extra dictionary of the changeset, please mutate it, |
|
1363 | # - extra: the future extra dictionary of the changeset, please mutate it, | |
1364 | # - opts: the import options. |
|
1364 | # - opts: the import options. | |
1365 | # XXX ideally, we would just pass an ctx ready to be computed, that would allow |
|
1365 | # XXX ideally, we would just pass an ctx ready to be computed, that would allow | |
1366 | # mutation of in memory commit and more. Feel free to rework the code to get |
|
1366 | # mutation of in memory commit and more. Feel free to rework the code to get | |
1367 | # there. |
|
1367 | # there. | |
1368 | extrapreimportmap = {} |
|
1368 | extrapreimportmap = {} | |
1369 | # 'postimport' are run after the commit is made and are provided the following |
|
1369 | # 'postimport' are run after the commit is made and are provided the following | |
1370 | # argument: |
|
1370 | # argument: | |
1371 | # - ctx: the changectx created by import. |
|
1371 | # - ctx: the changectx created by import. | |
1372 | extrapostimportmap = {} |
|
1372 | extrapostimportmap = {} | |
1373 |
|
1373 | |||
1374 | def tryimportone(ui, repo, patchdata, parents, opts, msgs, updatefunc): |
|
1374 | def tryimportone(ui, repo, patchdata, parents, opts, msgs, updatefunc): | |
1375 | """Utility function used by commands.import to import a single patch |
|
1375 | """Utility function used by commands.import to import a single patch | |
1376 |
|
1376 | |||
1377 | This function is explicitly defined here to help the evolve extension to |
|
1377 | This function is explicitly defined here to help the evolve extension to | |
1378 | wrap this part of the import logic. |
|
1378 | wrap this part of the import logic. | |
1379 |
|
1379 | |||
1380 | The API is currently a bit ugly because it a simple code translation from |
|
1380 | The API is currently a bit ugly because it a simple code translation from | |
1381 | the import command. Feel free to make it better. |
|
1381 | the import command. Feel free to make it better. | |
1382 |
|
1382 | |||
1383 | :patchdata: a dictionary containing parsed patch data (such as from |
|
1383 | :patchdata: a dictionary containing parsed patch data (such as from | |
1384 | ``patch.extract()``) |
|
1384 | ``patch.extract()``) | |
1385 | :parents: nodes that will be parent of the created commit |
|
1385 | :parents: nodes that will be parent of the created commit | |
1386 | :opts: the full dict of option passed to the import command |
|
1386 | :opts: the full dict of option passed to the import command | |
1387 | :msgs: list to save commit message to. |
|
1387 | :msgs: list to save commit message to. | |
1388 | (used in case we need to save it when failing) |
|
1388 | (used in case we need to save it when failing) | |
1389 | :updatefunc: a function that update a repo to a given node |
|
1389 | :updatefunc: a function that update a repo to a given node | |
1390 | updatefunc(<repo>, <node>) |
|
1390 | updatefunc(<repo>, <node>) | |
1391 | """ |
|
1391 | """ | |
1392 | # avoid cycle context -> subrepo -> cmdutil |
|
1392 | # avoid cycle context -> subrepo -> cmdutil | |
1393 | from . import context |
|
1393 | from . import context | |
1394 |
|
1394 | |||
1395 | tmpname = patchdata.get('filename') |
|
1395 | tmpname = patchdata.get('filename') | |
1396 | message = patchdata.get('message') |
|
1396 | message = patchdata.get('message') | |
1397 | user = opts.get('user') or patchdata.get('user') |
|
1397 | user = opts.get('user') or patchdata.get('user') | |
1398 | date = opts.get('date') or patchdata.get('date') |
|
1398 | date = opts.get('date') or patchdata.get('date') | |
1399 | branch = patchdata.get('branch') |
|
1399 | branch = patchdata.get('branch') | |
1400 | nodeid = patchdata.get('nodeid') |
|
1400 | nodeid = patchdata.get('nodeid') | |
1401 | p1 = patchdata.get('p1') |
|
1401 | p1 = patchdata.get('p1') | |
1402 | p2 = patchdata.get('p2') |
|
1402 | p2 = patchdata.get('p2') | |
1403 |
|
1403 | |||
1404 | nocommit = opts.get('no_commit') |
|
1404 | nocommit = opts.get('no_commit') | |
1405 | importbranch = opts.get('import_branch') |
|
1405 | importbranch = opts.get('import_branch') | |
1406 | update = not opts.get('bypass') |
|
1406 | update = not opts.get('bypass') | |
1407 | strip = opts["strip"] |
|
1407 | strip = opts["strip"] | |
1408 | prefix = opts["prefix"] |
|
1408 | prefix = opts["prefix"] | |
1409 | sim = float(opts.get('similarity') or 0) |
|
1409 | sim = float(opts.get('similarity') or 0) | |
1410 |
|
1410 | |||
1411 | if not tmpname: |
|
1411 | if not tmpname: | |
1412 | return None, None, False |
|
1412 | return None, None, False | |
1413 |
|
1413 | |||
1414 | rejects = False |
|
1414 | rejects = False | |
1415 |
|
1415 | |||
1416 | cmdline_message = logmessage(ui, opts) |
|
1416 | cmdline_message = logmessage(ui, opts) | |
1417 | if cmdline_message: |
|
1417 | if cmdline_message: | |
1418 | # pickup the cmdline msg |
|
1418 | # pickup the cmdline msg | |
1419 | message = cmdline_message |
|
1419 | message = cmdline_message | |
1420 | elif message: |
|
1420 | elif message: | |
1421 | # pickup the patch msg |
|
1421 | # pickup the patch msg | |
1422 | message = message.strip() |
|
1422 | message = message.strip() | |
1423 | else: |
|
1423 | else: | |
1424 | # launch the editor |
|
1424 | # launch the editor | |
1425 | message = None |
|
1425 | message = None | |
1426 | ui.debug('message:\n%s\n' % (message or '')) |
|
1426 | ui.debug('message:\n%s\n' % (message or '')) | |
1427 |
|
1427 | |||
1428 | if len(parents) == 1: |
|
1428 | if len(parents) == 1: | |
1429 | parents.append(repo[nullid]) |
|
1429 | parents.append(repo[nullid]) | |
1430 | if opts.get('exact'): |
|
1430 | if opts.get('exact'): | |
1431 | if not nodeid or not p1: |
|
1431 | if not nodeid or not p1: | |
1432 | raise error.Abort(_('not a Mercurial patch')) |
|
1432 | raise error.Abort(_('not a Mercurial patch')) | |
1433 | p1 = repo[p1] |
|
1433 | p1 = repo[p1] | |
1434 | p2 = repo[p2 or nullid] |
|
1434 | p2 = repo[p2 or nullid] | |
1435 | elif p2: |
|
1435 | elif p2: | |
1436 | try: |
|
1436 | try: | |
1437 | p1 = repo[p1] |
|
1437 | p1 = repo[p1] | |
1438 | p2 = repo[p2] |
|
1438 | p2 = repo[p2] | |
1439 | # Without any options, consider p2 only if the |
|
1439 | # Without any options, consider p2 only if the | |
1440 | # patch is being applied on top of the recorded |
|
1440 | # patch is being applied on top of the recorded | |
1441 | # first parent. |
|
1441 | # first parent. | |
1442 | if p1 != parents[0]: |
|
1442 | if p1 != parents[0]: | |
1443 | p1 = parents[0] |
|
1443 | p1 = parents[0] | |
1444 | p2 = repo[nullid] |
|
1444 | p2 = repo[nullid] | |
1445 | except error.RepoError: |
|
1445 | except error.RepoError: | |
1446 | p1, p2 = parents |
|
1446 | p1, p2 = parents | |
1447 | if p2.node() == nullid: |
|
1447 | if p2.node() == nullid: | |
1448 | ui.warn(_("warning: import the patch as a normal revision\n" |
|
1448 | ui.warn(_("warning: import the patch as a normal revision\n" | |
1449 | "(use --exact to import the patch as a merge)\n")) |
|
1449 | "(use --exact to import the patch as a merge)\n")) | |
1450 | else: |
|
1450 | else: | |
1451 | p1, p2 = parents |
|
1451 | p1, p2 = parents | |
1452 |
|
1452 | |||
1453 | n = None |
|
1453 | n = None | |
1454 | if update: |
|
1454 | if update: | |
1455 | if p1 != parents[0]: |
|
1455 | if p1 != parents[0]: | |
1456 | updatefunc(repo, p1.node()) |
|
1456 | updatefunc(repo, p1.node()) | |
1457 | if p2 != parents[1]: |
|
1457 | if p2 != parents[1]: | |
1458 | repo.setparents(p1.node(), p2.node()) |
|
1458 | repo.setparents(p1.node(), p2.node()) | |
1459 |
|
1459 | |||
1460 | if opts.get('exact') or importbranch: |
|
1460 | if opts.get('exact') or importbranch: | |
1461 | repo.dirstate.setbranch(branch or 'default') |
|
1461 | repo.dirstate.setbranch(branch or 'default') | |
1462 |
|
1462 | |||
1463 | partial = opts.get('partial', False) |
|
1463 | partial = opts.get('partial', False) | |
1464 | files = set() |
|
1464 | files = set() | |
1465 | try: |
|
1465 | try: | |
1466 | patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix, |
|
1466 | patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix, | |
1467 | files=files, eolmode=None, similarity=sim / 100.0) |
|
1467 | files=files, eolmode=None, similarity=sim / 100.0) | |
1468 | except error.PatchError as e: |
|
1468 | except error.PatchError as e: | |
1469 | if not partial: |
|
1469 | if not partial: | |
1470 | raise error.Abort(pycompat.bytestr(e)) |
|
1470 | raise error.Abort(pycompat.bytestr(e)) | |
1471 | if partial: |
|
1471 | if partial: | |
1472 | rejects = True |
|
1472 | rejects = True | |
1473 |
|
1473 | |||
1474 | files = list(files) |
|
1474 | files = list(files) | |
1475 | if nocommit: |
|
1475 | if nocommit: | |
1476 | if message: |
|
1476 | if message: | |
1477 | msgs.append(message) |
|
1477 | msgs.append(message) | |
1478 | else: |
|
1478 | else: | |
1479 | if opts.get('exact') or p2: |
|
1479 | if opts.get('exact') or p2: | |
1480 | # If you got here, you either use --force and know what |
|
1480 | # If you got here, you either use --force and know what | |
1481 | # you are doing or used --exact or a merge patch while |
|
1481 | # you are doing or used --exact or a merge patch while | |
1482 | # being updated to its first parent. |
|
1482 | # being updated to its first parent. | |
1483 | m = None |
|
1483 | m = None | |
1484 | else: |
|
1484 | else: | |
1485 | m = scmutil.matchfiles(repo, files or []) |
|
1485 | m = scmutil.matchfiles(repo, files or []) | |
1486 | editform = mergeeditform(repo[None], 'import.normal') |
|
1486 | editform = mergeeditform(repo[None], 'import.normal') | |
1487 | if opts.get('exact'): |
|
1487 | if opts.get('exact'): | |
1488 | editor = None |
|
1488 | editor = None | |
1489 | else: |
|
1489 | else: | |
1490 | editor = getcommiteditor(editform=editform, |
|
1490 | editor = getcommiteditor(editform=editform, | |
1491 | **pycompat.strkwargs(opts)) |
|
1491 | **pycompat.strkwargs(opts)) | |
1492 | extra = {} |
|
1492 | extra = {} | |
1493 | for idfunc in extrapreimport: |
|
1493 | for idfunc in extrapreimport: | |
1494 | extrapreimportmap[idfunc](repo, patchdata, extra, opts) |
|
1494 | extrapreimportmap[idfunc](repo, patchdata, extra, opts) | |
1495 | overrides = {} |
|
1495 | overrides = {} | |
1496 | if partial: |
|
1496 | if partial: | |
1497 | overrides[('ui', 'allowemptycommit')] = True |
|
1497 | overrides[('ui', 'allowemptycommit')] = True | |
1498 | with repo.ui.configoverride(overrides, 'import'): |
|
1498 | with repo.ui.configoverride(overrides, 'import'): | |
1499 | n = repo.commit(message, user, |
|
1499 | n = repo.commit(message, user, | |
1500 | date, match=m, |
|
1500 | date, match=m, | |
1501 | editor=editor, extra=extra) |
|
1501 | editor=editor, extra=extra) | |
1502 | for idfunc in extrapostimport: |
|
1502 | for idfunc in extrapostimport: | |
1503 | extrapostimportmap[idfunc](repo[n]) |
|
1503 | extrapostimportmap[idfunc](repo[n]) | |
1504 | else: |
|
1504 | else: | |
1505 | if opts.get('exact') or importbranch: |
|
1505 | if opts.get('exact') or importbranch: | |
1506 | branch = branch or 'default' |
|
1506 | branch = branch or 'default' | |
1507 | else: |
|
1507 | else: | |
1508 | branch = p1.branch() |
|
1508 | branch = p1.branch() | |
1509 | store = patch.filestore() |
|
1509 | store = patch.filestore() | |
1510 | try: |
|
1510 | try: | |
1511 | files = set() |
|
1511 | files = set() | |
1512 | try: |
|
1512 | try: | |
1513 | patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix, |
|
1513 | patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix, | |
1514 | files, eolmode=None) |
|
1514 | files, eolmode=None) | |
1515 | except error.PatchError as e: |
|
1515 | except error.PatchError as e: | |
1516 | raise error.Abort(stringutil.forcebytestr(e)) |
|
1516 | raise error.Abort(stringutil.forcebytestr(e)) | |
1517 | if opts.get('exact'): |
|
1517 | if opts.get('exact'): | |
1518 | editor = None |
|
1518 | editor = None | |
1519 | else: |
|
1519 | else: | |
1520 | editor = getcommiteditor(editform='import.bypass') |
|
1520 | editor = getcommiteditor(editform='import.bypass') | |
1521 | memctx = context.memctx(repo, (p1.node(), p2.node()), |
|
1521 | memctx = context.memctx(repo, (p1.node(), p2.node()), | |
1522 | message, |
|
1522 | message, | |
1523 | files=files, |
|
1523 | files=files, | |
1524 | filectxfn=store, |
|
1524 | filectxfn=store, | |
1525 | user=user, |
|
1525 | user=user, | |
1526 | date=date, |
|
1526 | date=date, | |
1527 | branch=branch, |
|
1527 | branch=branch, | |
1528 | editor=editor) |
|
1528 | editor=editor) | |
1529 | n = memctx.commit() |
|
1529 | n = memctx.commit() | |
1530 | finally: |
|
1530 | finally: | |
1531 | store.close() |
|
1531 | store.close() | |
1532 | if opts.get('exact') and nocommit: |
|
1532 | if opts.get('exact') and nocommit: | |
1533 | # --exact with --no-commit is still useful in that it does merge |
|
1533 | # --exact with --no-commit is still useful in that it does merge | |
1534 | # and branch bits |
|
1534 | # and branch bits | |
1535 | ui.warn(_("warning: can't check exact import with --no-commit\n")) |
|
1535 | ui.warn(_("warning: can't check exact import with --no-commit\n")) | |
1536 | elif opts.get('exact') and (not n or hex(n) != nodeid): |
|
1536 | elif opts.get('exact') and (not n or hex(n) != nodeid): | |
1537 | raise error.Abort(_('patch is damaged or loses information')) |
|
1537 | raise error.Abort(_('patch is damaged or loses information')) | |
1538 | msg = _('applied to working directory') |
|
1538 | msg = _('applied to working directory') | |
1539 | if n: |
|
1539 | if n: | |
1540 | # i18n: refers to a short changeset id |
|
1540 | # i18n: refers to a short changeset id | |
1541 | msg = _('created %s') % short(n) |
|
1541 | msg = _('created %s') % short(n) | |
1542 | return msg, n, rejects |
|
1542 | return msg, n, rejects | |
1543 |
|
1543 | |||
1544 | # facility to let extensions include additional data in an exported patch |
|
1544 | # facility to let extensions include additional data in an exported patch | |
1545 | # list of identifiers to be executed in order |
|
1545 | # list of identifiers to be executed in order | |
1546 | extraexport = [] |
|
1546 | extraexport = [] | |
1547 | # mapping from identifier to actual export function |
|
1547 | # mapping from identifier to actual export function | |
1548 | # function as to return a string to be added to the header or None |
|
1548 | # function as to return a string to be added to the header or None | |
1549 | # it is given two arguments (sequencenumber, changectx) |
|
1549 | # it is given two arguments (sequencenumber, changectx) | |
1550 | extraexportmap = {} |
|
1550 | extraexportmap = {} | |
1551 |
|
1551 | |||
1552 | def _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts): |
|
1552 | def _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts): | |
1553 | node = scmutil.binnode(ctx) |
|
1553 | node = scmutil.binnode(ctx) | |
1554 | parents = [p.node() for p in ctx.parents() if p] |
|
1554 | parents = [p.node() for p in ctx.parents() if p] | |
1555 | branch = ctx.branch() |
|
1555 | branch = ctx.branch() | |
1556 | if switch_parent: |
|
1556 | if switch_parent: | |
1557 | parents.reverse() |
|
1557 | parents.reverse() | |
1558 |
|
1558 | |||
1559 | if parents: |
|
1559 | if parents: | |
1560 | prev = parents[0] |
|
1560 | prev = parents[0] | |
1561 | else: |
|
1561 | else: | |
1562 | prev = nullid |
|
1562 | prev = nullid | |
1563 |
|
1563 | |||
1564 | fm.context(ctx=ctx) |
|
1564 | fm.context(ctx=ctx) | |
1565 | fm.plain('# HG changeset patch\n') |
|
1565 | fm.plain('# HG changeset patch\n') | |
1566 | fm.write('user', '# User %s\n', ctx.user()) |
|
1566 | fm.write('user', '# User %s\n', ctx.user()) | |
1567 | fm.plain('# Date %d %d\n' % ctx.date()) |
|
1567 | fm.plain('# Date %d %d\n' % ctx.date()) | |
1568 | fm.write('date', '# %s\n', fm.formatdate(ctx.date())) |
|
1568 | fm.write('date', '# %s\n', fm.formatdate(ctx.date())) | |
1569 | fm.condwrite(branch and branch != 'default', |
|
1569 | fm.condwrite(branch and branch != 'default', | |
1570 | 'branch', '# Branch %s\n', branch) |
|
1570 | 'branch', '# Branch %s\n', branch) | |
1571 | fm.write('node', '# Node ID %s\n', hex(node)) |
|
1571 | fm.write('node', '# Node ID %s\n', hex(node)) | |
1572 | fm.plain('# Parent %s\n' % hex(prev)) |
|
1572 | fm.plain('# Parent %s\n' % hex(prev)) | |
1573 | if len(parents) > 1: |
|
1573 | if len(parents) > 1: | |
1574 | fm.plain('# Parent %s\n' % hex(parents[1])) |
|
1574 | fm.plain('# Parent %s\n' % hex(parents[1])) | |
1575 | fm.data(parents=fm.formatlist(pycompat.maplist(hex, parents), name='node')) |
|
1575 | fm.data(parents=fm.formatlist(pycompat.maplist(hex, parents), name='node')) | |
1576 |
|
1576 | |||
1577 | # TODO: redesign extraexportmap function to support formatter |
|
1577 | # TODO: redesign extraexportmap function to support formatter | |
1578 | for headerid in extraexport: |
|
1578 | for headerid in extraexport: | |
1579 | header = extraexportmap[headerid](seqno, ctx) |
|
1579 | header = extraexportmap[headerid](seqno, ctx) | |
1580 | if header is not None: |
|
1580 | if header is not None: | |
1581 | fm.plain('# %s\n' % header) |
|
1581 | fm.plain('# %s\n' % header) | |
1582 |
|
1582 | |||
1583 | fm.write('desc', '%s\n', ctx.description().rstrip()) |
|
1583 | fm.write('desc', '%s\n', ctx.description().rstrip()) | |
1584 | fm.plain('\n') |
|
1584 | fm.plain('\n') | |
1585 |
|
1585 | |||
1586 | if fm.isplain(): |
|
1586 | if fm.isplain(): | |
1587 | chunkiter = patch.diffui(repo, prev, node, match, opts=diffopts) |
|
1587 | chunkiter = patch.diffui(repo, prev, node, match, opts=diffopts) | |
1588 | for chunk, label in chunkiter: |
|
1588 | for chunk, label in chunkiter: | |
1589 | fm.plain(chunk, label=label) |
|
1589 | fm.plain(chunk, label=label) | |
1590 | else: |
|
1590 | else: | |
1591 | chunkiter = patch.diff(repo, prev, node, match, opts=diffopts) |
|
1591 | chunkiter = patch.diff(repo, prev, node, match, opts=diffopts) | |
1592 | # TODO: make it structured? |
|
1592 | # TODO: make it structured? | |
1593 | fm.data(diff=b''.join(chunkiter)) |
|
1593 | fm.data(diff=b''.join(chunkiter)) | |
1594 |
|
1594 | |||
1595 | def _exportfile(repo, revs, fm, dest, switch_parent, diffopts, match): |
|
1595 | def _exportfile(repo, revs, fm, dest, switch_parent, diffopts, match): | |
1596 | """Export changesets to stdout or a single file""" |
|
1596 | """Export changesets to stdout or a single file""" | |
1597 | for seqno, rev in enumerate(revs, 1): |
|
1597 | for seqno, rev in enumerate(revs, 1): | |
1598 | ctx = repo[rev] |
|
1598 | ctx = repo[rev] | |
1599 | if not dest.startswith('<'): |
|
1599 | if not dest.startswith('<'): | |
1600 | repo.ui.note("%s\n" % dest) |
|
1600 | repo.ui.note("%s\n" % dest) | |
1601 | fm.startitem() |
|
1601 | fm.startitem() | |
1602 | _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts) |
|
1602 | _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts) | |
1603 |
|
1603 | |||
1604 | def _exportfntemplate(repo, revs, basefm, fntemplate, switch_parent, diffopts, |
|
1604 | def _exportfntemplate(repo, revs, basefm, fntemplate, switch_parent, diffopts, | |
1605 | match): |
|
1605 | match): | |
1606 | """Export changesets to possibly multiple files""" |
|
1606 | """Export changesets to possibly multiple files""" | |
1607 | total = len(revs) |
|
1607 | total = len(revs) | |
1608 | revwidth = max(len(str(rev)) for rev in revs) |
|
1608 | revwidth = max(len(str(rev)) for rev in revs) | |
1609 | filemap = util.sortdict() # filename: [(seqno, rev), ...] |
|
1609 | filemap = util.sortdict() # filename: [(seqno, rev), ...] | |
1610 |
|
1610 | |||
1611 | for seqno, rev in enumerate(revs, 1): |
|
1611 | for seqno, rev in enumerate(revs, 1): | |
1612 | ctx = repo[rev] |
|
1612 | ctx = repo[rev] | |
1613 | dest = makefilename(ctx, fntemplate, |
|
1613 | dest = makefilename(ctx, fntemplate, | |
1614 | total=total, seqno=seqno, revwidth=revwidth) |
|
1614 | total=total, seqno=seqno, revwidth=revwidth) | |
1615 | filemap.setdefault(dest, []).append((seqno, rev)) |
|
1615 | filemap.setdefault(dest, []).append((seqno, rev)) | |
1616 |
|
1616 | |||
1617 | for dest in filemap: |
|
1617 | for dest in filemap: | |
1618 | with formatter.maybereopen(basefm, dest) as fm: |
|
1618 | with formatter.maybereopen(basefm, dest) as fm: | |
1619 | repo.ui.note("%s\n" % dest) |
|
1619 | repo.ui.note("%s\n" % dest) | |
1620 | for seqno, rev in filemap[dest]: |
|
1620 | for seqno, rev in filemap[dest]: | |
1621 | fm.startitem() |
|
1621 | fm.startitem() | |
1622 | ctx = repo[rev] |
|
1622 | ctx = repo[rev] | |
1623 | _exportsingle(repo, ctx, fm, match, switch_parent, seqno, |
|
1623 | _exportsingle(repo, ctx, fm, match, switch_parent, seqno, | |
1624 | diffopts) |
|
1624 | diffopts) | |
1625 |
|
1625 | |||
1626 | def export(repo, revs, basefm, fntemplate='hg-%h.patch', switch_parent=False, |
|
1626 | def export(repo, revs, basefm, fntemplate='hg-%h.patch', switch_parent=False, | |
1627 | opts=None, match=None): |
|
1627 | opts=None, match=None): | |
1628 | '''export changesets as hg patches |
|
1628 | '''export changesets as hg patches | |
1629 |
|
1629 | |||
1630 | Args: |
|
1630 | Args: | |
1631 | repo: The repository from which we're exporting revisions. |
|
1631 | repo: The repository from which we're exporting revisions. | |
1632 | revs: A list of revisions to export as revision numbers. |
|
1632 | revs: A list of revisions to export as revision numbers. | |
1633 | basefm: A formatter to which patches should be written. |
|
1633 | basefm: A formatter to which patches should be written. | |
1634 | fntemplate: An optional string to use for generating patch file names. |
|
1634 | fntemplate: An optional string to use for generating patch file names. | |
1635 | switch_parent: If True, show diffs against second parent when not nullid. |
|
1635 | switch_parent: If True, show diffs against second parent when not nullid. | |
1636 | Default is false, which always shows diff against p1. |
|
1636 | Default is false, which always shows diff against p1. | |
1637 | opts: diff options to use for generating the patch. |
|
1637 | opts: diff options to use for generating the patch. | |
1638 | match: If specified, only export changes to files matching this matcher. |
|
1638 | match: If specified, only export changes to files matching this matcher. | |
1639 |
|
1639 | |||
1640 | Returns: |
|
1640 | Returns: | |
1641 | Nothing. |
|
1641 | Nothing. | |
1642 |
|
1642 | |||
1643 | Side Effect: |
|
1643 | Side Effect: | |
1644 | "HG Changeset Patch" data is emitted to one of the following |
|
1644 | "HG Changeset Patch" data is emitted to one of the following | |
1645 | destinations: |
|
1645 | destinations: | |
1646 | fntemplate specified: Each rev is written to a unique file named using |
|
1646 | fntemplate specified: Each rev is written to a unique file named using | |
1647 | the given template. |
|
1647 | the given template. | |
1648 | Otherwise: All revs will be written to basefm. |
|
1648 | Otherwise: All revs will be written to basefm. | |
1649 | ''' |
|
1649 | ''' | |
1650 | scmutil.prefetchfiles(repo, revs, match) |
|
1650 | scmutil.prefetchfiles(repo, revs, match) | |
1651 |
|
1651 | |||
1652 | if not fntemplate: |
|
1652 | if not fntemplate: | |
1653 | _exportfile(repo, revs, basefm, '<unnamed>', switch_parent, opts, match) |
|
1653 | _exportfile(repo, revs, basefm, '<unnamed>', switch_parent, opts, match) | |
1654 | else: |
|
1654 | else: | |
1655 | _exportfntemplate(repo, revs, basefm, fntemplate, switch_parent, opts, |
|
1655 | _exportfntemplate(repo, revs, basefm, fntemplate, switch_parent, opts, | |
1656 | match) |
|
1656 | match) | |
1657 |
|
1657 | |||
1658 | def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None): |
|
1658 | def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None): | |
1659 | """Export changesets to the given file stream""" |
|
1659 | """Export changesets to the given file stream""" | |
1660 | scmutil.prefetchfiles(repo, revs, match) |
|
1660 | scmutil.prefetchfiles(repo, revs, match) | |
1661 |
|
1661 | |||
1662 | dest = getattr(fp, 'name', '<unnamed>') |
|
1662 | dest = getattr(fp, 'name', '<unnamed>') | |
1663 | with formatter.formatter(repo.ui, fp, 'export', {}) as fm: |
|
1663 | with formatter.formatter(repo.ui, fp, 'export', {}) as fm: | |
1664 | _exportfile(repo, revs, fm, dest, switch_parent, opts, match) |
|
1664 | _exportfile(repo, revs, fm, dest, switch_parent, opts, match) | |
1665 |
|
1665 | |||
1666 | def showmarker(fm, marker, index=None): |
|
1666 | def showmarker(fm, marker, index=None): | |
1667 | """utility function to display obsolescence marker in a readable way |
|
1667 | """utility function to display obsolescence marker in a readable way | |
1668 |
|
1668 | |||
1669 | To be used by debug function.""" |
|
1669 | To be used by debug function.""" | |
1670 | if index is not None: |
|
1670 | if index is not None: | |
1671 | fm.write('index', '%i ', index) |
|
1671 | fm.write('index', '%i ', index) | |
1672 | fm.write('prednode', '%s ', hex(marker.prednode())) |
|
1672 | fm.write('prednode', '%s ', hex(marker.prednode())) | |
1673 | succs = marker.succnodes() |
|
1673 | succs = marker.succnodes() | |
1674 | fm.condwrite(succs, 'succnodes', '%s ', |
|
1674 | fm.condwrite(succs, 'succnodes', '%s ', | |
1675 | fm.formatlist(map(hex, succs), name='node')) |
|
1675 | fm.formatlist(map(hex, succs), name='node')) | |
1676 | fm.write('flag', '%X ', marker.flags()) |
|
1676 | fm.write('flag', '%X ', marker.flags()) | |
1677 | parents = marker.parentnodes() |
|
1677 | parents = marker.parentnodes() | |
1678 | if parents is not None: |
|
1678 | if parents is not None: | |
1679 | fm.write('parentnodes', '{%s} ', |
|
1679 | fm.write('parentnodes', '{%s} ', | |
1680 | fm.formatlist(map(hex, parents), name='node', sep=', ')) |
|
1680 | fm.formatlist(map(hex, parents), name='node', sep=', ')) | |
1681 | fm.write('date', '(%s) ', fm.formatdate(marker.date())) |
|
1681 | fm.write('date', '(%s) ', fm.formatdate(marker.date())) | |
1682 | meta = marker.metadata().copy() |
|
1682 | meta = marker.metadata().copy() | |
1683 | meta.pop('date', None) |
|
1683 | meta.pop('date', None) | |
1684 | smeta = pycompat.rapply(pycompat.maybebytestr, meta) |
|
1684 | smeta = pycompat.rapply(pycompat.maybebytestr, meta) | |
1685 | fm.write('metadata', '{%s}', fm.formatdict(smeta, fmt='%r: %r', sep=', ')) |
|
1685 | fm.write('metadata', '{%s}', fm.formatdict(smeta, fmt='%r: %r', sep=', ')) | |
1686 | fm.plain('\n') |
|
1686 | fm.plain('\n') | |
1687 |
|
1687 | |||
1688 | def finddate(ui, repo, date): |
|
1688 | def finddate(ui, repo, date): | |
1689 | """Find the tipmost changeset that matches the given date spec""" |
|
1689 | """Find the tipmost changeset that matches the given date spec""" | |
1690 |
|
1690 | |||
1691 | df = dateutil.matchdate(date) |
|
1691 | df = dateutil.matchdate(date) | |
1692 | m = scmutil.matchall(repo) |
|
1692 | m = scmutil.matchall(repo) | |
1693 | results = {} |
|
1693 | results = {} | |
1694 |
|
1694 | |||
1695 | def prep(ctx, fns): |
|
1695 | def prep(ctx, fns): | |
1696 | d = ctx.date() |
|
1696 | d = ctx.date() | |
1697 | if df(d[0]): |
|
1697 | if df(d[0]): | |
1698 | results[ctx.rev()] = d |
|
1698 | results[ctx.rev()] = d | |
1699 |
|
1699 | |||
1700 | for ctx in walkchangerevs(repo, m, {'rev': None}, prep): |
|
1700 | for ctx in walkchangerevs(repo, m, {'rev': None}, prep): | |
1701 | rev = ctx.rev() |
|
1701 | rev = ctx.rev() | |
1702 | if rev in results: |
|
1702 | if rev in results: | |
1703 | ui.status(_("found revision %s from %s\n") % |
|
1703 | ui.status(_("found revision %s from %s\n") % | |
1704 | (rev, dateutil.datestr(results[rev]))) |
|
1704 | (rev, dateutil.datestr(results[rev]))) | |
1705 | return '%d' % rev |
|
1705 | return '%d' % rev | |
1706 |
|
1706 | |||
1707 | raise error.Abort(_("revision matching date not found")) |
|
1707 | raise error.Abort(_("revision matching date not found")) | |
1708 |
|
1708 | |||
1709 | def increasingwindows(windowsize=8, sizelimit=512): |
|
1709 | def increasingwindows(windowsize=8, sizelimit=512): | |
1710 | while True: |
|
1710 | while True: | |
1711 | yield windowsize |
|
1711 | yield windowsize | |
1712 | if windowsize < sizelimit: |
|
1712 | if windowsize < sizelimit: | |
1713 | windowsize *= 2 |
|
1713 | windowsize *= 2 | |
1714 |
|
1714 | |||
1715 | def _walkrevs(repo, opts): |
|
1715 | def _walkrevs(repo, opts): | |
1716 | # Default --rev value depends on --follow but --follow behavior |
|
1716 | # Default --rev value depends on --follow but --follow behavior | |
1717 | # depends on revisions resolved from --rev... |
|
1717 | # depends on revisions resolved from --rev... | |
1718 | follow = opts.get('follow') or opts.get('follow_first') |
|
1718 | follow = opts.get('follow') or opts.get('follow_first') | |
1719 | if opts.get('rev'): |
|
1719 | if opts.get('rev'): | |
1720 | revs = scmutil.revrange(repo, opts['rev']) |
|
1720 | revs = scmutil.revrange(repo, opts['rev']) | |
1721 | elif follow and repo.dirstate.p1() == nullid: |
|
1721 | elif follow and repo.dirstate.p1() == nullid: | |
1722 | revs = smartset.baseset() |
|
1722 | revs = smartset.baseset() | |
1723 | elif follow: |
|
1723 | elif follow: | |
1724 | revs = repo.revs('reverse(:.)') |
|
1724 | revs = repo.revs('reverse(:.)') | |
1725 | else: |
|
1725 | else: | |
1726 | revs = smartset.spanset(repo) |
|
1726 | revs = smartset.spanset(repo) | |
1727 | revs.reverse() |
|
1727 | revs.reverse() | |
1728 | return revs |
|
1728 | return revs | |
1729 |
|
1729 | |||
1730 | class FileWalkError(Exception): |
|
1730 | class FileWalkError(Exception): | |
1731 | pass |
|
1731 | pass | |
1732 |
|
1732 | |||
1733 | def walkfilerevs(repo, match, follow, revs, fncache): |
|
1733 | def walkfilerevs(repo, match, follow, revs, fncache): | |
1734 | '''Walks the file history for the matched files. |
|
1734 | '''Walks the file history for the matched files. | |
1735 |
|
1735 | |||
1736 | Returns the changeset revs that are involved in the file history. |
|
1736 | Returns the changeset revs that are involved in the file history. | |
1737 |
|
1737 | |||
1738 | Throws FileWalkError if the file history can't be walked using |
|
1738 | Throws FileWalkError if the file history can't be walked using | |
1739 | filelogs alone. |
|
1739 | filelogs alone. | |
1740 | ''' |
|
1740 | ''' | |
1741 | wanted = set() |
|
1741 | wanted = set() | |
1742 | copies = [] |
|
1742 | copies = [] | |
1743 | minrev, maxrev = min(revs), max(revs) |
|
1743 | minrev, maxrev = min(revs), max(revs) | |
1744 | def filerevgen(filelog, last): |
|
1744 | def filerevgen(filelog, last): | |
1745 | """ |
|
1745 | """ | |
1746 | Only files, no patterns. Check the history of each file. |
|
1746 | Only files, no patterns. Check the history of each file. | |
1747 |
|
1747 | |||
1748 | Examines filelog entries within minrev, maxrev linkrev range |
|
1748 | Examines filelog entries within minrev, maxrev linkrev range | |
1749 | Returns an iterator yielding (linkrev, parentlinkrevs, copied) |
|
1749 | Returns an iterator yielding (linkrev, parentlinkrevs, copied) | |
1750 | tuples in backwards order |
|
1750 | tuples in backwards order | |
1751 | """ |
|
1751 | """ | |
1752 | cl_count = len(repo) |
|
1752 | cl_count = len(repo) | |
1753 | revs = [] |
|
1753 | revs = [] | |
1754 | for j in pycompat.xrange(0, last + 1): |
|
1754 | for j in pycompat.xrange(0, last + 1): | |
1755 | linkrev = filelog.linkrev(j) |
|
1755 | linkrev = filelog.linkrev(j) | |
1756 | if linkrev < minrev: |
|
1756 | if linkrev < minrev: | |
1757 | continue |
|
1757 | continue | |
1758 | # only yield rev for which we have the changelog, it can |
|
1758 | # only yield rev for which we have the changelog, it can | |
1759 | # happen while doing "hg log" during a pull or commit |
|
1759 | # happen while doing "hg log" during a pull or commit | |
1760 | if linkrev >= cl_count: |
|
1760 | if linkrev >= cl_count: | |
1761 | break |
|
1761 | break | |
1762 |
|
1762 | |||
1763 | parentlinkrevs = [] |
|
1763 | parentlinkrevs = [] | |
1764 | for p in filelog.parentrevs(j): |
|
1764 | for p in filelog.parentrevs(j): | |
1765 | if p != nullrev: |
|
1765 | if p != nullrev: | |
1766 | parentlinkrevs.append(filelog.linkrev(p)) |
|
1766 | parentlinkrevs.append(filelog.linkrev(p)) | |
1767 | n = filelog.node(j) |
|
1767 | n = filelog.node(j) | |
1768 | revs.append((linkrev, parentlinkrevs, |
|
1768 | revs.append((linkrev, parentlinkrevs, | |
1769 | follow and filelog.renamed(n))) |
|
1769 | follow and filelog.renamed(n))) | |
1770 |
|
1770 | |||
1771 | return reversed(revs) |
|
1771 | return reversed(revs) | |
1772 | def iterfiles(): |
|
1772 | def iterfiles(): | |
1773 | pctx = repo['.'] |
|
1773 | pctx = repo['.'] | |
1774 | for filename in match.files(): |
|
1774 | for filename in match.files(): | |
1775 | if follow: |
|
1775 | if follow: | |
1776 | if filename not in pctx: |
|
1776 | if filename not in pctx: | |
1777 | raise error.Abort(_('cannot follow file not in parent ' |
|
1777 | raise error.Abort(_('cannot follow file not in parent ' | |
1778 | 'revision: "%s"') % filename) |
|
1778 | 'revision: "%s"') % filename) | |
1779 | yield filename, pctx[filename].filenode() |
|
1779 | yield filename, pctx[filename].filenode() | |
1780 | else: |
|
1780 | else: | |
1781 | yield filename, None |
|
1781 | yield filename, None | |
1782 | for filename_node in copies: |
|
1782 | for filename_node in copies: | |
1783 | yield filename_node |
|
1783 | yield filename_node | |
1784 |
|
1784 | |||
1785 | for file_, node in iterfiles(): |
|
1785 | for file_, node in iterfiles(): | |
1786 | filelog = repo.file(file_) |
|
1786 | filelog = repo.file(file_) | |
1787 | if not len(filelog): |
|
1787 | if not len(filelog): | |
1788 | if node is None: |
|
1788 | if node is None: | |
1789 | # A zero count may be a directory or deleted file, so |
|
1789 | # A zero count may be a directory or deleted file, so | |
1790 | # try to find matching entries on the slow path. |
|
1790 | # try to find matching entries on the slow path. | |
1791 | if follow: |
|
1791 | if follow: | |
1792 | raise error.Abort( |
|
1792 | raise error.Abort( | |
1793 | _('cannot follow nonexistent file: "%s"') % file_) |
|
1793 | _('cannot follow nonexistent file: "%s"') % file_) | |
1794 | raise FileWalkError("Cannot walk via filelog") |
|
1794 | raise FileWalkError("Cannot walk via filelog") | |
1795 | else: |
|
1795 | else: | |
1796 | continue |
|
1796 | continue | |
1797 |
|
1797 | |||
1798 | if node is None: |
|
1798 | if node is None: | |
1799 | last = len(filelog) - 1 |
|
1799 | last = len(filelog) - 1 | |
1800 | else: |
|
1800 | else: | |
1801 | last = filelog.rev(node) |
|
1801 | last = filelog.rev(node) | |
1802 |
|
1802 | |||
1803 | # keep track of all ancestors of the file |
|
1803 | # keep track of all ancestors of the file | |
1804 | ancestors = {filelog.linkrev(last)} |
|
1804 | ancestors = {filelog.linkrev(last)} | |
1805 |
|
1805 | |||
1806 | # iterate from latest to oldest revision |
|
1806 | # iterate from latest to oldest revision | |
1807 | for rev, flparentlinkrevs, copied in filerevgen(filelog, last): |
|
1807 | for rev, flparentlinkrevs, copied in filerevgen(filelog, last): | |
1808 | if not follow: |
|
1808 | if not follow: | |
1809 | if rev > maxrev: |
|
1809 | if rev > maxrev: | |
1810 | continue |
|
1810 | continue | |
1811 | else: |
|
1811 | else: | |
1812 | # Note that last might not be the first interesting |
|
1812 | # Note that last might not be the first interesting | |
1813 | # rev to us: |
|
1813 | # rev to us: | |
1814 | # if the file has been changed after maxrev, we'll |
|
1814 | # if the file has been changed after maxrev, we'll | |
1815 | # have linkrev(last) > maxrev, and we still need |
|
1815 | # have linkrev(last) > maxrev, and we still need | |
1816 | # to explore the file graph |
|
1816 | # to explore the file graph | |
1817 | if rev not in ancestors: |
|
1817 | if rev not in ancestors: | |
1818 | continue |
|
1818 | continue | |
1819 | # XXX insert 1327 fix here |
|
1819 | # XXX insert 1327 fix here | |
1820 | if flparentlinkrevs: |
|
1820 | if flparentlinkrevs: | |
1821 | ancestors.update(flparentlinkrevs) |
|
1821 | ancestors.update(flparentlinkrevs) | |
1822 |
|
1822 | |||
1823 | fncache.setdefault(rev, []).append(file_) |
|
1823 | fncache.setdefault(rev, []).append(file_) | |
1824 | wanted.add(rev) |
|
1824 | wanted.add(rev) | |
1825 | if copied: |
|
1825 | if copied: | |
1826 | copies.append(copied) |
|
1826 | copies.append(copied) | |
1827 |
|
1827 | |||
1828 | return wanted |
|
1828 | return wanted | |
1829 |
|
1829 | |||
1830 | class _followfilter(object): |
|
1830 | class _followfilter(object): | |
1831 | def __init__(self, repo, onlyfirst=False): |
|
1831 | def __init__(self, repo, onlyfirst=False): | |
1832 | self.repo = repo |
|
1832 | self.repo = repo | |
1833 | self.startrev = nullrev |
|
1833 | self.startrev = nullrev | |
1834 | self.roots = set() |
|
1834 | self.roots = set() | |
1835 | self.onlyfirst = onlyfirst |
|
1835 | self.onlyfirst = onlyfirst | |
1836 |
|
1836 | |||
1837 | def match(self, rev): |
|
1837 | def match(self, rev): | |
1838 | def realparents(rev): |
|
1838 | def realparents(rev): | |
1839 | if self.onlyfirst: |
|
1839 | if self.onlyfirst: | |
1840 | return self.repo.changelog.parentrevs(rev)[0:1] |
|
1840 | return self.repo.changelog.parentrevs(rev)[0:1] | |
1841 | else: |
|
1841 | else: | |
1842 | return filter(lambda x: x != nullrev, |
|
1842 | return filter(lambda x: x != nullrev, | |
1843 | self.repo.changelog.parentrevs(rev)) |
|
1843 | self.repo.changelog.parentrevs(rev)) | |
1844 |
|
1844 | |||
1845 | if self.startrev == nullrev: |
|
1845 | if self.startrev == nullrev: | |
1846 | self.startrev = rev |
|
1846 | self.startrev = rev | |
1847 | return True |
|
1847 | return True | |
1848 |
|
1848 | |||
1849 | if rev > self.startrev: |
|
1849 | if rev > self.startrev: | |
1850 | # forward: all descendants |
|
1850 | # forward: all descendants | |
1851 | if not self.roots: |
|
1851 | if not self.roots: | |
1852 | self.roots.add(self.startrev) |
|
1852 | self.roots.add(self.startrev) | |
1853 | for parent in realparents(rev): |
|
1853 | for parent in realparents(rev): | |
1854 | if parent in self.roots: |
|
1854 | if parent in self.roots: | |
1855 | self.roots.add(rev) |
|
1855 | self.roots.add(rev) | |
1856 | return True |
|
1856 | return True | |
1857 | else: |
|
1857 | else: | |
1858 | # backwards: all parents |
|
1858 | # backwards: all parents | |
1859 | if not self.roots: |
|
1859 | if not self.roots: | |
1860 | self.roots.update(realparents(self.startrev)) |
|
1860 | self.roots.update(realparents(self.startrev)) | |
1861 | if rev in self.roots: |
|
1861 | if rev in self.roots: | |
1862 | self.roots.remove(rev) |
|
1862 | self.roots.remove(rev) | |
1863 | self.roots.update(realparents(rev)) |
|
1863 | self.roots.update(realparents(rev)) | |
1864 | return True |
|
1864 | return True | |
1865 |
|
1865 | |||
1866 | return False |
|
1866 | return False | |
1867 |
|
1867 | |||
1868 | def walkchangerevs(repo, match, opts, prepare): |
|
1868 | def walkchangerevs(repo, match, opts, prepare): | |
1869 | '''Iterate over files and the revs in which they changed. |
|
1869 | '''Iterate over files and the revs in which they changed. | |
1870 |
|
1870 | |||
1871 | Callers most commonly need to iterate backwards over the history |
|
1871 | Callers most commonly need to iterate backwards over the history | |
1872 | in which they are interested. Doing so has awful (quadratic-looking) |
|
1872 | in which they are interested. Doing so has awful (quadratic-looking) | |
1873 | performance, so we use iterators in a "windowed" way. |
|
1873 | performance, so we use iterators in a "windowed" way. | |
1874 |
|
1874 | |||
1875 | We walk a window of revisions in the desired order. Within the |
|
1875 | We walk a window of revisions in the desired order. Within the | |
1876 | window, we first walk forwards to gather data, then in the desired |
|
1876 | window, we first walk forwards to gather data, then in the desired | |
1877 | order (usually backwards) to display it. |
|
1877 | order (usually backwards) to display it. | |
1878 |
|
1878 | |||
1879 | This function returns an iterator yielding contexts. Before |
|
1879 | This function returns an iterator yielding contexts. Before | |
1880 | yielding each context, the iterator will first call the prepare |
|
1880 | yielding each context, the iterator will first call the prepare | |
1881 | function on each context in the window in forward order.''' |
|
1881 | function on each context in the window in forward order.''' | |
1882 |
|
1882 | |||
1883 | allfiles = opts.get('all_files') |
|
1883 | allfiles = opts.get('all_files') | |
1884 | follow = opts.get('follow') or opts.get('follow_first') |
|
1884 | follow = opts.get('follow') or opts.get('follow_first') | |
1885 | revs = _walkrevs(repo, opts) |
|
1885 | revs = _walkrevs(repo, opts) | |
1886 | if not revs: |
|
1886 | if not revs: | |
1887 | return [] |
|
1887 | return [] | |
1888 | wanted = set() |
|
1888 | wanted = set() | |
1889 | slowpath = match.anypats() or (not match.always() and opts.get('removed')) |
|
1889 | slowpath = match.anypats() or (not match.always() and opts.get('removed')) | |
1890 | fncache = {} |
|
1890 | fncache = {} | |
1891 | change = repo.__getitem__ |
|
1891 | change = repo.__getitem__ | |
1892 |
|
1892 | |||
1893 | # First step is to fill wanted, the set of revisions that we want to yield. |
|
1893 | # First step is to fill wanted, the set of revisions that we want to yield. | |
1894 | # When it does not induce extra cost, we also fill fncache for revisions in |
|
1894 | # When it does not induce extra cost, we also fill fncache for revisions in | |
1895 | # wanted: a cache of filenames that were changed (ctx.files()) and that |
|
1895 | # wanted: a cache of filenames that were changed (ctx.files()) and that | |
1896 | # match the file filtering conditions. |
|
1896 | # match the file filtering conditions. | |
1897 |
|
1897 | |||
1898 | if match.always() or allfiles: |
|
1898 | if match.always() or allfiles: | |
1899 | # No files, no patterns. Display all revs. |
|
1899 | # No files, no patterns. Display all revs. | |
1900 | wanted = revs |
|
1900 | wanted = revs | |
1901 | elif not slowpath: |
|
1901 | elif not slowpath: | |
1902 | # We only have to read through the filelog to find wanted revisions |
|
1902 | # We only have to read through the filelog to find wanted revisions | |
1903 |
|
1903 | |||
1904 | try: |
|
1904 | try: | |
1905 | wanted = walkfilerevs(repo, match, follow, revs, fncache) |
|
1905 | wanted = walkfilerevs(repo, match, follow, revs, fncache) | |
1906 | except FileWalkError: |
|
1906 | except FileWalkError: | |
1907 | slowpath = True |
|
1907 | slowpath = True | |
1908 |
|
1908 | |||
1909 | # We decided to fall back to the slowpath because at least one |
|
1909 | # We decided to fall back to the slowpath because at least one | |
1910 | # of the paths was not a file. Check to see if at least one of them |
|
1910 | # of the paths was not a file. Check to see if at least one of them | |
1911 | # existed in history, otherwise simply return |
|
1911 | # existed in history, otherwise simply return | |
1912 | for path in match.files(): |
|
1912 | for path in match.files(): | |
1913 | if path == '.' or path in repo.store: |
|
1913 | if path == '.' or path in repo.store: | |
1914 | break |
|
1914 | break | |
1915 | else: |
|
1915 | else: | |
1916 | return [] |
|
1916 | return [] | |
1917 |
|
1917 | |||
1918 | if slowpath: |
|
1918 | if slowpath: | |
1919 | # We have to read the changelog to match filenames against |
|
1919 | # We have to read the changelog to match filenames against | |
1920 | # changed files |
|
1920 | # changed files | |
1921 |
|
1921 | |||
1922 | if follow: |
|
1922 | if follow: | |
1923 | raise error.Abort(_('can only follow copies/renames for explicit ' |
|
1923 | raise error.Abort(_('can only follow copies/renames for explicit ' | |
1924 | 'filenames')) |
|
1924 | 'filenames')) | |
1925 |
|
1925 | |||
1926 | # The slow path checks files modified in every changeset. |
|
1926 | # The slow path checks files modified in every changeset. | |
1927 | # This is really slow on large repos, so compute the set lazily. |
|
1927 | # This is really slow on large repos, so compute the set lazily. | |
1928 | class lazywantedset(object): |
|
1928 | class lazywantedset(object): | |
1929 | def __init__(self): |
|
1929 | def __init__(self): | |
1930 | self.set = set() |
|
1930 | self.set = set() | |
1931 | self.revs = set(revs) |
|
1931 | self.revs = set(revs) | |
1932 |
|
1932 | |||
1933 | # No need to worry about locality here because it will be accessed |
|
1933 | # No need to worry about locality here because it will be accessed | |
1934 | # in the same order as the increasing window below. |
|
1934 | # in the same order as the increasing window below. | |
1935 | def __contains__(self, value): |
|
1935 | def __contains__(self, value): | |
1936 | if value in self.set: |
|
1936 | if value in self.set: | |
1937 | return True |
|
1937 | return True | |
1938 | elif not value in self.revs: |
|
1938 | elif not value in self.revs: | |
1939 | return False |
|
1939 | return False | |
1940 | else: |
|
1940 | else: | |
1941 | self.revs.discard(value) |
|
1941 | self.revs.discard(value) | |
1942 | ctx = change(value) |
|
1942 | ctx = change(value) | |
1943 | matches = [f for f in ctx.files() if match(f)] |
|
1943 | matches = [f for f in ctx.files() if match(f)] | |
1944 | if matches: |
|
1944 | if matches: | |
1945 | fncache[value] = matches |
|
1945 | fncache[value] = matches | |
1946 | self.set.add(value) |
|
1946 | self.set.add(value) | |
1947 | return True |
|
1947 | return True | |
1948 | return False |
|
1948 | return False | |
1949 |
|
1949 | |||
1950 | def discard(self, value): |
|
1950 | def discard(self, value): | |
1951 | self.revs.discard(value) |
|
1951 | self.revs.discard(value) | |
1952 | self.set.discard(value) |
|
1952 | self.set.discard(value) | |
1953 |
|
1953 | |||
1954 | wanted = lazywantedset() |
|
1954 | wanted = lazywantedset() | |
1955 |
|
1955 | |||
1956 | # it might be worthwhile to do this in the iterator if the rev range |
|
1956 | # it might be worthwhile to do this in the iterator if the rev range | |
1957 | # is descending and the prune args are all within that range |
|
1957 | # is descending and the prune args are all within that range | |
1958 | for rev in opts.get('prune', ()): |
|
1958 | for rev in opts.get('prune', ()): | |
1959 | rev = repo[rev].rev() |
|
1959 | rev = repo[rev].rev() | |
1960 | ff = _followfilter(repo) |
|
1960 | ff = _followfilter(repo) | |
1961 | stop = min(revs[0], revs[-1]) |
|
1961 | stop = min(revs[0], revs[-1]) | |
1962 | for x in pycompat.xrange(rev, stop - 1, -1): |
|
1962 | for x in pycompat.xrange(rev, stop - 1, -1): | |
1963 | if ff.match(x): |
|
1963 | if ff.match(x): | |
1964 | wanted = wanted - [x] |
|
1964 | wanted = wanted - [x] | |
1965 |
|
1965 | |||
1966 | # Now that wanted is correctly initialized, we can iterate over the |
|
1966 | # Now that wanted is correctly initialized, we can iterate over the | |
1967 | # revision range, yielding only revisions in wanted. |
|
1967 | # revision range, yielding only revisions in wanted. | |
1968 | def iterate(): |
|
1968 | def iterate(): | |
1969 | if follow and match.always(): |
|
1969 | if follow and match.always(): | |
1970 | ff = _followfilter(repo, onlyfirst=opts.get('follow_first')) |
|
1970 | ff = _followfilter(repo, onlyfirst=opts.get('follow_first')) | |
1971 | def want(rev): |
|
1971 | def want(rev): | |
1972 | return ff.match(rev) and rev in wanted |
|
1972 | return ff.match(rev) and rev in wanted | |
1973 | else: |
|
1973 | else: | |
1974 | def want(rev): |
|
1974 | def want(rev): | |
1975 | return rev in wanted |
|
1975 | return rev in wanted | |
1976 |
|
1976 | |||
1977 | it = iter(revs) |
|
1977 | it = iter(revs) | |
1978 | stopiteration = False |
|
1978 | stopiteration = False | |
1979 | for windowsize in increasingwindows(): |
|
1979 | for windowsize in increasingwindows(): | |
1980 | nrevs = [] |
|
1980 | nrevs = [] | |
1981 | for i in pycompat.xrange(windowsize): |
|
1981 | for i in pycompat.xrange(windowsize): | |
1982 | rev = next(it, None) |
|
1982 | rev = next(it, None) | |
1983 | if rev is None: |
|
1983 | if rev is None: | |
1984 | stopiteration = True |
|
1984 | stopiteration = True | |
1985 | break |
|
1985 | break | |
1986 | elif want(rev): |
|
1986 | elif want(rev): | |
1987 | nrevs.append(rev) |
|
1987 | nrevs.append(rev) | |
1988 | for rev in sorted(nrevs): |
|
1988 | for rev in sorted(nrevs): | |
1989 | fns = fncache.get(rev) |
|
1989 | fns = fncache.get(rev) | |
1990 | ctx = change(rev) |
|
1990 | ctx = change(rev) | |
1991 | if not fns: |
|
1991 | if not fns: | |
1992 | def fns_generator(): |
|
1992 | def fns_generator(): | |
1993 | if allfiles: |
|
1993 | if allfiles: | |
1994 | fiter = iter(ctx) |
|
1994 | fiter = iter(ctx) | |
1995 | else: |
|
1995 | else: | |
1996 | fiter = ctx.files() |
|
1996 | fiter = ctx.files() | |
1997 | for f in fiter: |
|
1997 | for f in fiter: | |
1998 | if match(f): |
|
1998 | if match(f): | |
1999 | yield f |
|
1999 | yield f | |
2000 | fns = fns_generator() |
|
2000 | fns = fns_generator() | |
2001 | prepare(ctx, fns) |
|
2001 | prepare(ctx, fns) | |
2002 | for rev in nrevs: |
|
2002 | for rev in nrevs: | |
2003 | yield change(rev) |
|
2003 | yield change(rev) | |
2004 |
|
2004 | |||
2005 | if stopiteration: |
|
2005 | if stopiteration: | |
2006 | break |
|
2006 | break | |
2007 |
|
2007 | |||
2008 | return iterate() |
|
2008 | return iterate() | |
2009 |
|
2009 | |||
2010 | def add(ui, repo, match, prefix, explicitonly, **opts): |
|
2010 | def add(ui, repo, match, prefix, explicitonly, **opts): | |
2011 | join = lambda f: os.path.join(prefix, f) |
|
2011 | join = lambda f: os.path.join(prefix, f) | |
2012 | bad = [] |
|
2012 | bad = [] | |
2013 |
|
2013 | |||
2014 | badfn = lambda x, y: bad.append(x) or match.bad(x, y) |
|
2014 | badfn = lambda x, y: bad.append(x) or match.bad(x, y) | |
2015 | names = [] |
|
2015 | names = [] | |
2016 | wctx = repo[None] |
|
2016 | wctx = repo[None] | |
2017 | cca = None |
|
2017 | cca = None | |
2018 | abort, warn = scmutil.checkportabilityalert(ui) |
|
2018 | abort, warn = scmutil.checkportabilityalert(ui) | |
2019 | if abort or warn: |
|
2019 | if abort or warn: | |
2020 | cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate) |
|
2020 | cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate) | |
2021 |
|
2021 | |||
2022 | badmatch = matchmod.badmatch(match, badfn) |
|
2022 | badmatch = matchmod.badmatch(match, badfn) | |
2023 | dirstate = repo.dirstate |
|
2023 | dirstate = repo.dirstate | |
2024 | # We don't want to just call wctx.walk here, since it would return a lot of |
|
2024 | # We don't want to just call wctx.walk here, since it would return a lot of | |
2025 | # clean files, which we aren't interested in and takes time. |
|
2025 | # clean files, which we aren't interested in and takes time. | |
2026 | for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate), |
|
2026 | for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate), | |
2027 | unknown=True, ignored=False, full=False)): |
|
2027 | unknown=True, ignored=False, full=False)): | |
2028 | exact = match.exact(f) |
|
2028 | exact = match.exact(f) | |
2029 | if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f): |
|
2029 | if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f): | |
2030 | if cca: |
|
2030 | if cca: | |
2031 | cca(f) |
|
2031 | cca(f) | |
2032 | names.append(f) |
|
2032 | names.append(f) | |
2033 | if ui.verbose or not exact: |
|
2033 | if ui.verbose or not exact: | |
2034 |
ui.status(_('adding %s\n') % match.rel(f) |
|
2034 | ui.status(_('adding %s\n') % match.rel(f), | |
|
2035 | label='addremove.added') | |||
2035 |
|
2036 | |||
2036 | for subpath in sorted(wctx.substate): |
|
2037 | for subpath in sorted(wctx.substate): | |
2037 | sub = wctx.sub(subpath) |
|
2038 | sub = wctx.sub(subpath) | |
2038 | try: |
|
2039 | try: | |
2039 | submatch = matchmod.subdirmatcher(subpath, match) |
|
2040 | submatch = matchmod.subdirmatcher(subpath, match) | |
2040 | if opts.get(r'subrepos'): |
|
2041 | if opts.get(r'subrepos'): | |
2041 | bad.extend(sub.add(ui, submatch, prefix, False, **opts)) |
|
2042 | bad.extend(sub.add(ui, submatch, prefix, False, **opts)) | |
2042 | else: |
|
2043 | else: | |
2043 | bad.extend(sub.add(ui, submatch, prefix, True, **opts)) |
|
2044 | bad.extend(sub.add(ui, submatch, prefix, True, **opts)) | |
2044 | except error.LookupError: |
|
2045 | except error.LookupError: | |
2045 | ui.status(_("skipping missing subrepository: %s\n") |
|
2046 | ui.status(_("skipping missing subrepository: %s\n") | |
2046 | % join(subpath)) |
|
2047 | % join(subpath)) | |
2047 |
|
2048 | |||
2048 | if not opts.get(r'dry_run'): |
|
2049 | if not opts.get(r'dry_run'): | |
2049 | rejected = wctx.add(names, prefix) |
|
2050 | rejected = wctx.add(names, prefix) | |
2050 | bad.extend(f for f in rejected if f in match.files()) |
|
2051 | bad.extend(f for f in rejected if f in match.files()) | |
2051 | return bad |
|
2052 | return bad | |
2052 |
|
2053 | |||
2053 | def addwebdirpath(repo, serverpath, webconf): |
|
2054 | def addwebdirpath(repo, serverpath, webconf): | |
2054 | webconf[serverpath] = repo.root |
|
2055 | webconf[serverpath] = repo.root | |
2055 | repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root)) |
|
2056 | repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root)) | |
2056 |
|
2057 | |||
2057 | for r in repo.revs('filelog("path:.hgsub")'): |
|
2058 | for r in repo.revs('filelog("path:.hgsub")'): | |
2058 | ctx = repo[r] |
|
2059 | ctx = repo[r] | |
2059 | for subpath in ctx.substate: |
|
2060 | for subpath in ctx.substate: | |
2060 | ctx.sub(subpath).addwebdirpath(serverpath, webconf) |
|
2061 | ctx.sub(subpath).addwebdirpath(serverpath, webconf) | |
2061 |
|
2062 | |||
2062 | def forget(ui, repo, match, prefix, explicitonly, dryrun, interactive): |
|
2063 | def forget(ui, repo, match, prefix, explicitonly, dryrun, interactive): | |
2063 | if dryrun and interactive: |
|
2064 | if dryrun and interactive: | |
2064 | raise error.Abort(_("cannot specify both --dry-run and --interactive")) |
|
2065 | raise error.Abort(_("cannot specify both --dry-run and --interactive")) | |
2065 | join = lambda f: os.path.join(prefix, f) |
|
2066 | join = lambda f: os.path.join(prefix, f) | |
2066 | bad = [] |
|
2067 | bad = [] | |
2067 | badfn = lambda x, y: bad.append(x) or match.bad(x, y) |
|
2068 | badfn = lambda x, y: bad.append(x) or match.bad(x, y) | |
2068 | wctx = repo[None] |
|
2069 | wctx = repo[None] | |
2069 | forgot = [] |
|
2070 | forgot = [] | |
2070 |
|
2071 | |||
2071 | s = repo.status(match=matchmod.badmatch(match, badfn), clean=True) |
|
2072 | s = repo.status(match=matchmod.badmatch(match, badfn), clean=True) | |
2072 | forget = sorted(s.modified + s.added + s.deleted + s.clean) |
|
2073 | forget = sorted(s.modified + s.added + s.deleted + s.clean) | |
2073 | if explicitonly: |
|
2074 | if explicitonly: | |
2074 | forget = [f for f in forget if match.exact(f)] |
|
2075 | forget = [f for f in forget if match.exact(f)] | |
2075 |
|
2076 | |||
2076 | for subpath in sorted(wctx.substate): |
|
2077 | for subpath in sorted(wctx.substate): | |
2077 | sub = wctx.sub(subpath) |
|
2078 | sub = wctx.sub(subpath) | |
2078 | try: |
|
2079 | try: | |
2079 | submatch = matchmod.subdirmatcher(subpath, match) |
|
2080 | submatch = matchmod.subdirmatcher(subpath, match) | |
2080 | subbad, subforgot = sub.forget(submatch, prefix, dryrun=dryrun, |
|
2081 | subbad, subforgot = sub.forget(submatch, prefix, dryrun=dryrun, | |
2081 | interactive=interactive) |
|
2082 | interactive=interactive) | |
2082 | bad.extend([subpath + '/' + f for f in subbad]) |
|
2083 | bad.extend([subpath + '/' + f for f in subbad]) | |
2083 | forgot.extend([subpath + '/' + f for f in subforgot]) |
|
2084 | forgot.extend([subpath + '/' + f for f in subforgot]) | |
2084 | except error.LookupError: |
|
2085 | except error.LookupError: | |
2085 | ui.status(_("skipping missing subrepository: %s\n") |
|
2086 | ui.status(_("skipping missing subrepository: %s\n") | |
2086 | % join(subpath)) |
|
2087 | % join(subpath)) | |
2087 |
|
2088 | |||
2088 | if not explicitonly: |
|
2089 | if not explicitonly: | |
2089 | for f in match.files(): |
|
2090 | for f in match.files(): | |
2090 | if f not in repo.dirstate and not repo.wvfs.isdir(f): |
|
2091 | if f not in repo.dirstate and not repo.wvfs.isdir(f): | |
2091 | if f not in forgot: |
|
2092 | if f not in forgot: | |
2092 | if repo.wvfs.exists(f): |
|
2093 | if repo.wvfs.exists(f): | |
2093 | # Don't complain if the exact case match wasn't given. |
|
2094 | # Don't complain if the exact case match wasn't given. | |
2094 | # But don't do this until after checking 'forgot', so |
|
2095 | # But don't do this until after checking 'forgot', so | |
2095 | # that subrepo files aren't normalized, and this op is |
|
2096 | # that subrepo files aren't normalized, and this op is | |
2096 | # purely from data cached by the status walk above. |
|
2097 | # purely from data cached by the status walk above. | |
2097 | if repo.dirstate.normalize(f) in repo.dirstate: |
|
2098 | if repo.dirstate.normalize(f) in repo.dirstate: | |
2098 | continue |
|
2099 | continue | |
2099 | ui.warn(_('not removing %s: ' |
|
2100 | ui.warn(_('not removing %s: ' | |
2100 | 'file is already untracked\n') |
|
2101 | 'file is already untracked\n') | |
2101 | % match.rel(f)) |
|
2102 | % match.rel(f)) | |
2102 | bad.append(f) |
|
2103 | bad.append(f) | |
2103 |
|
2104 | |||
2104 | if interactive: |
|
2105 | if interactive: | |
2105 | responses = _('[Ynsa?]' |
|
2106 | responses = _('[Ynsa?]' | |
2106 | '$$ &Yes, forget this file' |
|
2107 | '$$ &Yes, forget this file' | |
2107 | '$$ &No, skip this file' |
|
2108 | '$$ &No, skip this file' | |
2108 | '$$ &Skip remaining files' |
|
2109 | '$$ &Skip remaining files' | |
2109 | '$$ Include &all remaining files' |
|
2110 | '$$ Include &all remaining files' | |
2110 | '$$ &? (display help)') |
|
2111 | '$$ &? (display help)') | |
2111 | for filename in forget[:]: |
|
2112 | for filename in forget[:]: | |
2112 | r = ui.promptchoice(_('forget %s %s') % (filename, responses)) |
|
2113 | r = ui.promptchoice(_('forget %s %s') % (filename, responses)) | |
2113 | if r == 4: # ? |
|
2114 | if r == 4: # ? | |
2114 | while r == 4: |
|
2115 | while r == 4: | |
2115 | for c, t in ui.extractchoices(responses)[1]: |
|
2116 | for c, t in ui.extractchoices(responses)[1]: | |
2116 | ui.write('%s - %s\n' % (c, encoding.lower(t))) |
|
2117 | ui.write('%s - %s\n' % (c, encoding.lower(t))) | |
2117 | r = ui.promptchoice(_('forget %s %s') % (filename, |
|
2118 | r = ui.promptchoice(_('forget %s %s') % (filename, | |
2118 | responses)) |
|
2119 | responses)) | |
2119 | if r == 0: # yes |
|
2120 | if r == 0: # yes | |
2120 | continue |
|
2121 | continue | |
2121 | elif r == 1: # no |
|
2122 | elif r == 1: # no | |
2122 | forget.remove(filename) |
|
2123 | forget.remove(filename) | |
2123 | elif r == 2: # Skip |
|
2124 | elif r == 2: # Skip | |
2124 | fnindex = forget.index(filename) |
|
2125 | fnindex = forget.index(filename) | |
2125 | del forget[fnindex:] |
|
2126 | del forget[fnindex:] | |
2126 | break |
|
2127 | break | |
2127 | elif r == 3: # All |
|
2128 | elif r == 3: # All | |
2128 | break |
|
2129 | break | |
2129 |
|
2130 | |||
2130 | for f in forget: |
|
2131 | for f in forget: | |
2131 | if ui.verbose or not match.exact(f) or interactive: |
|
2132 | if ui.verbose or not match.exact(f) or interactive: | |
2132 | ui.status(_('removing %s\n') % match.rel(f)) |
|
2133 | ui.status(_('removing %s\n') % match.rel(f)) | |
2133 |
|
2134 | |||
2134 | if not dryrun: |
|
2135 | if not dryrun: | |
2135 | rejected = wctx.forget(forget, prefix) |
|
2136 | rejected = wctx.forget(forget, prefix) | |
2136 | bad.extend(f for f in rejected if f in match.files()) |
|
2137 | bad.extend(f for f in rejected if f in match.files()) | |
2137 | forgot.extend(f for f in forget if f not in rejected) |
|
2138 | forgot.extend(f for f in forget if f not in rejected) | |
2138 | return bad, forgot |
|
2139 | return bad, forgot | |
2139 |
|
2140 | |||
2140 | def files(ui, ctx, m, fm, fmt, subrepos): |
|
2141 | def files(ui, ctx, m, fm, fmt, subrepos): | |
2141 | ret = 1 |
|
2142 | ret = 1 | |
2142 |
|
2143 | |||
2143 | needsfctx = ui.verbose or {'size', 'flags'} & fm.datahint() |
|
2144 | needsfctx = ui.verbose or {'size', 'flags'} & fm.datahint() | |
2144 | for f in ctx.matches(m): |
|
2145 | for f in ctx.matches(m): | |
2145 | fm.startitem() |
|
2146 | fm.startitem() | |
2146 | fm.context(ctx=ctx) |
|
2147 | fm.context(ctx=ctx) | |
2147 | if needsfctx: |
|
2148 | if needsfctx: | |
2148 | fc = ctx[f] |
|
2149 | fc = ctx[f] | |
2149 | fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags()) |
|
2150 | fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags()) | |
2150 | fm.data(abspath=f) |
|
2151 | fm.data(abspath=f) | |
2151 | fm.write('path', fmt, m.rel(f)) |
|
2152 | fm.write('path', fmt, m.rel(f)) | |
2152 | ret = 0 |
|
2153 | ret = 0 | |
2153 |
|
2154 | |||
2154 | for subpath in sorted(ctx.substate): |
|
2155 | for subpath in sorted(ctx.substate): | |
2155 | submatch = matchmod.subdirmatcher(subpath, m) |
|
2156 | submatch = matchmod.subdirmatcher(subpath, m) | |
2156 | if (subrepos or m.exact(subpath) or any(submatch.files())): |
|
2157 | if (subrepos or m.exact(subpath) or any(submatch.files())): | |
2157 | sub = ctx.sub(subpath) |
|
2158 | sub = ctx.sub(subpath) | |
2158 | try: |
|
2159 | try: | |
2159 | recurse = m.exact(subpath) or subrepos |
|
2160 | recurse = m.exact(subpath) or subrepos | |
2160 | if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0: |
|
2161 | if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0: | |
2161 | ret = 0 |
|
2162 | ret = 0 | |
2162 | except error.LookupError: |
|
2163 | except error.LookupError: | |
2163 | ui.status(_("skipping missing subrepository: %s\n") |
|
2164 | ui.status(_("skipping missing subrepository: %s\n") | |
2164 | % m.abs(subpath)) |
|
2165 | % m.abs(subpath)) | |
2165 |
|
2166 | |||
2166 | return ret |
|
2167 | return ret | |
2167 |
|
2168 | |||
2168 | def remove(ui, repo, m, prefix, after, force, subrepos, dryrun, warnings=None): |
|
2169 | def remove(ui, repo, m, prefix, after, force, subrepos, dryrun, warnings=None): | |
2169 | join = lambda f: os.path.join(prefix, f) |
|
2170 | join = lambda f: os.path.join(prefix, f) | |
2170 | ret = 0 |
|
2171 | ret = 0 | |
2171 | s = repo.status(match=m, clean=True) |
|
2172 | s = repo.status(match=m, clean=True) | |
2172 | modified, added, deleted, clean = s[0], s[1], s[3], s[6] |
|
2173 | modified, added, deleted, clean = s[0], s[1], s[3], s[6] | |
2173 |
|
2174 | |||
2174 | wctx = repo[None] |
|
2175 | wctx = repo[None] | |
2175 |
|
2176 | |||
2176 | if warnings is None: |
|
2177 | if warnings is None: | |
2177 | warnings = [] |
|
2178 | warnings = [] | |
2178 | warn = True |
|
2179 | warn = True | |
2179 | else: |
|
2180 | else: | |
2180 | warn = False |
|
2181 | warn = False | |
2181 |
|
2182 | |||
2182 | subs = sorted(wctx.substate) |
|
2183 | subs = sorted(wctx.substate) | |
2183 | progress = ui.makeprogress(_('searching'), total=len(subs), |
|
2184 | progress = ui.makeprogress(_('searching'), total=len(subs), | |
2184 | unit=_('subrepos')) |
|
2185 | unit=_('subrepos')) | |
2185 | for subpath in subs: |
|
2186 | for subpath in subs: | |
2186 | submatch = matchmod.subdirmatcher(subpath, m) |
|
2187 | submatch = matchmod.subdirmatcher(subpath, m) | |
2187 | if subrepos or m.exact(subpath) or any(submatch.files()): |
|
2188 | if subrepos or m.exact(subpath) or any(submatch.files()): | |
2188 | progress.increment() |
|
2189 | progress.increment() | |
2189 | sub = wctx.sub(subpath) |
|
2190 | sub = wctx.sub(subpath) | |
2190 | try: |
|
2191 | try: | |
2191 | if sub.removefiles(submatch, prefix, after, force, subrepos, |
|
2192 | if sub.removefiles(submatch, prefix, after, force, subrepos, | |
2192 | dryrun, warnings): |
|
2193 | dryrun, warnings): | |
2193 | ret = 1 |
|
2194 | ret = 1 | |
2194 | except error.LookupError: |
|
2195 | except error.LookupError: | |
2195 | warnings.append(_("skipping missing subrepository: %s\n") |
|
2196 | warnings.append(_("skipping missing subrepository: %s\n") | |
2196 | % join(subpath)) |
|
2197 | % join(subpath)) | |
2197 | progress.complete() |
|
2198 | progress.complete() | |
2198 |
|
2199 | |||
2199 | # warn about failure to delete explicit files/dirs |
|
2200 | # warn about failure to delete explicit files/dirs | |
2200 | deleteddirs = util.dirs(deleted) |
|
2201 | deleteddirs = util.dirs(deleted) | |
2201 | files = m.files() |
|
2202 | files = m.files() | |
2202 | progress = ui.makeprogress(_('deleting'), total=len(files), |
|
2203 | progress = ui.makeprogress(_('deleting'), total=len(files), | |
2203 | unit=_('files')) |
|
2204 | unit=_('files')) | |
2204 | for f in files: |
|
2205 | for f in files: | |
2205 | def insubrepo(): |
|
2206 | def insubrepo(): | |
2206 | for subpath in wctx.substate: |
|
2207 | for subpath in wctx.substate: | |
2207 | if f.startswith(subpath + '/'): |
|
2208 | if f.startswith(subpath + '/'): | |
2208 | return True |
|
2209 | return True | |
2209 | return False |
|
2210 | return False | |
2210 |
|
2211 | |||
2211 | progress.increment() |
|
2212 | progress.increment() | |
2212 | isdir = f in deleteddirs or wctx.hasdir(f) |
|
2213 | isdir = f in deleteddirs or wctx.hasdir(f) | |
2213 | if (f in repo.dirstate or isdir or f == '.' |
|
2214 | if (f in repo.dirstate or isdir or f == '.' | |
2214 | or insubrepo() or f in subs): |
|
2215 | or insubrepo() or f in subs): | |
2215 | continue |
|
2216 | continue | |
2216 |
|
2217 | |||
2217 | if repo.wvfs.exists(f): |
|
2218 | if repo.wvfs.exists(f): | |
2218 | if repo.wvfs.isdir(f): |
|
2219 | if repo.wvfs.isdir(f): | |
2219 | warnings.append(_('not removing %s: no tracked files\n') |
|
2220 | warnings.append(_('not removing %s: no tracked files\n') | |
2220 | % m.rel(f)) |
|
2221 | % m.rel(f)) | |
2221 | else: |
|
2222 | else: | |
2222 | warnings.append(_('not removing %s: file is untracked\n') |
|
2223 | warnings.append(_('not removing %s: file is untracked\n') | |
2223 | % m.rel(f)) |
|
2224 | % m.rel(f)) | |
2224 | # missing files will generate a warning elsewhere |
|
2225 | # missing files will generate a warning elsewhere | |
2225 | ret = 1 |
|
2226 | ret = 1 | |
2226 | progress.complete() |
|
2227 | progress.complete() | |
2227 |
|
2228 | |||
2228 | if force: |
|
2229 | if force: | |
2229 | list = modified + deleted + clean + added |
|
2230 | list = modified + deleted + clean + added | |
2230 | elif after: |
|
2231 | elif after: | |
2231 | list = deleted |
|
2232 | list = deleted | |
2232 | remaining = modified + added + clean |
|
2233 | remaining = modified + added + clean | |
2233 | progress = ui.makeprogress(_('skipping'), total=len(remaining), |
|
2234 | progress = ui.makeprogress(_('skipping'), total=len(remaining), | |
2234 | unit=_('files')) |
|
2235 | unit=_('files')) | |
2235 | for f in remaining: |
|
2236 | for f in remaining: | |
2236 | progress.increment() |
|
2237 | progress.increment() | |
2237 | if ui.verbose or (f in files): |
|
2238 | if ui.verbose or (f in files): | |
2238 | warnings.append(_('not removing %s: file still exists\n') |
|
2239 | warnings.append(_('not removing %s: file still exists\n') | |
2239 | % m.rel(f)) |
|
2240 | % m.rel(f)) | |
2240 | ret = 1 |
|
2241 | ret = 1 | |
2241 | progress.complete() |
|
2242 | progress.complete() | |
2242 | else: |
|
2243 | else: | |
2243 | list = deleted + clean |
|
2244 | list = deleted + clean | |
2244 | progress = ui.makeprogress(_('skipping'), |
|
2245 | progress = ui.makeprogress(_('skipping'), | |
2245 | total=(len(modified) + len(added)), |
|
2246 | total=(len(modified) + len(added)), | |
2246 | unit=_('files')) |
|
2247 | unit=_('files')) | |
2247 | for f in modified: |
|
2248 | for f in modified: | |
2248 | progress.increment() |
|
2249 | progress.increment() | |
2249 | warnings.append(_('not removing %s: file is modified (use -f' |
|
2250 | warnings.append(_('not removing %s: file is modified (use -f' | |
2250 | ' to force removal)\n') % m.rel(f)) |
|
2251 | ' to force removal)\n') % m.rel(f)) | |
2251 | ret = 1 |
|
2252 | ret = 1 | |
2252 | for f in added: |
|
2253 | for f in added: | |
2253 | progress.increment() |
|
2254 | progress.increment() | |
2254 | warnings.append(_("not removing %s: file has been marked for add" |
|
2255 | warnings.append(_("not removing %s: file has been marked for add" | |
2255 | " (use 'hg forget' to undo add)\n") % m.rel(f)) |
|
2256 | " (use 'hg forget' to undo add)\n") % m.rel(f)) | |
2256 | ret = 1 |
|
2257 | ret = 1 | |
2257 | progress.complete() |
|
2258 | progress.complete() | |
2258 |
|
2259 | |||
2259 | list = sorted(list) |
|
2260 | list = sorted(list) | |
2260 | progress = ui.makeprogress(_('deleting'), total=len(list), |
|
2261 | progress = ui.makeprogress(_('deleting'), total=len(list), | |
2261 | unit=_('files')) |
|
2262 | unit=_('files')) | |
2262 | for f in list: |
|
2263 | for f in list: | |
2263 | if ui.verbose or not m.exact(f): |
|
2264 | if ui.verbose or not m.exact(f): | |
2264 | progress.increment() |
|
2265 | progress.increment() | |
2265 | ui.status(_('removing %s\n') % m.rel(f)) |
|
2266 | ui.status(_('removing %s\n') % m.rel(f)) | |
2266 | progress.complete() |
|
2267 | progress.complete() | |
2267 |
|
2268 | |||
2268 | if not dryrun: |
|
2269 | if not dryrun: | |
2269 | with repo.wlock(): |
|
2270 | with repo.wlock(): | |
2270 | if not after: |
|
2271 | if not after: | |
2271 | for f in list: |
|
2272 | for f in list: | |
2272 | if f in added: |
|
2273 | if f in added: | |
2273 | continue # we never unlink added files on remove |
|
2274 | continue # we never unlink added files on remove | |
2274 | rmdir = repo.ui.configbool('experimental', |
|
2275 | rmdir = repo.ui.configbool('experimental', | |
2275 | 'removeemptydirs') |
|
2276 | 'removeemptydirs') | |
2276 | repo.wvfs.unlinkpath(f, ignoremissing=True, rmdir=rmdir) |
|
2277 | repo.wvfs.unlinkpath(f, ignoremissing=True, rmdir=rmdir) | |
2277 | repo[None].forget(list) |
|
2278 | repo[None].forget(list) | |
2278 |
|
2279 | |||
2279 | if warn: |
|
2280 | if warn: | |
2280 | for warning in warnings: |
|
2281 | for warning in warnings: | |
2281 | ui.warn(warning) |
|
2282 | ui.warn(warning) | |
2282 |
|
2283 | |||
2283 | return ret |
|
2284 | return ret | |
2284 |
|
2285 | |||
2285 | def _updatecatformatter(fm, ctx, matcher, path, decode): |
|
2286 | def _updatecatformatter(fm, ctx, matcher, path, decode): | |
2286 | """Hook for adding data to the formatter used by ``hg cat``. |
|
2287 | """Hook for adding data to the formatter used by ``hg cat``. | |
2287 |
|
2288 | |||
2288 | Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call |
|
2289 | Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call | |
2289 | this method first.""" |
|
2290 | this method first.""" | |
2290 | data = ctx[path].data() |
|
2291 | data = ctx[path].data() | |
2291 | if decode: |
|
2292 | if decode: | |
2292 | data = ctx.repo().wwritedata(path, data) |
|
2293 | data = ctx.repo().wwritedata(path, data) | |
2293 | fm.startitem() |
|
2294 | fm.startitem() | |
2294 | fm.context(ctx=ctx) |
|
2295 | fm.context(ctx=ctx) | |
2295 | fm.write('data', '%s', data) |
|
2296 | fm.write('data', '%s', data) | |
2296 | fm.data(abspath=path, path=matcher.rel(path)) |
|
2297 | fm.data(abspath=path, path=matcher.rel(path)) | |
2297 |
|
2298 | |||
2298 | def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts): |
|
2299 | def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts): | |
2299 | err = 1 |
|
2300 | err = 1 | |
2300 | opts = pycompat.byteskwargs(opts) |
|
2301 | opts = pycompat.byteskwargs(opts) | |
2301 |
|
2302 | |||
2302 | def write(path): |
|
2303 | def write(path): | |
2303 | filename = None |
|
2304 | filename = None | |
2304 | if fntemplate: |
|
2305 | if fntemplate: | |
2305 | filename = makefilename(ctx, fntemplate, |
|
2306 | filename = makefilename(ctx, fntemplate, | |
2306 | pathname=os.path.join(prefix, path)) |
|
2307 | pathname=os.path.join(prefix, path)) | |
2307 | # attempt to create the directory if it does not already exist |
|
2308 | # attempt to create the directory if it does not already exist | |
2308 | try: |
|
2309 | try: | |
2309 | os.makedirs(os.path.dirname(filename)) |
|
2310 | os.makedirs(os.path.dirname(filename)) | |
2310 | except OSError: |
|
2311 | except OSError: | |
2311 | pass |
|
2312 | pass | |
2312 | with formatter.maybereopen(basefm, filename) as fm: |
|
2313 | with formatter.maybereopen(basefm, filename) as fm: | |
2313 | _updatecatformatter(fm, ctx, matcher, path, opts.get('decode')) |
|
2314 | _updatecatformatter(fm, ctx, matcher, path, opts.get('decode')) | |
2314 |
|
2315 | |||
2315 | # Automation often uses hg cat on single files, so special case it |
|
2316 | # Automation often uses hg cat on single files, so special case it | |
2316 | # for performance to avoid the cost of parsing the manifest. |
|
2317 | # for performance to avoid the cost of parsing the manifest. | |
2317 | if len(matcher.files()) == 1 and not matcher.anypats(): |
|
2318 | if len(matcher.files()) == 1 and not matcher.anypats(): | |
2318 | file = matcher.files()[0] |
|
2319 | file = matcher.files()[0] | |
2319 | mfl = repo.manifestlog |
|
2320 | mfl = repo.manifestlog | |
2320 | mfnode = ctx.manifestnode() |
|
2321 | mfnode = ctx.manifestnode() | |
2321 | try: |
|
2322 | try: | |
2322 | if mfnode and mfl[mfnode].find(file)[0]: |
|
2323 | if mfnode and mfl[mfnode].find(file)[0]: | |
2323 | scmutil.prefetchfiles(repo, [ctx.rev()], matcher) |
|
2324 | scmutil.prefetchfiles(repo, [ctx.rev()], matcher) | |
2324 | write(file) |
|
2325 | write(file) | |
2325 | return 0 |
|
2326 | return 0 | |
2326 | except KeyError: |
|
2327 | except KeyError: | |
2327 | pass |
|
2328 | pass | |
2328 |
|
2329 | |||
2329 | scmutil.prefetchfiles(repo, [ctx.rev()], matcher) |
|
2330 | scmutil.prefetchfiles(repo, [ctx.rev()], matcher) | |
2330 |
|
2331 | |||
2331 | for abs in ctx.walk(matcher): |
|
2332 | for abs in ctx.walk(matcher): | |
2332 | write(abs) |
|
2333 | write(abs) | |
2333 | err = 0 |
|
2334 | err = 0 | |
2334 |
|
2335 | |||
2335 | for subpath in sorted(ctx.substate): |
|
2336 | for subpath in sorted(ctx.substate): | |
2336 | sub = ctx.sub(subpath) |
|
2337 | sub = ctx.sub(subpath) | |
2337 | try: |
|
2338 | try: | |
2338 | submatch = matchmod.subdirmatcher(subpath, matcher) |
|
2339 | submatch = matchmod.subdirmatcher(subpath, matcher) | |
2339 |
|
2340 | |||
2340 | if not sub.cat(submatch, basefm, fntemplate, |
|
2341 | if not sub.cat(submatch, basefm, fntemplate, | |
2341 | os.path.join(prefix, sub._path), |
|
2342 | os.path.join(prefix, sub._path), | |
2342 | **pycompat.strkwargs(opts)): |
|
2343 | **pycompat.strkwargs(opts)): | |
2343 | err = 0 |
|
2344 | err = 0 | |
2344 | except error.RepoLookupError: |
|
2345 | except error.RepoLookupError: | |
2345 | ui.status(_("skipping missing subrepository: %s\n") |
|
2346 | ui.status(_("skipping missing subrepository: %s\n") | |
2346 | % os.path.join(prefix, subpath)) |
|
2347 | % os.path.join(prefix, subpath)) | |
2347 |
|
2348 | |||
2348 | return err |
|
2349 | return err | |
2349 |
|
2350 | |||
2350 | def commit(ui, repo, commitfunc, pats, opts): |
|
2351 | def commit(ui, repo, commitfunc, pats, opts): | |
2351 | '''commit the specified files or all outstanding changes''' |
|
2352 | '''commit the specified files or all outstanding changes''' | |
2352 | date = opts.get('date') |
|
2353 | date = opts.get('date') | |
2353 | if date: |
|
2354 | if date: | |
2354 | opts['date'] = dateutil.parsedate(date) |
|
2355 | opts['date'] = dateutil.parsedate(date) | |
2355 | message = logmessage(ui, opts) |
|
2356 | message = logmessage(ui, opts) | |
2356 | matcher = scmutil.match(repo[None], pats, opts) |
|
2357 | matcher = scmutil.match(repo[None], pats, opts) | |
2357 |
|
2358 | |||
2358 | dsguard = None |
|
2359 | dsguard = None | |
2359 | # extract addremove carefully -- this function can be called from a command |
|
2360 | # extract addremove carefully -- this function can be called from a command | |
2360 | # that doesn't support addremove |
|
2361 | # that doesn't support addremove | |
2361 | if opts.get('addremove'): |
|
2362 | if opts.get('addremove'): | |
2362 | dsguard = dirstateguard.dirstateguard(repo, 'commit') |
|
2363 | dsguard = dirstateguard.dirstateguard(repo, 'commit') | |
2363 | with dsguard or util.nullcontextmanager(): |
|
2364 | with dsguard or util.nullcontextmanager(): | |
2364 | if dsguard: |
|
2365 | if dsguard: | |
2365 | if scmutil.addremove(repo, matcher, "", opts) != 0: |
|
2366 | if scmutil.addremove(repo, matcher, "", opts) != 0: | |
2366 | raise error.Abort( |
|
2367 | raise error.Abort( | |
2367 | _("failed to mark all new/missing files as added/removed")) |
|
2368 | _("failed to mark all new/missing files as added/removed")) | |
2368 |
|
2369 | |||
2369 | return commitfunc(ui, repo, message, matcher, opts) |
|
2370 | return commitfunc(ui, repo, message, matcher, opts) | |
2370 |
|
2371 | |||
2371 | def samefile(f, ctx1, ctx2): |
|
2372 | def samefile(f, ctx1, ctx2): | |
2372 | if f in ctx1.manifest(): |
|
2373 | if f in ctx1.manifest(): | |
2373 | a = ctx1.filectx(f) |
|
2374 | a = ctx1.filectx(f) | |
2374 | if f in ctx2.manifest(): |
|
2375 | if f in ctx2.manifest(): | |
2375 | b = ctx2.filectx(f) |
|
2376 | b = ctx2.filectx(f) | |
2376 | return (not a.cmp(b) |
|
2377 | return (not a.cmp(b) | |
2377 | and a.flags() == b.flags()) |
|
2378 | and a.flags() == b.flags()) | |
2378 | else: |
|
2379 | else: | |
2379 | return False |
|
2380 | return False | |
2380 | else: |
|
2381 | else: | |
2381 | return f not in ctx2.manifest() |
|
2382 | return f not in ctx2.manifest() | |
2382 |
|
2383 | |||
2383 | def amend(ui, repo, old, extra, pats, opts): |
|
2384 | def amend(ui, repo, old, extra, pats, opts): | |
2384 | # avoid cycle context -> subrepo -> cmdutil |
|
2385 | # avoid cycle context -> subrepo -> cmdutil | |
2385 | from . import context |
|
2386 | from . import context | |
2386 |
|
2387 | |||
2387 | # amend will reuse the existing user if not specified, but the obsolete |
|
2388 | # amend will reuse the existing user if not specified, but the obsolete | |
2388 | # marker creation requires that the current user's name is specified. |
|
2389 | # marker creation requires that the current user's name is specified. | |
2389 | if obsolete.isenabled(repo, obsolete.createmarkersopt): |
|
2390 | if obsolete.isenabled(repo, obsolete.createmarkersopt): | |
2390 | ui.username() # raise exception if username not set |
|
2391 | ui.username() # raise exception if username not set | |
2391 |
|
2392 | |||
2392 | ui.note(_('amending changeset %s\n') % old) |
|
2393 | ui.note(_('amending changeset %s\n') % old) | |
2393 | base = old.p1() |
|
2394 | base = old.p1() | |
2394 |
|
2395 | |||
2395 | with repo.wlock(), repo.lock(), repo.transaction('amend'): |
|
2396 | with repo.wlock(), repo.lock(), repo.transaction('amend'): | |
2396 | # Participating changesets: |
|
2397 | # Participating changesets: | |
2397 | # |
|
2398 | # | |
2398 | # wctx o - workingctx that contains changes from working copy |
|
2399 | # wctx o - workingctx that contains changes from working copy | |
2399 | # | to go into amending commit |
|
2400 | # | to go into amending commit | |
2400 | # | |
|
2401 | # | | |
2401 | # old o - changeset to amend |
|
2402 | # old o - changeset to amend | |
2402 | # | |
|
2403 | # | | |
2403 | # base o - first parent of the changeset to amend |
|
2404 | # base o - first parent of the changeset to amend | |
2404 | wctx = repo[None] |
|
2405 | wctx = repo[None] | |
2405 |
|
2406 | |||
2406 | # Copy to avoid mutating input |
|
2407 | # Copy to avoid mutating input | |
2407 | extra = extra.copy() |
|
2408 | extra = extra.copy() | |
2408 | # Update extra dict from amended commit (e.g. to preserve graft |
|
2409 | # Update extra dict from amended commit (e.g. to preserve graft | |
2409 | # source) |
|
2410 | # source) | |
2410 | extra.update(old.extra()) |
|
2411 | extra.update(old.extra()) | |
2411 |
|
2412 | |||
2412 | # Also update it from the from the wctx |
|
2413 | # Also update it from the from the wctx | |
2413 | extra.update(wctx.extra()) |
|
2414 | extra.update(wctx.extra()) | |
2414 |
|
2415 | |||
2415 | user = opts.get('user') or old.user() |
|
2416 | user = opts.get('user') or old.user() | |
2416 | date = opts.get('date') or old.date() |
|
2417 | date = opts.get('date') or old.date() | |
2417 |
|
2418 | |||
2418 | # Parse the date to allow comparison between date and old.date() |
|
2419 | # Parse the date to allow comparison between date and old.date() | |
2419 | date = dateutil.parsedate(date) |
|
2420 | date = dateutil.parsedate(date) | |
2420 |
|
2421 | |||
2421 | if len(old.parents()) > 1: |
|
2422 | if len(old.parents()) > 1: | |
2422 | # ctx.files() isn't reliable for merges, so fall back to the |
|
2423 | # ctx.files() isn't reliable for merges, so fall back to the | |
2423 | # slower repo.status() method |
|
2424 | # slower repo.status() method | |
2424 | files = set([fn for st in base.status(old)[:3] |
|
2425 | files = set([fn for st in base.status(old)[:3] | |
2425 | for fn in st]) |
|
2426 | for fn in st]) | |
2426 | else: |
|
2427 | else: | |
2427 | files = set(old.files()) |
|
2428 | files = set(old.files()) | |
2428 |
|
2429 | |||
2429 | # add/remove the files to the working copy if the "addremove" option |
|
2430 | # add/remove the files to the working copy if the "addremove" option | |
2430 | # was specified. |
|
2431 | # was specified. | |
2431 | matcher = scmutil.match(wctx, pats, opts) |
|
2432 | matcher = scmutil.match(wctx, pats, opts) | |
2432 | if (opts.get('addremove') |
|
2433 | if (opts.get('addremove') | |
2433 | and scmutil.addremove(repo, matcher, "", opts)): |
|
2434 | and scmutil.addremove(repo, matcher, "", opts)): | |
2434 | raise error.Abort( |
|
2435 | raise error.Abort( | |
2435 | _("failed to mark all new/missing files as added/removed")) |
|
2436 | _("failed to mark all new/missing files as added/removed")) | |
2436 |
|
2437 | |||
2437 | # Check subrepos. This depends on in-place wctx._status update in |
|
2438 | # Check subrepos. This depends on in-place wctx._status update in | |
2438 | # subrepo.precommit(). To minimize the risk of this hack, we do |
|
2439 | # subrepo.precommit(). To minimize the risk of this hack, we do | |
2439 | # nothing if .hgsub does not exist. |
|
2440 | # nothing if .hgsub does not exist. | |
2440 | if '.hgsub' in wctx or '.hgsub' in old: |
|
2441 | if '.hgsub' in wctx or '.hgsub' in old: | |
2441 | subs, commitsubs, newsubstate = subrepoutil.precommit( |
|
2442 | subs, commitsubs, newsubstate = subrepoutil.precommit( | |
2442 | ui, wctx, wctx._status, matcher) |
|
2443 | ui, wctx, wctx._status, matcher) | |
2443 | # amend should abort if commitsubrepos is enabled |
|
2444 | # amend should abort if commitsubrepos is enabled | |
2444 | assert not commitsubs |
|
2445 | assert not commitsubs | |
2445 | if subs: |
|
2446 | if subs: | |
2446 | subrepoutil.writestate(repo, newsubstate) |
|
2447 | subrepoutil.writestate(repo, newsubstate) | |
2447 |
|
2448 | |||
2448 | ms = mergemod.mergestate.read(repo) |
|
2449 | ms = mergemod.mergestate.read(repo) | |
2449 | mergeutil.checkunresolved(ms) |
|
2450 | mergeutil.checkunresolved(ms) | |
2450 |
|
2451 | |||
2451 | filestoamend = set(f for f in wctx.files() if matcher(f)) |
|
2452 | filestoamend = set(f for f in wctx.files() if matcher(f)) | |
2452 |
|
2453 | |||
2453 | changes = (len(filestoamend) > 0) |
|
2454 | changes = (len(filestoamend) > 0) | |
2454 | if changes: |
|
2455 | if changes: | |
2455 | # Recompute copies (avoid recording a -> b -> a) |
|
2456 | # Recompute copies (avoid recording a -> b -> a) | |
2456 | copied = copies.pathcopies(base, wctx, matcher) |
|
2457 | copied = copies.pathcopies(base, wctx, matcher) | |
2457 | if old.p2: |
|
2458 | if old.p2: | |
2458 | copied.update(copies.pathcopies(old.p2(), wctx, matcher)) |
|
2459 | copied.update(copies.pathcopies(old.p2(), wctx, matcher)) | |
2459 |
|
2460 | |||
2460 | # Prune files which were reverted by the updates: if old |
|
2461 | # Prune files which were reverted by the updates: if old | |
2461 | # introduced file X and the file was renamed in the working |
|
2462 | # introduced file X and the file was renamed in the working | |
2462 | # copy, then those two files are the same and |
|
2463 | # copy, then those two files are the same and | |
2463 | # we can discard X from our list of files. Likewise if X |
|
2464 | # we can discard X from our list of files. Likewise if X | |
2464 | # was removed, it's no longer relevant. If X is missing (aka |
|
2465 | # was removed, it's no longer relevant. If X is missing (aka | |
2465 | # deleted), old X must be preserved. |
|
2466 | # deleted), old X must be preserved. | |
2466 | files.update(filestoamend) |
|
2467 | files.update(filestoamend) | |
2467 | files = [f for f in files if (not samefile(f, wctx, base) |
|
2468 | files = [f for f in files if (not samefile(f, wctx, base) | |
2468 | or f in wctx.deleted())] |
|
2469 | or f in wctx.deleted())] | |
2469 |
|
2470 | |||
2470 | def filectxfn(repo, ctx_, path): |
|
2471 | def filectxfn(repo, ctx_, path): | |
2471 | try: |
|
2472 | try: | |
2472 | # If the file being considered is not amongst the files |
|
2473 | # If the file being considered is not amongst the files | |
2473 | # to be amended, we should return the file context from the |
|
2474 | # to be amended, we should return the file context from the | |
2474 | # old changeset. This avoids issues when only some files in |
|
2475 | # old changeset. This avoids issues when only some files in | |
2475 | # the working copy are being amended but there are also |
|
2476 | # the working copy are being amended but there are also | |
2476 | # changes to other files from the old changeset. |
|
2477 | # changes to other files from the old changeset. | |
2477 | if path not in filestoamend: |
|
2478 | if path not in filestoamend: | |
2478 | return old.filectx(path) |
|
2479 | return old.filectx(path) | |
2479 |
|
2480 | |||
2480 | # Return None for removed files. |
|
2481 | # Return None for removed files. | |
2481 | if path in wctx.removed(): |
|
2482 | if path in wctx.removed(): | |
2482 | return None |
|
2483 | return None | |
2483 |
|
2484 | |||
2484 | fctx = wctx[path] |
|
2485 | fctx = wctx[path] | |
2485 | flags = fctx.flags() |
|
2486 | flags = fctx.flags() | |
2486 | mctx = context.memfilectx(repo, ctx_, |
|
2487 | mctx = context.memfilectx(repo, ctx_, | |
2487 | fctx.path(), fctx.data(), |
|
2488 | fctx.path(), fctx.data(), | |
2488 | islink='l' in flags, |
|
2489 | islink='l' in flags, | |
2489 | isexec='x' in flags, |
|
2490 | isexec='x' in flags, | |
2490 | copied=copied.get(path)) |
|
2491 | copied=copied.get(path)) | |
2491 | return mctx |
|
2492 | return mctx | |
2492 | except KeyError: |
|
2493 | except KeyError: | |
2493 | return None |
|
2494 | return None | |
2494 | else: |
|
2495 | else: | |
2495 | ui.note(_('copying changeset %s to %s\n') % (old, base)) |
|
2496 | ui.note(_('copying changeset %s to %s\n') % (old, base)) | |
2496 |
|
2497 | |||
2497 | # Use version of files as in the old cset |
|
2498 | # Use version of files as in the old cset | |
2498 | def filectxfn(repo, ctx_, path): |
|
2499 | def filectxfn(repo, ctx_, path): | |
2499 | try: |
|
2500 | try: | |
2500 | return old.filectx(path) |
|
2501 | return old.filectx(path) | |
2501 | except KeyError: |
|
2502 | except KeyError: | |
2502 | return None |
|
2503 | return None | |
2503 |
|
2504 | |||
2504 | # See if we got a message from -m or -l, if not, open the editor with |
|
2505 | # See if we got a message from -m or -l, if not, open the editor with | |
2505 | # the message of the changeset to amend. |
|
2506 | # the message of the changeset to amend. | |
2506 | message = logmessage(ui, opts) |
|
2507 | message = logmessage(ui, opts) | |
2507 |
|
2508 | |||
2508 | editform = mergeeditform(old, 'commit.amend') |
|
2509 | editform = mergeeditform(old, 'commit.amend') | |
2509 | editor = getcommiteditor(editform=editform, |
|
2510 | editor = getcommiteditor(editform=editform, | |
2510 | **pycompat.strkwargs(opts)) |
|
2511 | **pycompat.strkwargs(opts)) | |
2511 |
|
2512 | |||
2512 | if not message: |
|
2513 | if not message: | |
2513 | editor = getcommiteditor(edit=True, editform=editform) |
|
2514 | editor = getcommiteditor(edit=True, editform=editform) | |
2514 | message = old.description() |
|
2515 | message = old.description() | |
2515 |
|
2516 | |||
2516 | pureextra = extra.copy() |
|
2517 | pureextra = extra.copy() | |
2517 | extra['amend_source'] = old.hex() |
|
2518 | extra['amend_source'] = old.hex() | |
2518 |
|
2519 | |||
2519 | new = context.memctx(repo, |
|
2520 | new = context.memctx(repo, | |
2520 | parents=[base.node(), old.p2().node()], |
|
2521 | parents=[base.node(), old.p2().node()], | |
2521 | text=message, |
|
2522 | text=message, | |
2522 | files=files, |
|
2523 | files=files, | |
2523 | filectxfn=filectxfn, |
|
2524 | filectxfn=filectxfn, | |
2524 | user=user, |
|
2525 | user=user, | |
2525 | date=date, |
|
2526 | date=date, | |
2526 | extra=extra, |
|
2527 | extra=extra, | |
2527 | editor=editor) |
|
2528 | editor=editor) | |
2528 |
|
2529 | |||
2529 | newdesc = changelog.stripdesc(new.description()) |
|
2530 | newdesc = changelog.stripdesc(new.description()) | |
2530 | if ((not changes) |
|
2531 | if ((not changes) | |
2531 | and newdesc == old.description() |
|
2532 | and newdesc == old.description() | |
2532 | and user == old.user() |
|
2533 | and user == old.user() | |
2533 | and date == old.date() |
|
2534 | and date == old.date() | |
2534 | and pureextra == old.extra()): |
|
2535 | and pureextra == old.extra()): | |
2535 | # nothing changed. continuing here would create a new node |
|
2536 | # nothing changed. continuing here would create a new node | |
2536 | # anyway because of the amend_source noise. |
|
2537 | # anyway because of the amend_source noise. | |
2537 | # |
|
2538 | # | |
2538 | # This not what we expect from amend. |
|
2539 | # This not what we expect from amend. | |
2539 | return old.node() |
|
2540 | return old.node() | |
2540 |
|
2541 | |||
2541 | commitphase = None |
|
2542 | commitphase = None | |
2542 | if opts.get('secret'): |
|
2543 | if opts.get('secret'): | |
2543 | commitphase = phases.secret |
|
2544 | commitphase = phases.secret | |
2544 | newid = repo.commitctx(new) |
|
2545 | newid = repo.commitctx(new) | |
2545 |
|
2546 | |||
2546 | # Reroute the working copy parent to the new changeset |
|
2547 | # Reroute the working copy parent to the new changeset | |
2547 | repo.setparents(newid, nullid) |
|
2548 | repo.setparents(newid, nullid) | |
2548 | mapping = {old.node(): (newid,)} |
|
2549 | mapping = {old.node(): (newid,)} | |
2549 | obsmetadata = None |
|
2550 | obsmetadata = None | |
2550 | if opts.get('note'): |
|
2551 | if opts.get('note'): | |
2551 | obsmetadata = {'note': encoding.fromlocal(opts['note'])} |
|
2552 | obsmetadata = {'note': encoding.fromlocal(opts['note'])} | |
2552 | backup = ui.configbool('ui', 'history-editing-backup') |
|
2553 | backup = ui.configbool('ui', 'history-editing-backup') | |
2553 | scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata, |
|
2554 | scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata, | |
2554 | fixphase=True, targetphase=commitphase, |
|
2555 | fixphase=True, targetphase=commitphase, | |
2555 | backup=backup) |
|
2556 | backup=backup) | |
2556 |
|
2557 | |||
2557 | # Fixing the dirstate because localrepo.commitctx does not update |
|
2558 | # Fixing the dirstate because localrepo.commitctx does not update | |
2558 | # it. This is rather convenient because we did not need to update |
|
2559 | # it. This is rather convenient because we did not need to update | |
2559 | # the dirstate for all the files in the new commit which commitctx |
|
2560 | # the dirstate for all the files in the new commit which commitctx | |
2560 | # could have done if it updated the dirstate. Now, we can |
|
2561 | # could have done if it updated the dirstate. Now, we can | |
2561 | # selectively update the dirstate only for the amended files. |
|
2562 | # selectively update the dirstate only for the amended files. | |
2562 | dirstate = repo.dirstate |
|
2563 | dirstate = repo.dirstate | |
2563 |
|
2564 | |||
2564 | # Update the state of the files which were added and |
|
2565 | # Update the state of the files which were added and | |
2565 | # and modified in the amend to "normal" in the dirstate. |
|
2566 | # and modified in the amend to "normal" in the dirstate. | |
2566 | normalfiles = set(wctx.modified() + wctx.added()) & filestoamend |
|
2567 | normalfiles = set(wctx.modified() + wctx.added()) & filestoamend | |
2567 | for f in normalfiles: |
|
2568 | for f in normalfiles: | |
2568 | dirstate.normal(f) |
|
2569 | dirstate.normal(f) | |
2569 |
|
2570 | |||
2570 | # Update the state of files which were removed in the amend |
|
2571 | # Update the state of files which were removed in the amend | |
2571 | # to "removed" in the dirstate. |
|
2572 | # to "removed" in the dirstate. | |
2572 | removedfiles = set(wctx.removed()) & filestoamend |
|
2573 | removedfiles = set(wctx.removed()) & filestoamend | |
2573 | for f in removedfiles: |
|
2574 | for f in removedfiles: | |
2574 | dirstate.drop(f) |
|
2575 | dirstate.drop(f) | |
2575 |
|
2576 | |||
2576 | return newid |
|
2577 | return newid | |
2577 |
|
2578 | |||
2578 | def commiteditor(repo, ctx, subs, editform=''): |
|
2579 | def commiteditor(repo, ctx, subs, editform=''): | |
2579 | if ctx.description(): |
|
2580 | if ctx.description(): | |
2580 | return ctx.description() |
|
2581 | return ctx.description() | |
2581 | return commitforceeditor(repo, ctx, subs, editform=editform, |
|
2582 | return commitforceeditor(repo, ctx, subs, editform=editform, | |
2582 | unchangedmessagedetection=True) |
|
2583 | unchangedmessagedetection=True) | |
2583 |
|
2584 | |||
2584 | def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None, |
|
2585 | def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None, | |
2585 | editform='', unchangedmessagedetection=False): |
|
2586 | editform='', unchangedmessagedetection=False): | |
2586 | if not extramsg: |
|
2587 | if not extramsg: | |
2587 | extramsg = _("Leave message empty to abort commit.") |
|
2588 | extramsg = _("Leave message empty to abort commit.") | |
2588 |
|
2589 | |||
2589 | forms = [e for e in editform.split('.') if e] |
|
2590 | forms = [e for e in editform.split('.') if e] | |
2590 | forms.insert(0, 'changeset') |
|
2591 | forms.insert(0, 'changeset') | |
2591 | templatetext = None |
|
2592 | templatetext = None | |
2592 | while forms: |
|
2593 | while forms: | |
2593 | ref = '.'.join(forms) |
|
2594 | ref = '.'.join(forms) | |
2594 | if repo.ui.config('committemplate', ref): |
|
2595 | if repo.ui.config('committemplate', ref): | |
2595 | templatetext = committext = buildcommittemplate( |
|
2596 | templatetext = committext = buildcommittemplate( | |
2596 | repo, ctx, subs, extramsg, ref) |
|
2597 | repo, ctx, subs, extramsg, ref) | |
2597 | break |
|
2598 | break | |
2598 | forms.pop() |
|
2599 | forms.pop() | |
2599 | else: |
|
2600 | else: | |
2600 | committext = buildcommittext(repo, ctx, subs, extramsg) |
|
2601 | committext = buildcommittext(repo, ctx, subs, extramsg) | |
2601 |
|
2602 | |||
2602 | # run editor in the repository root |
|
2603 | # run editor in the repository root | |
2603 | olddir = pycompat.getcwd() |
|
2604 | olddir = pycompat.getcwd() | |
2604 | os.chdir(repo.root) |
|
2605 | os.chdir(repo.root) | |
2605 |
|
2606 | |||
2606 | # make in-memory changes visible to external process |
|
2607 | # make in-memory changes visible to external process | |
2607 | tr = repo.currenttransaction() |
|
2608 | tr = repo.currenttransaction() | |
2608 | repo.dirstate.write(tr) |
|
2609 | repo.dirstate.write(tr) | |
2609 | pending = tr and tr.writepending() and repo.root |
|
2610 | pending = tr and tr.writepending() and repo.root | |
2610 |
|
2611 | |||
2611 | editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(), |
|
2612 | editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(), | |
2612 | editform=editform, pending=pending, |
|
2613 | editform=editform, pending=pending, | |
2613 | repopath=repo.path, action='commit') |
|
2614 | repopath=repo.path, action='commit') | |
2614 | text = editortext |
|
2615 | text = editortext | |
2615 |
|
2616 | |||
2616 | # strip away anything below this special string (used for editors that want |
|
2617 | # strip away anything below this special string (used for editors that want | |
2617 | # to display the diff) |
|
2618 | # to display the diff) | |
2618 | stripbelow = re.search(_linebelow, text, flags=re.MULTILINE) |
|
2619 | stripbelow = re.search(_linebelow, text, flags=re.MULTILINE) | |
2619 | if stripbelow: |
|
2620 | if stripbelow: | |
2620 | text = text[:stripbelow.start()] |
|
2621 | text = text[:stripbelow.start()] | |
2621 |
|
2622 | |||
2622 | text = re.sub("(?m)^HG:.*(\n|$)", "", text) |
|
2623 | text = re.sub("(?m)^HG:.*(\n|$)", "", text) | |
2623 | os.chdir(olddir) |
|
2624 | os.chdir(olddir) | |
2624 |
|
2625 | |||
2625 | if finishdesc: |
|
2626 | if finishdesc: | |
2626 | text = finishdesc(text) |
|
2627 | text = finishdesc(text) | |
2627 | if not text.strip(): |
|
2628 | if not text.strip(): | |
2628 | raise error.Abort(_("empty commit message")) |
|
2629 | raise error.Abort(_("empty commit message")) | |
2629 | if unchangedmessagedetection and editortext == templatetext: |
|
2630 | if unchangedmessagedetection and editortext == templatetext: | |
2630 | raise error.Abort(_("commit message unchanged")) |
|
2631 | raise error.Abort(_("commit message unchanged")) | |
2631 |
|
2632 | |||
2632 | return text |
|
2633 | return text | |
2633 |
|
2634 | |||
2634 | def buildcommittemplate(repo, ctx, subs, extramsg, ref): |
|
2635 | def buildcommittemplate(repo, ctx, subs, extramsg, ref): | |
2635 | ui = repo.ui |
|
2636 | ui = repo.ui | |
2636 | spec = formatter.templatespec(ref, None, None) |
|
2637 | spec = formatter.templatespec(ref, None, None) | |
2637 | t = logcmdutil.changesettemplater(ui, repo, spec) |
|
2638 | t = logcmdutil.changesettemplater(ui, repo, spec) | |
2638 | t.t.cache.update((k, templater.unquotestring(v)) |
|
2639 | t.t.cache.update((k, templater.unquotestring(v)) | |
2639 | for k, v in repo.ui.configitems('committemplate')) |
|
2640 | for k, v in repo.ui.configitems('committemplate')) | |
2640 |
|
2641 | |||
2641 | if not extramsg: |
|
2642 | if not extramsg: | |
2642 | extramsg = '' # ensure that extramsg is string |
|
2643 | extramsg = '' # ensure that extramsg is string | |
2643 |
|
2644 | |||
2644 | ui.pushbuffer() |
|
2645 | ui.pushbuffer() | |
2645 | t.show(ctx, extramsg=extramsg) |
|
2646 | t.show(ctx, extramsg=extramsg) | |
2646 | return ui.popbuffer() |
|
2647 | return ui.popbuffer() | |
2647 |
|
2648 | |||
2648 | def hgprefix(msg): |
|
2649 | def hgprefix(msg): | |
2649 | return "\n".join(["HG: %s" % a for a in msg.split("\n") if a]) |
|
2650 | return "\n".join(["HG: %s" % a for a in msg.split("\n") if a]) | |
2650 |
|
2651 | |||
2651 | def buildcommittext(repo, ctx, subs, extramsg): |
|
2652 | def buildcommittext(repo, ctx, subs, extramsg): | |
2652 | edittext = [] |
|
2653 | edittext = [] | |
2653 | modified, added, removed = ctx.modified(), ctx.added(), ctx.removed() |
|
2654 | modified, added, removed = ctx.modified(), ctx.added(), ctx.removed() | |
2654 | if ctx.description(): |
|
2655 | if ctx.description(): | |
2655 | edittext.append(ctx.description()) |
|
2656 | edittext.append(ctx.description()) | |
2656 | edittext.append("") |
|
2657 | edittext.append("") | |
2657 | edittext.append("") # Empty line between message and comments. |
|
2658 | edittext.append("") # Empty line between message and comments. | |
2658 | edittext.append(hgprefix(_("Enter commit message." |
|
2659 | edittext.append(hgprefix(_("Enter commit message." | |
2659 | " Lines beginning with 'HG:' are removed."))) |
|
2660 | " Lines beginning with 'HG:' are removed."))) | |
2660 | edittext.append(hgprefix(extramsg)) |
|
2661 | edittext.append(hgprefix(extramsg)) | |
2661 | edittext.append("HG: --") |
|
2662 | edittext.append("HG: --") | |
2662 | edittext.append(hgprefix(_("user: %s") % ctx.user())) |
|
2663 | edittext.append(hgprefix(_("user: %s") % ctx.user())) | |
2663 | if ctx.p2(): |
|
2664 | if ctx.p2(): | |
2664 | edittext.append(hgprefix(_("branch merge"))) |
|
2665 | edittext.append(hgprefix(_("branch merge"))) | |
2665 | if ctx.branch(): |
|
2666 | if ctx.branch(): | |
2666 | edittext.append(hgprefix(_("branch '%s'") % ctx.branch())) |
|
2667 | edittext.append(hgprefix(_("branch '%s'") % ctx.branch())) | |
2667 | if bookmarks.isactivewdirparent(repo): |
|
2668 | if bookmarks.isactivewdirparent(repo): | |
2668 | edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark)) |
|
2669 | edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark)) | |
2669 | edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs]) |
|
2670 | edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs]) | |
2670 | edittext.extend([hgprefix(_("added %s") % f) for f in added]) |
|
2671 | edittext.extend([hgprefix(_("added %s") % f) for f in added]) | |
2671 | edittext.extend([hgprefix(_("changed %s") % f) for f in modified]) |
|
2672 | edittext.extend([hgprefix(_("changed %s") % f) for f in modified]) | |
2672 | edittext.extend([hgprefix(_("removed %s") % f) for f in removed]) |
|
2673 | edittext.extend([hgprefix(_("removed %s") % f) for f in removed]) | |
2673 | if not added and not modified and not removed: |
|
2674 | if not added and not modified and not removed: | |
2674 | edittext.append(hgprefix(_("no files changed"))) |
|
2675 | edittext.append(hgprefix(_("no files changed"))) | |
2675 | edittext.append("") |
|
2676 | edittext.append("") | |
2676 |
|
2677 | |||
2677 | return "\n".join(edittext) |
|
2678 | return "\n".join(edittext) | |
2678 |
|
2679 | |||
2679 | def commitstatus(repo, node, branch, bheads=None, opts=None): |
|
2680 | def commitstatus(repo, node, branch, bheads=None, opts=None): | |
2680 | if opts is None: |
|
2681 | if opts is None: | |
2681 | opts = {} |
|
2682 | opts = {} | |
2682 | ctx = repo[node] |
|
2683 | ctx = repo[node] | |
2683 | parents = ctx.parents() |
|
2684 | parents = ctx.parents() | |
2684 |
|
2685 | |||
2685 | if (not opts.get('amend') and bheads and node not in bheads and not |
|
2686 | if (not opts.get('amend') and bheads and node not in bheads and not | |
2686 | [x for x in parents if x.node() in bheads and x.branch() == branch]): |
|
2687 | [x for x in parents if x.node() in bheads and x.branch() == branch]): | |
2687 | repo.ui.status(_('created new head\n')) |
|
2688 | repo.ui.status(_('created new head\n')) | |
2688 | # The message is not printed for initial roots. For the other |
|
2689 | # The message is not printed for initial roots. For the other | |
2689 | # changesets, it is printed in the following situations: |
|
2690 | # changesets, it is printed in the following situations: | |
2690 | # |
|
2691 | # | |
2691 | # Par column: for the 2 parents with ... |
|
2692 | # Par column: for the 2 parents with ... | |
2692 | # N: null or no parent |
|
2693 | # N: null or no parent | |
2693 | # B: parent is on another named branch |
|
2694 | # B: parent is on another named branch | |
2694 | # C: parent is a regular non head changeset |
|
2695 | # C: parent is a regular non head changeset | |
2695 | # H: parent was a branch head of the current branch |
|
2696 | # H: parent was a branch head of the current branch | |
2696 | # Msg column: whether we print "created new head" message |
|
2697 | # Msg column: whether we print "created new head" message | |
2697 | # In the following, it is assumed that there already exists some |
|
2698 | # In the following, it is assumed that there already exists some | |
2698 | # initial branch heads of the current branch, otherwise nothing is |
|
2699 | # initial branch heads of the current branch, otherwise nothing is | |
2699 | # printed anyway. |
|
2700 | # printed anyway. | |
2700 | # |
|
2701 | # | |
2701 | # Par Msg Comment |
|
2702 | # Par Msg Comment | |
2702 | # N N y additional topo root |
|
2703 | # N N y additional topo root | |
2703 | # |
|
2704 | # | |
2704 | # B N y additional branch root |
|
2705 | # B N y additional branch root | |
2705 | # C N y additional topo head |
|
2706 | # C N y additional topo head | |
2706 | # H N n usual case |
|
2707 | # H N n usual case | |
2707 | # |
|
2708 | # | |
2708 | # B B y weird additional branch root |
|
2709 | # B B y weird additional branch root | |
2709 | # C B y branch merge |
|
2710 | # C B y branch merge | |
2710 | # H B n merge with named branch |
|
2711 | # H B n merge with named branch | |
2711 | # |
|
2712 | # | |
2712 | # C C y additional head from merge |
|
2713 | # C C y additional head from merge | |
2713 | # C H n merge with a head |
|
2714 | # C H n merge with a head | |
2714 | # |
|
2715 | # | |
2715 | # H H n head merge: head count decreases |
|
2716 | # H H n head merge: head count decreases | |
2716 |
|
2717 | |||
2717 | if not opts.get('close_branch'): |
|
2718 | if not opts.get('close_branch'): | |
2718 | for r in parents: |
|
2719 | for r in parents: | |
2719 | if r.closesbranch() and r.branch() == branch: |
|
2720 | if r.closesbranch() and r.branch() == branch: | |
2720 | repo.ui.status(_('reopening closed branch head %d\n') % r.rev()) |
|
2721 | repo.ui.status(_('reopening closed branch head %d\n') % r.rev()) | |
2721 |
|
2722 | |||
2722 | if repo.ui.debugflag: |
|
2723 | if repo.ui.debugflag: | |
2723 | repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx.hex())) |
|
2724 | repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx.hex())) | |
2724 | elif repo.ui.verbose: |
|
2725 | elif repo.ui.verbose: | |
2725 | repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx)) |
|
2726 | repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx)) | |
2726 |
|
2727 | |||
2727 | def postcommitstatus(repo, pats, opts): |
|
2728 | def postcommitstatus(repo, pats, opts): | |
2728 | return repo.status(match=scmutil.match(repo[None], pats, opts)) |
|
2729 | return repo.status(match=scmutil.match(repo[None], pats, opts)) | |
2729 |
|
2730 | |||
2730 | def revert(ui, repo, ctx, parents, *pats, **opts): |
|
2731 | def revert(ui, repo, ctx, parents, *pats, **opts): | |
2731 | opts = pycompat.byteskwargs(opts) |
|
2732 | opts = pycompat.byteskwargs(opts) | |
2732 | parent, p2 = parents |
|
2733 | parent, p2 = parents | |
2733 | node = ctx.node() |
|
2734 | node = ctx.node() | |
2734 |
|
2735 | |||
2735 | mf = ctx.manifest() |
|
2736 | mf = ctx.manifest() | |
2736 | if node == p2: |
|
2737 | if node == p2: | |
2737 | parent = p2 |
|
2738 | parent = p2 | |
2738 |
|
2739 | |||
2739 | # need all matching names in dirstate and manifest of target rev, |
|
2740 | # need all matching names in dirstate and manifest of target rev, | |
2740 | # so have to walk both. do not print errors if files exist in one |
|
2741 | # so have to walk both. do not print errors if files exist in one | |
2741 | # but not other. in both cases, filesets should be evaluated against |
|
2742 | # but not other. in both cases, filesets should be evaluated against | |
2742 | # workingctx to get consistent result (issue4497). this means 'set:**' |
|
2743 | # workingctx to get consistent result (issue4497). this means 'set:**' | |
2743 | # cannot be used to select missing files from target rev. |
|
2744 | # cannot be used to select missing files from target rev. | |
2744 |
|
2745 | |||
2745 | # `names` is a mapping for all elements in working copy and target revision |
|
2746 | # `names` is a mapping for all elements in working copy and target revision | |
2746 | # The mapping is in the form: |
|
2747 | # The mapping is in the form: | |
2747 | # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>) |
|
2748 | # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>) | |
2748 | names = {} |
|
2749 | names = {} | |
2749 |
|
2750 | |||
2750 | with repo.wlock(): |
|
2751 | with repo.wlock(): | |
2751 | ## filling of the `names` mapping |
|
2752 | ## filling of the `names` mapping | |
2752 | # walk dirstate to fill `names` |
|
2753 | # walk dirstate to fill `names` | |
2753 |
|
2754 | |||
2754 | interactive = opts.get('interactive', False) |
|
2755 | interactive = opts.get('interactive', False) | |
2755 | wctx = repo[None] |
|
2756 | wctx = repo[None] | |
2756 | m = scmutil.match(wctx, pats, opts) |
|
2757 | m = scmutil.match(wctx, pats, opts) | |
2757 |
|
2758 | |||
2758 | # we'll need this later |
|
2759 | # we'll need this later | |
2759 | targetsubs = sorted(s for s in wctx.substate if m(s)) |
|
2760 | targetsubs = sorted(s for s in wctx.substate if m(s)) | |
2760 |
|
2761 | |||
2761 | if not m.always(): |
|
2762 | if not m.always(): | |
2762 | matcher = matchmod.badmatch(m, lambda x, y: False) |
|
2763 | matcher = matchmod.badmatch(m, lambda x, y: False) | |
2763 | for abs in wctx.walk(matcher): |
|
2764 | for abs in wctx.walk(matcher): | |
2764 | names[abs] = m.rel(abs), m.exact(abs) |
|
2765 | names[abs] = m.rel(abs), m.exact(abs) | |
2765 |
|
2766 | |||
2766 | # walk target manifest to fill `names` |
|
2767 | # walk target manifest to fill `names` | |
2767 |
|
2768 | |||
2768 | def badfn(path, msg): |
|
2769 | def badfn(path, msg): | |
2769 | if path in names: |
|
2770 | if path in names: | |
2770 | return |
|
2771 | return | |
2771 | if path in ctx.substate: |
|
2772 | if path in ctx.substate: | |
2772 | return |
|
2773 | return | |
2773 | path_ = path + '/' |
|
2774 | path_ = path + '/' | |
2774 | for f in names: |
|
2775 | for f in names: | |
2775 | if f.startswith(path_): |
|
2776 | if f.startswith(path_): | |
2776 | return |
|
2777 | return | |
2777 | ui.warn("%s: %s\n" % (m.rel(path), msg)) |
|
2778 | ui.warn("%s: %s\n" % (m.rel(path), msg)) | |
2778 |
|
2779 | |||
2779 | for abs in ctx.walk(matchmod.badmatch(m, badfn)): |
|
2780 | for abs in ctx.walk(matchmod.badmatch(m, badfn)): | |
2780 | if abs not in names: |
|
2781 | if abs not in names: | |
2781 | names[abs] = m.rel(abs), m.exact(abs) |
|
2782 | names[abs] = m.rel(abs), m.exact(abs) | |
2782 |
|
2783 | |||
2783 | # Find status of all file in `names`. |
|
2784 | # Find status of all file in `names`. | |
2784 | m = scmutil.matchfiles(repo, names) |
|
2785 | m = scmutil.matchfiles(repo, names) | |
2785 |
|
2786 | |||
2786 | changes = repo.status(node1=node, match=m, |
|
2787 | changes = repo.status(node1=node, match=m, | |
2787 | unknown=True, ignored=True, clean=True) |
|
2788 | unknown=True, ignored=True, clean=True) | |
2788 | else: |
|
2789 | else: | |
2789 | changes = repo.status(node1=node, match=m) |
|
2790 | changes = repo.status(node1=node, match=m) | |
2790 | for kind in changes: |
|
2791 | for kind in changes: | |
2791 | for abs in kind: |
|
2792 | for abs in kind: | |
2792 | names[abs] = m.rel(abs), m.exact(abs) |
|
2793 | names[abs] = m.rel(abs), m.exact(abs) | |
2793 |
|
2794 | |||
2794 | m = scmutil.matchfiles(repo, names) |
|
2795 | m = scmutil.matchfiles(repo, names) | |
2795 |
|
2796 | |||
2796 | modified = set(changes.modified) |
|
2797 | modified = set(changes.modified) | |
2797 | added = set(changes.added) |
|
2798 | added = set(changes.added) | |
2798 | removed = set(changes.removed) |
|
2799 | removed = set(changes.removed) | |
2799 | _deleted = set(changes.deleted) |
|
2800 | _deleted = set(changes.deleted) | |
2800 | unknown = set(changes.unknown) |
|
2801 | unknown = set(changes.unknown) | |
2801 | unknown.update(changes.ignored) |
|
2802 | unknown.update(changes.ignored) | |
2802 | clean = set(changes.clean) |
|
2803 | clean = set(changes.clean) | |
2803 | modadded = set() |
|
2804 | modadded = set() | |
2804 |
|
2805 | |||
2805 | # We need to account for the state of the file in the dirstate, |
|
2806 | # We need to account for the state of the file in the dirstate, | |
2806 | # even when we revert against something else than parent. This will |
|
2807 | # even when we revert against something else than parent. This will | |
2807 | # slightly alter the behavior of revert (doing back up or not, delete |
|
2808 | # slightly alter the behavior of revert (doing back up or not, delete | |
2808 | # or just forget etc). |
|
2809 | # or just forget etc). | |
2809 | if parent == node: |
|
2810 | if parent == node: | |
2810 | dsmodified = modified |
|
2811 | dsmodified = modified | |
2811 | dsadded = added |
|
2812 | dsadded = added | |
2812 | dsremoved = removed |
|
2813 | dsremoved = removed | |
2813 | # store all local modifications, useful later for rename detection |
|
2814 | # store all local modifications, useful later for rename detection | |
2814 | localchanges = dsmodified | dsadded |
|
2815 | localchanges = dsmodified | dsadded | |
2815 | modified, added, removed = set(), set(), set() |
|
2816 | modified, added, removed = set(), set(), set() | |
2816 | else: |
|
2817 | else: | |
2817 | changes = repo.status(node1=parent, match=m) |
|
2818 | changes = repo.status(node1=parent, match=m) | |
2818 | dsmodified = set(changes.modified) |
|
2819 | dsmodified = set(changes.modified) | |
2819 | dsadded = set(changes.added) |
|
2820 | dsadded = set(changes.added) | |
2820 | dsremoved = set(changes.removed) |
|
2821 | dsremoved = set(changes.removed) | |
2821 | # store all local modifications, useful later for rename detection |
|
2822 | # store all local modifications, useful later for rename detection | |
2822 | localchanges = dsmodified | dsadded |
|
2823 | localchanges = dsmodified | dsadded | |
2823 |
|
2824 | |||
2824 | # only take into account for removes between wc and target |
|
2825 | # only take into account for removes between wc and target | |
2825 | clean |= dsremoved - removed |
|
2826 | clean |= dsremoved - removed | |
2826 | dsremoved &= removed |
|
2827 | dsremoved &= removed | |
2827 | # distinct between dirstate remove and other |
|
2828 | # distinct between dirstate remove and other | |
2828 | removed -= dsremoved |
|
2829 | removed -= dsremoved | |
2829 |
|
2830 | |||
2830 | modadded = added & dsmodified |
|
2831 | modadded = added & dsmodified | |
2831 | added -= modadded |
|
2832 | added -= modadded | |
2832 |
|
2833 | |||
2833 | # tell newly modified apart. |
|
2834 | # tell newly modified apart. | |
2834 | dsmodified &= modified |
|
2835 | dsmodified &= modified | |
2835 | dsmodified |= modified & dsadded # dirstate added may need backup |
|
2836 | dsmodified |= modified & dsadded # dirstate added may need backup | |
2836 | modified -= dsmodified |
|
2837 | modified -= dsmodified | |
2837 |
|
2838 | |||
2838 | # We need to wait for some post-processing to update this set |
|
2839 | # We need to wait for some post-processing to update this set | |
2839 | # before making the distinction. The dirstate will be used for |
|
2840 | # before making the distinction. The dirstate will be used for | |
2840 | # that purpose. |
|
2841 | # that purpose. | |
2841 | dsadded = added |
|
2842 | dsadded = added | |
2842 |
|
2843 | |||
2843 | # in case of merge, files that are actually added can be reported as |
|
2844 | # in case of merge, files that are actually added can be reported as | |
2844 | # modified, we need to post process the result |
|
2845 | # modified, we need to post process the result | |
2845 | if p2 != nullid: |
|
2846 | if p2 != nullid: | |
2846 | mergeadd = set(dsmodified) |
|
2847 | mergeadd = set(dsmodified) | |
2847 | for path in dsmodified: |
|
2848 | for path in dsmodified: | |
2848 | if path in mf: |
|
2849 | if path in mf: | |
2849 | mergeadd.remove(path) |
|
2850 | mergeadd.remove(path) | |
2850 | dsadded |= mergeadd |
|
2851 | dsadded |= mergeadd | |
2851 | dsmodified -= mergeadd |
|
2852 | dsmodified -= mergeadd | |
2852 |
|
2853 | |||
2853 | # if f is a rename, update `names` to also revert the source |
|
2854 | # if f is a rename, update `names` to also revert the source | |
2854 | cwd = repo.getcwd() |
|
2855 | cwd = repo.getcwd() | |
2855 | for f in localchanges: |
|
2856 | for f in localchanges: | |
2856 | src = repo.dirstate.copied(f) |
|
2857 | src = repo.dirstate.copied(f) | |
2857 | # XXX should we check for rename down to target node? |
|
2858 | # XXX should we check for rename down to target node? | |
2858 | if src and src not in names and repo.dirstate[src] == 'r': |
|
2859 | if src and src not in names and repo.dirstate[src] == 'r': | |
2859 | dsremoved.add(src) |
|
2860 | dsremoved.add(src) | |
2860 | names[src] = (repo.pathto(src, cwd), True) |
|
2861 | names[src] = (repo.pathto(src, cwd), True) | |
2861 |
|
2862 | |||
2862 | # determine the exact nature of the deleted changesets |
|
2863 | # determine the exact nature of the deleted changesets | |
2863 | deladded = set(_deleted) |
|
2864 | deladded = set(_deleted) | |
2864 | for path in _deleted: |
|
2865 | for path in _deleted: | |
2865 | if path in mf: |
|
2866 | if path in mf: | |
2866 | deladded.remove(path) |
|
2867 | deladded.remove(path) | |
2867 | deleted = _deleted - deladded |
|
2868 | deleted = _deleted - deladded | |
2868 |
|
2869 | |||
2869 | # distinguish between file to forget and the other |
|
2870 | # distinguish between file to forget and the other | |
2870 | added = set() |
|
2871 | added = set() | |
2871 | for abs in dsadded: |
|
2872 | for abs in dsadded: | |
2872 | if repo.dirstate[abs] != 'a': |
|
2873 | if repo.dirstate[abs] != 'a': | |
2873 | added.add(abs) |
|
2874 | added.add(abs) | |
2874 | dsadded -= added |
|
2875 | dsadded -= added | |
2875 |
|
2876 | |||
2876 | for abs in deladded: |
|
2877 | for abs in deladded: | |
2877 | if repo.dirstate[abs] == 'a': |
|
2878 | if repo.dirstate[abs] == 'a': | |
2878 | dsadded.add(abs) |
|
2879 | dsadded.add(abs) | |
2879 | deladded -= dsadded |
|
2880 | deladded -= dsadded | |
2880 |
|
2881 | |||
2881 | # For files marked as removed, we check if an unknown file is present at |
|
2882 | # For files marked as removed, we check if an unknown file is present at | |
2882 | # the same path. If a such file exists it may need to be backed up. |
|
2883 | # the same path. If a such file exists it may need to be backed up. | |
2883 | # Making the distinction at this stage helps have simpler backup |
|
2884 | # Making the distinction at this stage helps have simpler backup | |
2884 | # logic. |
|
2885 | # logic. | |
2885 | removunk = set() |
|
2886 | removunk = set() | |
2886 | for abs in removed: |
|
2887 | for abs in removed: | |
2887 | target = repo.wjoin(abs) |
|
2888 | target = repo.wjoin(abs) | |
2888 | if os.path.lexists(target): |
|
2889 | if os.path.lexists(target): | |
2889 | removunk.add(abs) |
|
2890 | removunk.add(abs) | |
2890 | removed -= removunk |
|
2891 | removed -= removunk | |
2891 |
|
2892 | |||
2892 | dsremovunk = set() |
|
2893 | dsremovunk = set() | |
2893 | for abs in dsremoved: |
|
2894 | for abs in dsremoved: | |
2894 | target = repo.wjoin(abs) |
|
2895 | target = repo.wjoin(abs) | |
2895 | if os.path.lexists(target): |
|
2896 | if os.path.lexists(target): | |
2896 | dsremovunk.add(abs) |
|
2897 | dsremovunk.add(abs) | |
2897 | dsremoved -= dsremovunk |
|
2898 | dsremoved -= dsremovunk | |
2898 |
|
2899 | |||
2899 | # action to be actually performed by revert |
|
2900 | # action to be actually performed by revert | |
2900 | # (<list of file>, message>) tuple |
|
2901 | # (<list of file>, message>) tuple | |
2901 | actions = {'revert': ([], _('reverting %s\n')), |
|
2902 | actions = {'revert': ([], _('reverting %s\n')), | |
2902 | 'add': ([], _('adding %s\n')), |
|
2903 | 'add': ([], _('adding %s\n')), | |
2903 | 'remove': ([], _('removing %s\n')), |
|
2904 | 'remove': ([], _('removing %s\n')), | |
2904 | 'drop': ([], _('removing %s\n')), |
|
2905 | 'drop': ([], _('removing %s\n')), | |
2905 | 'forget': ([], _('forgetting %s\n')), |
|
2906 | 'forget': ([], _('forgetting %s\n')), | |
2906 | 'undelete': ([], _('undeleting %s\n')), |
|
2907 | 'undelete': ([], _('undeleting %s\n')), | |
2907 | 'noop': (None, _('no changes needed to %s\n')), |
|
2908 | 'noop': (None, _('no changes needed to %s\n')), | |
2908 | 'unknown': (None, _('file not managed: %s\n')), |
|
2909 | 'unknown': (None, _('file not managed: %s\n')), | |
2909 | } |
|
2910 | } | |
2910 |
|
2911 | |||
2911 | # "constant" that convey the backup strategy. |
|
2912 | # "constant" that convey the backup strategy. | |
2912 | # All set to `discard` if `no-backup` is set do avoid checking |
|
2913 | # All set to `discard` if `no-backup` is set do avoid checking | |
2913 | # no_backup lower in the code. |
|
2914 | # no_backup lower in the code. | |
2914 | # These values are ordered for comparison purposes |
|
2915 | # These values are ordered for comparison purposes | |
2915 | backupinteractive = 3 # do backup if interactively modified |
|
2916 | backupinteractive = 3 # do backup if interactively modified | |
2916 | backup = 2 # unconditionally do backup |
|
2917 | backup = 2 # unconditionally do backup | |
2917 | check = 1 # check if the existing file differs from target |
|
2918 | check = 1 # check if the existing file differs from target | |
2918 | discard = 0 # never do backup |
|
2919 | discard = 0 # never do backup | |
2919 | if opts.get('no_backup'): |
|
2920 | if opts.get('no_backup'): | |
2920 | backupinteractive = backup = check = discard |
|
2921 | backupinteractive = backup = check = discard | |
2921 | if interactive: |
|
2922 | if interactive: | |
2922 | dsmodifiedbackup = backupinteractive |
|
2923 | dsmodifiedbackup = backupinteractive | |
2923 | else: |
|
2924 | else: | |
2924 | dsmodifiedbackup = backup |
|
2925 | dsmodifiedbackup = backup | |
2925 | tobackup = set() |
|
2926 | tobackup = set() | |
2926 |
|
2927 | |||
2927 | backupanddel = actions['remove'] |
|
2928 | backupanddel = actions['remove'] | |
2928 | if not opts.get('no_backup'): |
|
2929 | if not opts.get('no_backup'): | |
2929 | backupanddel = actions['drop'] |
|
2930 | backupanddel = actions['drop'] | |
2930 |
|
2931 | |||
2931 | disptable = ( |
|
2932 | disptable = ( | |
2932 | # dispatch table: |
|
2933 | # dispatch table: | |
2933 | # file state |
|
2934 | # file state | |
2934 | # action |
|
2935 | # action | |
2935 | # make backup |
|
2936 | # make backup | |
2936 |
|
2937 | |||
2937 | ## Sets that results that will change file on disk |
|
2938 | ## Sets that results that will change file on disk | |
2938 | # Modified compared to target, no local change |
|
2939 | # Modified compared to target, no local change | |
2939 | (modified, actions['revert'], discard), |
|
2940 | (modified, actions['revert'], discard), | |
2940 | # Modified compared to target, but local file is deleted |
|
2941 | # Modified compared to target, but local file is deleted | |
2941 | (deleted, actions['revert'], discard), |
|
2942 | (deleted, actions['revert'], discard), | |
2942 | # Modified compared to target, local change |
|
2943 | # Modified compared to target, local change | |
2943 | (dsmodified, actions['revert'], dsmodifiedbackup), |
|
2944 | (dsmodified, actions['revert'], dsmodifiedbackup), | |
2944 | # Added since target |
|
2945 | # Added since target | |
2945 | (added, actions['remove'], discard), |
|
2946 | (added, actions['remove'], discard), | |
2946 | # Added in working directory |
|
2947 | # Added in working directory | |
2947 | (dsadded, actions['forget'], discard), |
|
2948 | (dsadded, actions['forget'], discard), | |
2948 | # Added since target, have local modification |
|
2949 | # Added since target, have local modification | |
2949 | (modadded, backupanddel, backup), |
|
2950 | (modadded, backupanddel, backup), | |
2950 | # Added since target but file is missing in working directory |
|
2951 | # Added since target but file is missing in working directory | |
2951 | (deladded, actions['drop'], discard), |
|
2952 | (deladded, actions['drop'], discard), | |
2952 | # Removed since target, before working copy parent |
|
2953 | # Removed since target, before working copy parent | |
2953 | (removed, actions['add'], discard), |
|
2954 | (removed, actions['add'], discard), | |
2954 | # Same as `removed` but an unknown file exists at the same path |
|
2955 | # Same as `removed` but an unknown file exists at the same path | |
2955 | (removunk, actions['add'], check), |
|
2956 | (removunk, actions['add'], check), | |
2956 | # Removed since targe, marked as such in working copy parent |
|
2957 | # Removed since targe, marked as such in working copy parent | |
2957 | (dsremoved, actions['undelete'], discard), |
|
2958 | (dsremoved, actions['undelete'], discard), | |
2958 | # Same as `dsremoved` but an unknown file exists at the same path |
|
2959 | # Same as `dsremoved` but an unknown file exists at the same path | |
2959 | (dsremovunk, actions['undelete'], check), |
|
2960 | (dsremovunk, actions['undelete'], check), | |
2960 | ## the following sets does not result in any file changes |
|
2961 | ## the following sets does not result in any file changes | |
2961 | # File with no modification |
|
2962 | # File with no modification | |
2962 | (clean, actions['noop'], discard), |
|
2963 | (clean, actions['noop'], discard), | |
2963 | # Existing file, not tracked anywhere |
|
2964 | # Existing file, not tracked anywhere | |
2964 | (unknown, actions['unknown'], discard), |
|
2965 | (unknown, actions['unknown'], discard), | |
2965 | ) |
|
2966 | ) | |
2966 |
|
2967 | |||
2967 | for abs, (rel, exact) in sorted(names.items()): |
|
2968 | for abs, (rel, exact) in sorted(names.items()): | |
2968 | # target file to be touch on disk (relative to cwd) |
|
2969 | # target file to be touch on disk (relative to cwd) | |
2969 | target = repo.wjoin(abs) |
|
2970 | target = repo.wjoin(abs) | |
2970 | # search the entry in the dispatch table. |
|
2971 | # search the entry in the dispatch table. | |
2971 | # if the file is in any of these sets, it was touched in the working |
|
2972 | # if the file is in any of these sets, it was touched in the working | |
2972 | # directory parent and we are sure it needs to be reverted. |
|
2973 | # directory parent and we are sure it needs to be reverted. | |
2973 | for table, (xlist, msg), dobackup in disptable: |
|
2974 | for table, (xlist, msg), dobackup in disptable: | |
2974 | if abs not in table: |
|
2975 | if abs not in table: | |
2975 | continue |
|
2976 | continue | |
2976 | if xlist is not None: |
|
2977 | if xlist is not None: | |
2977 | xlist.append(abs) |
|
2978 | xlist.append(abs) | |
2978 | if dobackup: |
|
2979 | if dobackup: | |
2979 | # If in interactive mode, don't automatically create |
|
2980 | # If in interactive mode, don't automatically create | |
2980 | # .orig files (issue4793) |
|
2981 | # .orig files (issue4793) | |
2981 | if dobackup == backupinteractive: |
|
2982 | if dobackup == backupinteractive: | |
2982 | tobackup.add(abs) |
|
2983 | tobackup.add(abs) | |
2983 | elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])): |
|
2984 | elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])): | |
2984 | bakname = scmutil.origpath(ui, repo, rel) |
|
2985 | bakname = scmutil.origpath(ui, repo, rel) | |
2985 | ui.note(_('saving current version of %s as %s\n') % |
|
2986 | ui.note(_('saving current version of %s as %s\n') % | |
2986 | (rel, bakname)) |
|
2987 | (rel, bakname)) | |
2987 | if not opts.get('dry_run'): |
|
2988 | if not opts.get('dry_run'): | |
2988 | if interactive: |
|
2989 | if interactive: | |
2989 | util.copyfile(target, bakname) |
|
2990 | util.copyfile(target, bakname) | |
2990 | else: |
|
2991 | else: | |
2991 | util.rename(target, bakname) |
|
2992 | util.rename(target, bakname) | |
2992 | if ui.verbose or not exact: |
|
2993 | if ui.verbose or not exact: | |
2993 | if not isinstance(msg, bytes): |
|
2994 | if not isinstance(msg, bytes): | |
2994 | msg = msg(abs) |
|
2995 | msg = msg(abs) | |
2995 | ui.status(msg % rel) |
|
2996 | ui.status(msg % rel) | |
2996 | elif exact: |
|
2997 | elif exact: | |
2997 | ui.warn(msg % rel) |
|
2998 | ui.warn(msg % rel) | |
2998 | break |
|
2999 | break | |
2999 |
|
3000 | |||
3000 | if not opts.get('dry_run'): |
|
3001 | if not opts.get('dry_run'): | |
3001 | needdata = ('revert', 'add', 'undelete') |
|
3002 | needdata = ('revert', 'add', 'undelete') | |
3002 | oplist = [actions[name][0] for name in needdata] |
|
3003 | oplist = [actions[name][0] for name in needdata] | |
3003 | prefetch = scmutil.prefetchfiles |
|
3004 | prefetch = scmutil.prefetchfiles | |
3004 | matchfiles = scmutil.matchfiles |
|
3005 | matchfiles = scmutil.matchfiles | |
3005 | prefetch(repo, [ctx.rev()], |
|
3006 | prefetch(repo, [ctx.rev()], | |
3006 | matchfiles(repo, |
|
3007 | matchfiles(repo, | |
3007 | [f for sublist in oplist for f in sublist])) |
|
3008 | [f for sublist in oplist for f in sublist])) | |
3008 | _performrevert(repo, parents, ctx, actions, interactive, tobackup) |
|
3009 | _performrevert(repo, parents, ctx, actions, interactive, tobackup) | |
3009 |
|
3010 | |||
3010 | if targetsubs: |
|
3011 | if targetsubs: | |
3011 | # Revert the subrepos on the revert list |
|
3012 | # Revert the subrepos on the revert list | |
3012 | for sub in targetsubs: |
|
3013 | for sub in targetsubs: | |
3013 | try: |
|
3014 | try: | |
3014 | wctx.sub(sub).revert(ctx.substate[sub], *pats, |
|
3015 | wctx.sub(sub).revert(ctx.substate[sub], *pats, | |
3015 | **pycompat.strkwargs(opts)) |
|
3016 | **pycompat.strkwargs(opts)) | |
3016 | except KeyError: |
|
3017 | except KeyError: | |
3017 | raise error.Abort("subrepository '%s' does not exist in %s!" |
|
3018 | raise error.Abort("subrepository '%s' does not exist in %s!" | |
3018 | % (sub, short(ctx.node()))) |
|
3019 | % (sub, short(ctx.node()))) | |
3019 |
|
3020 | |||
3020 | def _performrevert(repo, parents, ctx, actions, interactive=False, |
|
3021 | def _performrevert(repo, parents, ctx, actions, interactive=False, | |
3021 | tobackup=None): |
|
3022 | tobackup=None): | |
3022 | """function that actually perform all the actions computed for revert |
|
3023 | """function that actually perform all the actions computed for revert | |
3023 |
|
3024 | |||
3024 | This is an independent function to let extension to plug in and react to |
|
3025 | This is an independent function to let extension to plug in and react to | |
3025 | the imminent revert. |
|
3026 | the imminent revert. | |
3026 |
|
3027 | |||
3027 | Make sure you have the working directory locked when calling this function. |
|
3028 | Make sure you have the working directory locked when calling this function. | |
3028 | """ |
|
3029 | """ | |
3029 | parent, p2 = parents |
|
3030 | parent, p2 = parents | |
3030 | node = ctx.node() |
|
3031 | node = ctx.node() | |
3031 | excluded_files = [] |
|
3032 | excluded_files = [] | |
3032 |
|
3033 | |||
3033 | def checkout(f): |
|
3034 | def checkout(f): | |
3034 | fc = ctx[f] |
|
3035 | fc = ctx[f] | |
3035 | repo.wwrite(f, fc.data(), fc.flags()) |
|
3036 | repo.wwrite(f, fc.data(), fc.flags()) | |
3036 |
|
3037 | |||
3037 | def doremove(f): |
|
3038 | def doremove(f): | |
3038 | try: |
|
3039 | try: | |
3039 | rmdir = repo.ui.configbool('experimental', 'removeemptydirs') |
|
3040 | rmdir = repo.ui.configbool('experimental', 'removeemptydirs') | |
3040 | repo.wvfs.unlinkpath(f, rmdir=rmdir) |
|
3041 | repo.wvfs.unlinkpath(f, rmdir=rmdir) | |
3041 | except OSError: |
|
3042 | except OSError: | |
3042 | pass |
|
3043 | pass | |
3043 | repo.dirstate.remove(f) |
|
3044 | repo.dirstate.remove(f) | |
3044 |
|
3045 | |||
3045 | audit_path = pathutil.pathauditor(repo.root, cached=True) |
|
3046 | audit_path = pathutil.pathauditor(repo.root, cached=True) | |
3046 | for f in actions['forget'][0]: |
|
3047 | for f in actions['forget'][0]: | |
3047 | if interactive: |
|
3048 | if interactive: | |
3048 | choice = repo.ui.promptchoice( |
|
3049 | choice = repo.ui.promptchoice( | |
3049 | _("forget added file %s (Yn)?$$ &Yes $$ &No") % f) |
|
3050 | _("forget added file %s (Yn)?$$ &Yes $$ &No") % f) | |
3050 | if choice == 0: |
|
3051 | if choice == 0: | |
3051 | repo.dirstate.drop(f) |
|
3052 | repo.dirstate.drop(f) | |
3052 | else: |
|
3053 | else: | |
3053 | excluded_files.append(f) |
|
3054 | excluded_files.append(f) | |
3054 | else: |
|
3055 | else: | |
3055 | repo.dirstate.drop(f) |
|
3056 | repo.dirstate.drop(f) | |
3056 | for f in actions['remove'][0]: |
|
3057 | for f in actions['remove'][0]: | |
3057 | audit_path(f) |
|
3058 | audit_path(f) | |
3058 | if interactive: |
|
3059 | if interactive: | |
3059 | choice = repo.ui.promptchoice( |
|
3060 | choice = repo.ui.promptchoice( | |
3060 | _("remove added file %s (Yn)?$$ &Yes $$ &No") % f) |
|
3061 | _("remove added file %s (Yn)?$$ &Yes $$ &No") % f) | |
3061 | if choice == 0: |
|
3062 | if choice == 0: | |
3062 | doremove(f) |
|
3063 | doremove(f) | |
3063 | else: |
|
3064 | else: | |
3064 | excluded_files.append(f) |
|
3065 | excluded_files.append(f) | |
3065 | else: |
|
3066 | else: | |
3066 | doremove(f) |
|
3067 | doremove(f) | |
3067 | for f in actions['drop'][0]: |
|
3068 | for f in actions['drop'][0]: | |
3068 | audit_path(f) |
|
3069 | audit_path(f) | |
3069 | repo.dirstate.remove(f) |
|
3070 | repo.dirstate.remove(f) | |
3070 |
|
3071 | |||
3071 | normal = None |
|
3072 | normal = None | |
3072 | if node == parent: |
|
3073 | if node == parent: | |
3073 | # We're reverting to our parent. If possible, we'd like status |
|
3074 | # We're reverting to our parent. If possible, we'd like status | |
3074 | # to report the file as clean. We have to use normallookup for |
|
3075 | # to report the file as clean. We have to use normallookup for | |
3075 | # merges to avoid losing information about merged/dirty files. |
|
3076 | # merges to avoid losing information about merged/dirty files. | |
3076 | if p2 != nullid: |
|
3077 | if p2 != nullid: | |
3077 | normal = repo.dirstate.normallookup |
|
3078 | normal = repo.dirstate.normallookup | |
3078 | else: |
|
3079 | else: | |
3079 | normal = repo.dirstate.normal |
|
3080 | normal = repo.dirstate.normal | |
3080 |
|
3081 | |||
3081 | newlyaddedandmodifiedfiles = set() |
|
3082 | newlyaddedandmodifiedfiles = set() | |
3082 | if interactive: |
|
3083 | if interactive: | |
3083 | # Prompt the user for changes to revert |
|
3084 | # Prompt the user for changes to revert | |
3084 | torevert = [f for f in actions['revert'][0] if f not in excluded_files] |
|
3085 | torevert = [f for f in actions['revert'][0] if f not in excluded_files] | |
3085 | m = scmutil.matchfiles(repo, torevert) |
|
3086 | m = scmutil.matchfiles(repo, torevert) | |
3086 | diffopts = patch.difffeatureopts(repo.ui, whitespace=True) |
|
3087 | diffopts = patch.difffeatureopts(repo.ui, whitespace=True) | |
3087 | diffopts.nodates = True |
|
3088 | diffopts.nodates = True | |
3088 | diffopts.git = True |
|
3089 | diffopts.git = True | |
3089 | operation = 'discard' |
|
3090 | operation = 'discard' | |
3090 | reversehunks = True |
|
3091 | reversehunks = True | |
3091 | if node != parent: |
|
3092 | if node != parent: | |
3092 | operation = 'apply' |
|
3093 | operation = 'apply' | |
3093 | reversehunks = False |
|
3094 | reversehunks = False | |
3094 | if reversehunks: |
|
3095 | if reversehunks: | |
3095 | diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts) |
|
3096 | diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts) | |
3096 | else: |
|
3097 | else: | |
3097 | diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts) |
|
3098 | diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts) | |
3098 | originalchunks = patch.parsepatch(diff) |
|
3099 | originalchunks = patch.parsepatch(diff) | |
3099 |
|
3100 | |||
3100 | try: |
|
3101 | try: | |
3101 |
|
3102 | |||
3102 | chunks, opts = recordfilter(repo.ui, originalchunks, |
|
3103 | chunks, opts = recordfilter(repo.ui, originalchunks, | |
3103 | operation=operation) |
|
3104 | operation=operation) | |
3104 | if reversehunks: |
|
3105 | if reversehunks: | |
3105 | chunks = patch.reversehunks(chunks) |
|
3106 | chunks = patch.reversehunks(chunks) | |
3106 |
|
3107 | |||
3107 | except error.PatchError as err: |
|
3108 | except error.PatchError as err: | |
3108 | raise error.Abort(_('error parsing patch: %s') % err) |
|
3109 | raise error.Abort(_('error parsing patch: %s') % err) | |
3109 |
|
3110 | |||
3110 | newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks) |
|
3111 | newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks) | |
3111 | if tobackup is None: |
|
3112 | if tobackup is None: | |
3112 | tobackup = set() |
|
3113 | tobackup = set() | |
3113 | # Apply changes |
|
3114 | # Apply changes | |
3114 | fp = stringio() |
|
3115 | fp = stringio() | |
3115 | for c in chunks: |
|
3116 | for c in chunks: | |
3116 | # Create a backup file only if this hunk should be backed up |
|
3117 | # Create a backup file only if this hunk should be backed up | |
3117 | if ishunk(c) and c.header.filename() in tobackup: |
|
3118 | if ishunk(c) and c.header.filename() in tobackup: | |
3118 | abs = c.header.filename() |
|
3119 | abs = c.header.filename() | |
3119 | target = repo.wjoin(abs) |
|
3120 | target = repo.wjoin(abs) | |
3120 | bakname = scmutil.origpath(repo.ui, repo, m.rel(abs)) |
|
3121 | bakname = scmutil.origpath(repo.ui, repo, m.rel(abs)) | |
3121 | util.copyfile(target, bakname) |
|
3122 | util.copyfile(target, bakname) | |
3122 | tobackup.remove(abs) |
|
3123 | tobackup.remove(abs) | |
3123 | c.write(fp) |
|
3124 | c.write(fp) | |
3124 | dopatch = fp.tell() |
|
3125 | dopatch = fp.tell() | |
3125 | fp.seek(0) |
|
3126 | fp.seek(0) | |
3126 | if dopatch: |
|
3127 | if dopatch: | |
3127 | try: |
|
3128 | try: | |
3128 | patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None) |
|
3129 | patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None) | |
3129 | except error.PatchError as err: |
|
3130 | except error.PatchError as err: | |
3130 | raise error.Abort(pycompat.bytestr(err)) |
|
3131 | raise error.Abort(pycompat.bytestr(err)) | |
3131 | del fp |
|
3132 | del fp | |
3132 | else: |
|
3133 | else: | |
3133 | for f in actions['revert'][0]: |
|
3134 | for f in actions['revert'][0]: | |
3134 | checkout(f) |
|
3135 | checkout(f) | |
3135 | if normal: |
|
3136 | if normal: | |
3136 | normal(f) |
|
3137 | normal(f) | |
3137 |
|
3138 | |||
3138 | for f in actions['add'][0]: |
|
3139 | for f in actions['add'][0]: | |
3139 | # Don't checkout modified files, they are already created by the diff |
|
3140 | # Don't checkout modified files, they are already created by the diff | |
3140 | if f not in newlyaddedandmodifiedfiles: |
|
3141 | if f not in newlyaddedandmodifiedfiles: | |
3141 | checkout(f) |
|
3142 | checkout(f) | |
3142 | repo.dirstate.add(f) |
|
3143 | repo.dirstate.add(f) | |
3143 |
|
3144 | |||
3144 | normal = repo.dirstate.normallookup |
|
3145 | normal = repo.dirstate.normallookup | |
3145 | if node == parent and p2 == nullid: |
|
3146 | if node == parent and p2 == nullid: | |
3146 | normal = repo.dirstate.normal |
|
3147 | normal = repo.dirstate.normal | |
3147 | for f in actions['undelete'][0]: |
|
3148 | for f in actions['undelete'][0]: | |
3148 | checkout(f) |
|
3149 | checkout(f) | |
3149 | normal(f) |
|
3150 | normal(f) | |
3150 |
|
3151 | |||
3151 | copied = copies.pathcopies(repo[parent], ctx) |
|
3152 | copied = copies.pathcopies(repo[parent], ctx) | |
3152 |
|
3153 | |||
3153 | for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]: |
|
3154 | for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]: | |
3154 | if f in copied: |
|
3155 | if f in copied: | |
3155 | repo.dirstate.copy(copied[f], f) |
|
3156 | repo.dirstate.copy(copied[f], f) | |
3156 |
|
3157 | |||
3157 | # a list of (ui, repo, otherpeer, opts, missing) functions called by |
|
3158 | # a list of (ui, repo, otherpeer, opts, missing) functions called by | |
3158 | # commands.outgoing. "missing" is "missing" of the result of |
|
3159 | # commands.outgoing. "missing" is "missing" of the result of | |
3159 | # "findcommonoutgoing()" |
|
3160 | # "findcommonoutgoing()" | |
3160 | outgoinghooks = util.hooks() |
|
3161 | outgoinghooks = util.hooks() | |
3161 |
|
3162 | |||
3162 | # a list of (ui, repo) functions called by commands.summary |
|
3163 | # a list of (ui, repo) functions called by commands.summary | |
3163 | summaryhooks = util.hooks() |
|
3164 | summaryhooks = util.hooks() | |
3164 |
|
3165 | |||
3165 | # a list of (ui, repo, opts, changes) functions called by commands.summary. |
|
3166 | # a list of (ui, repo, opts, changes) functions called by commands.summary. | |
3166 | # |
|
3167 | # | |
3167 | # functions should return tuple of booleans below, if 'changes' is None: |
|
3168 | # functions should return tuple of booleans below, if 'changes' is None: | |
3168 | # (whether-incomings-are-needed, whether-outgoings-are-needed) |
|
3169 | # (whether-incomings-are-needed, whether-outgoings-are-needed) | |
3169 | # |
|
3170 | # | |
3170 | # otherwise, 'changes' is a tuple of tuples below: |
|
3171 | # otherwise, 'changes' is a tuple of tuples below: | |
3171 | # - (sourceurl, sourcebranch, sourcepeer, incoming) |
|
3172 | # - (sourceurl, sourcebranch, sourcepeer, incoming) | |
3172 | # - (desturl, destbranch, destpeer, outgoing) |
|
3173 | # - (desturl, destbranch, destpeer, outgoing) | |
3173 | summaryremotehooks = util.hooks() |
|
3174 | summaryremotehooks = util.hooks() | |
3174 |
|
3175 | |||
3175 | # A list of state files kept by multistep operations like graft. |
|
3176 | # A list of state files kept by multistep operations like graft. | |
3176 | # Since graft cannot be aborted, it is considered 'clearable' by update. |
|
3177 | # Since graft cannot be aborted, it is considered 'clearable' by update. | |
3177 | # note: bisect is intentionally excluded |
|
3178 | # note: bisect is intentionally excluded | |
3178 | # (state file, clearable, allowcommit, error, hint) |
|
3179 | # (state file, clearable, allowcommit, error, hint) | |
3179 | unfinishedstates = [ |
|
3180 | unfinishedstates = [ | |
3180 | ('graftstate', True, False, _('graft in progress'), |
|
3181 | ('graftstate', True, False, _('graft in progress'), | |
3181 | _("use 'hg graft --continue' or 'hg graft --stop' to stop")), |
|
3182 | _("use 'hg graft --continue' or 'hg graft --stop' to stop")), | |
3182 | ('updatestate', True, False, _('last update was interrupted'), |
|
3183 | ('updatestate', True, False, _('last update was interrupted'), | |
3183 | _("use 'hg update' to get a consistent checkout")) |
|
3184 | _("use 'hg update' to get a consistent checkout")) | |
3184 | ] |
|
3185 | ] | |
3185 |
|
3186 | |||
3186 | def checkunfinished(repo, commit=False): |
|
3187 | def checkunfinished(repo, commit=False): | |
3187 | '''Look for an unfinished multistep operation, like graft, and abort |
|
3188 | '''Look for an unfinished multistep operation, like graft, and abort | |
3188 | if found. It's probably good to check this right before |
|
3189 | if found. It's probably good to check this right before | |
3189 | bailifchanged(). |
|
3190 | bailifchanged(). | |
3190 | ''' |
|
3191 | ''' | |
3191 | # Check for non-clearable states first, so things like rebase will take |
|
3192 | # Check for non-clearable states first, so things like rebase will take | |
3192 | # precedence over update. |
|
3193 | # precedence over update. | |
3193 | for f, clearable, allowcommit, msg, hint in unfinishedstates: |
|
3194 | for f, clearable, allowcommit, msg, hint in unfinishedstates: | |
3194 | if clearable or (commit and allowcommit): |
|
3195 | if clearable or (commit and allowcommit): | |
3195 | continue |
|
3196 | continue | |
3196 | if repo.vfs.exists(f): |
|
3197 | if repo.vfs.exists(f): | |
3197 | raise error.Abort(msg, hint=hint) |
|
3198 | raise error.Abort(msg, hint=hint) | |
3198 |
|
3199 | |||
3199 | for f, clearable, allowcommit, msg, hint in unfinishedstates: |
|
3200 | for f, clearable, allowcommit, msg, hint in unfinishedstates: | |
3200 | if not clearable or (commit and allowcommit): |
|
3201 | if not clearable or (commit and allowcommit): | |
3201 | continue |
|
3202 | continue | |
3202 | if repo.vfs.exists(f): |
|
3203 | if repo.vfs.exists(f): | |
3203 | raise error.Abort(msg, hint=hint) |
|
3204 | raise error.Abort(msg, hint=hint) | |
3204 |
|
3205 | |||
3205 | def clearunfinished(repo): |
|
3206 | def clearunfinished(repo): | |
3206 | '''Check for unfinished operations (as above), and clear the ones |
|
3207 | '''Check for unfinished operations (as above), and clear the ones | |
3207 | that are clearable. |
|
3208 | that are clearable. | |
3208 | ''' |
|
3209 | ''' | |
3209 | for f, clearable, allowcommit, msg, hint in unfinishedstates: |
|
3210 | for f, clearable, allowcommit, msg, hint in unfinishedstates: | |
3210 | if not clearable and repo.vfs.exists(f): |
|
3211 | if not clearable and repo.vfs.exists(f): | |
3211 | raise error.Abort(msg, hint=hint) |
|
3212 | raise error.Abort(msg, hint=hint) | |
3212 | for f, clearable, allowcommit, msg, hint in unfinishedstates: |
|
3213 | for f, clearable, allowcommit, msg, hint in unfinishedstates: | |
3213 | if clearable and repo.vfs.exists(f): |
|
3214 | if clearable and repo.vfs.exists(f): | |
3214 | util.unlink(repo.vfs.join(f)) |
|
3215 | util.unlink(repo.vfs.join(f)) | |
3215 |
|
3216 | |||
3216 | afterresolvedstates = [ |
|
3217 | afterresolvedstates = [ | |
3217 | ('graftstate', |
|
3218 | ('graftstate', | |
3218 | _('hg graft --continue')), |
|
3219 | _('hg graft --continue')), | |
3219 | ] |
|
3220 | ] | |
3220 |
|
3221 | |||
3221 | def howtocontinue(repo): |
|
3222 | def howtocontinue(repo): | |
3222 | '''Check for an unfinished operation and return the command to finish |
|
3223 | '''Check for an unfinished operation and return the command to finish | |
3223 | it. |
|
3224 | it. | |
3224 |
|
3225 | |||
3225 | afterresolvedstates tuples define a .hg/{file} and the corresponding |
|
3226 | afterresolvedstates tuples define a .hg/{file} and the corresponding | |
3226 | command needed to finish it. |
|
3227 | command needed to finish it. | |
3227 |
|
3228 | |||
3228 | Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is |
|
3229 | Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is | |
3229 | a boolean. |
|
3230 | a boolean. | |
3230 | ''' |
|
3231 | ''' | |
3231 | contmsg = _("continue: %s") |
|
3232 | contmsg = _("continue: %s") | |
3232 | for f, msg in afterresolvedstates: |
|
3233 | for f, msg in afterresolvedstates: | |
3233 | if repo.vfs.exists(f): |
|
3234 | if repo.vfs.exists(f): | |
3234 | return contmsg % msg, True |
|
3235 | return contmsg % msg, True | |
3235 | if repo[None].dirty(missing=True, merge=False, branch=False): |
|
3236 | if repo[None].dirty(missing=True, merge=False, branch=False): | |
3236 | return contmsg % _("hg commit"), False |
|
3237 | return contmsg % _("hg commit"), False | |
3237 | return None, None |
|
3238 | return None, None | |
3238 |
|
3239 | |||
3239 | def checkafterresolved(repo): |
|
3240 | def checkafterresolved(repo): | |
3240 | '''Inform the user about the next action after completing hg resolve |
|
3241 | '''Inform the user about the next action after completing hg resolve | |
3241 |
|
3242 | |||
3242 | If there's a matching afterresolvedstates, howtocontinue will yield |
|
3243 | If there's a matching afterresolvedstates, howtocontinue will yield | |
3243 | repo.ui.warn as the reporter. |
|
3244 | repo.ui.warn as the reporter. | |
3244 |
|
3245 | |||
3245 | Otherwise, it will yield repo.ui.note. |
|
3246 | Otherwise, it will yield repo.ui.note. | |
3246 | ''' |
|
3247 | ''' | |
3247 | msg, warning = howtocontinue(repo) |
|
3248 | msg, warning = howtocontinue(repo) | |
3248 | if msg is not None: |
|
3249 | if msg is not None: | |
3249 | if warning: |
|
3250 | if warning: | |
3250 | repo.ui.warn("%s\n" % msg) |
|
3251 | repo.ui.warn("%s\n" % msg) | |
3251 | else: |
|
3252 | else: | |
3252 | repo.ui.note("%s\n" % msg) |
|
3253 | repo.ui.note("%s\n" % msg) | |
3253 |
|
3254 | |||
3254 | def wrongtooltocontinue(repo, task): |
|
3255 | def wrongtooltocontinue(repo, task): | |
3255 | '''Raise an abort suggesting how to properly continue if there is an |
|
3256 | '''Raise an abort suggesting how to properly continue if there is an | |
3256 | active task. |
|
3257 | active task. | |
3257 |
|
3258 | |||
3258 | Uses howtocontinue() to find the active task. |
|
3259 | Uses howtocontinue() to find the active task. | |
3259 |
|
3260 | |||
3260 | If there's no task (repo.ui.note for 'hg commit'), it does not offer |
|
3261 | If there's no task (repo.ui.note for 'hg commit'), it does not offer | |
3261 | a hint. |
|
3262 | a hint. | |
3262 | ''' |
|
3263 | ''' | |
3263 | after = howtocontinue(repo) |
|
3264 | after = howtocontinue(repo) | |
3264 | hint = None |
|
3265 | hint = None | |
3265 | if after[1]: |
|
3266 | if after[1]: | |
3266 | hint = after[0] |
|
3267 | hint = after[0] | |
3267 | raise error.Abort(_('no %s in progress') % task, hint=hint) |
|
3268 | raise error.Abort(_('no %s in progress') % task, hint=hint) |
@@ -1,329 +1,332 | |||||
1 | $ hg init a |
|
1 | $ hg init a | |
2 | $ cd a |
|
2 | $ cd a | |
3 | $ echo a > a |
|
3 | $ echo a > a | |
4 | $ hg add -n |
|
4 | $ hg add -n | |
5 | adding a |
|
5 | adding a | |
6 | $ hg st |
|
6 | $ hg st | |
7 | ? a |
|
7 | ? a | |
8 | $ hg add |
|
8 | $ hg add | |
9 | adding a |
|
9 | adding a | |
10 | $ hg st |
|
10 | $ hg st | |
11 | A a |
|
11 | A a | |
12 | $ hg forget a |
|
12 | $ hg forget a | |
13 | $ hg add |
|
13 | $ hg add | |
14 | adding a |
|
14 | adding a | |
|
15 | $ hg forget a | |||
|
16 | $ hg add --color debug | |||
|
17 | [addremove.added ui.status|adding a] | |||
15 | $ hg st |
|
18 | $ hg st | |
16 | A a |
|
19 | A a | |
17 | $ mkdir dir |
|
20 | $ mkdir dir | |
18 | $ cd dir |
|
21 | $ cd dir | |
19 | $ hg add ../a |
|
22 | $ hg add ../a | |
20 | ../a already tracked! |
|
23 | ../a already tracked! | |
21 | $ cd .. |
|
24 | $ cd .. | |
22 |
|
25 | |||
23 | $ echo b > b |
|
26 | $ echo b > b | |
24 | $ hg add -n b |
|
27 | $ hg add -n b | |
25 | $ hg st |
|
28 | $ hg st | |
26 | A a |
|
29 | A a | |
27 | ? b |
|
30 | ? b | |
28 | $ hg add b |
|
31 | $ hg add b | |
29 | $ hg st |
|
32 | $ hg st | |
30 | A a |
|
33 | A a | |
31 | A b |
|
34 | A b | |
32 |
|
35 | |||
33 | should fail |
|
36 | should fail | |
34 |
|
37 | |||
35 | $ hg add b |
|
38 | $ hg add b | |
36 | b already tracked! |
|
39 | b already tracked! | |
37 | $ hg st |
|
40 | $ hg st | |
38 | A a |
|
41 | A a | |
39 | A b |
|
42 | A b | |
40 |
|
43 | |||
41 | #if no-windows |
|
44 | #if no-windows | |
42 | $ echo foo > con.xml |
|
45 | $ echo foo > con.xml | |
43 | $ hg --config ui.portablefilenames=jump add con.xml |
|
46 | $ hg --config ui.portablefilenames=jump add con.xml | |
44 | abort: ui.portablefilenames value is invalid ('jump') |
|
47 | abort: ui.portablefilenames value is invalid ('jump') | |
45 | [255] |
|
48 | [255] | |
46 | $ hg --config ui.portablefilenames=abort add con.xml |
|
49 | $ hg --config ui.portablefilenames=abort add con.xml | |
47 | abort: filename contains 'con', which is reserved on Windows: con.xml |
|
50 | abort: filename contains 'con', which is reserved on Windows: con.xml | |
48 | [255] |
|
51 | [255] | |
49 | $ hg st |
|
52 | $ hg st | |
50 | A a |
|
53 | A a | |
51 | A b |
|
54 | A b | |
52 | ? con.xml |
|
55 | ? con.xml | |
53 | $ hg add con.xml |
|
56 | $ hg add con.xml | |
54 | warning: filename contains 'con', which is reserved on Windows: con.xml |
|
57 | warning: filename contains 'con', which is reserved on Windows: con.xml | |
55 | $ hg st |
|
58 | $ hg st | |
56 | A a |
|
59 | A a | |
57 | A b |
|
60 | A b | |
58 | A con.xml |
|
61 | A con.xml | |
59 | $ hg forget con.xml |
|
62 | $ hg forget con.xml | |
60 | $ rm con.xml |
|
63 | $ rm con.xml | |
61 | #endif |
|
64 | #endif | |
62 |
|
65 | |||
63 | #if eol-in-paths |
|
66 | #if eol-in-paths | |
64 | $ echo bla > 'hello:world' |
|
67 | $ echo bla > 'hello:world' | |
65 | $ hg --config ui.portablefilenames=abort add |
|
68 | $ hg --config ui.portablefilenames=abort add | |
66 | adding hello:world |
|
69 | adding hello:world | |
67 | abort: filename contains ':', which is reserved on Windows: 'hello:world' |
|
70 | abort: filename contains ':', which is reserved on Windows: 'hello:world' | |
68 | [255] |
|
71 | [255] | |
69 | $ hg st |
|
72 | $ hg st | |
70 | A a |
|
73 | A a | |
71 | A b |
|
74 | A b | |
72 | ? hello:world |
|
75 | ? hello:world | |
73 | $ hg --config ui.portablefilenames=ignore add |
|
76 | $ hg --config ui.portablefilenames=ignore add | |
74 | adding hello:world |
|
77 | adding hello:world | |
75 | $ hg st |
|
78 | $ hg st | |
76 | A a |
|
79 | A a | |
77 | A b |
|
80 | A b | |
78 | A hello:world |
|
81 | A hello:world | |
79 | #endif |
|
82 | #endif | |
80 |
|
83 | |||
81 | $ hg ci -m 0 --traceback |
|
84 | $ hg ci -m 0 --traceback | |
82 |
|
85 | |||
83 | $ hg log -r "heads(. or wdir() & file('**'))" |
|
86 | $ hg log -r "heads(. or wdir() & file('**'))" | |
84 | changeset: 0:* (glob) |
|
87 | changeset: 0:* (glob) | |
85 | tag: tip |
|
88 | tag: tip | |
86 | user: test |
|
89 | user: test | |
87 | date: Thu Jan 01 00:00:00 1970 +0000 |
|
90 | date: Thu Jan 01 00:00:00 1970 +0000 | |
88 | summary: 0 |
|
91 | summary: 0 | |
89 |
|
92 | |||
90 | should fail |
|
93 | should fail | |
91 |
|
94 | |||
92 | $ hg add a |
|
95 | $ hg add a | |
93 | a already tracked! |
|
96 | a already tracked! | |
94 |
|
97 | |||
95 | $ echo aa > a |
|
98 | $ echo aa > a | |
96 | $ hg ci -m 1 |
|
99 | $ hg ci -m 1 | |
97 | $ hg up 0 |
|
100 | $ hg up 0 | |
98 | 1 files updated, 0 files merged, 0 files removed, 0 files unresolved |
|
101 | 1 files updated, 0 files merged, 0 files removed, 0 files unresolved | |
99 | $ echo aaa > a |
|
102 | $ echo aaa > a | |
100 | $ hg ci -m 2 |
|
103 | $ hg ci -m 2 | |
101 | created new head |
|
104 | created new head | |
102 |
|
105 | |||
103 | $ hg merge |
|
106 | $ hg merge | |
104 | merging a |
|
107 | merging a | |
105 | warning: conflicts while merging a! (edit, then use 'hg resolve --mark') |
|
108 | warning: conflicts while merging a! (edit, then use 'hg resolve --mark') | |
106 | 0 files updated, 0 files merged, 0 files removed, 1 files unresolved |
|
109 | 0 files updated, 0 files merged, 0 files removed, 1 files unresolved | |
107 | use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon |
|
110 | use 'hg resolve' to retry unresolved file merges or 'hg merge --abort' to abandon | |
108 | [1] |
|
111 | [1] | |
109 | $ hg st |
|
112 | $ hg st | |
110 | M a |
|
113 | M a | |
111 | ? a.orig |
|
114 | ? a.orig | |
112 |
|
115 | |||
113 | wdir doesn't cause a crash, and can be dynamically selected if dirty |
|
116 | wdir doesn't cause a crash, and can be dynamically selected if dirty | |
114 |
|
117 | |||
115 | $ hg log -r "heads(. or wdir() & file('**'))" |
|
118 | $ hg log -r "heads(. or wdir() & file('**'))" | |
116 | changeset: 2147483647:ffffffffffff |
|
119 | changeset: 2147483647:ffffffffffff | |
117 | parent: 2:* (glob) |
|
120 | parent: 2:* (glob) | |
118 | parent: 1:* (glob) |
|
121 | parent: 1:* (glob) | |
119 | user: test |
|
122 | user: test | |
120 | date: * (glob) |
|
123 | date: * (glob) | |
121 |
|
124 | |||
122 | should fail |
|
125 | should fail | |
123 |
|
126 | |||
124 | $ hg add a |
|
127 | $ hg add a | |
125 | a already tracked! |
|
128 | a already tracked! | |
126 | $ hg st |
|
129 | $ hg st | |
127 | M a |
|
130 | M a | |
128 | ? a.orig |
|
131 | ? a.orig | |
129 | $ hg resolve -m a |
|
132 | $ hg resolve -m a | |
130 | (no more unresolved files) |
|
133 | (no more unresolved files) | |
131 | $ hg ci -m merge |
|
134 | $ hg ci -m merge | |
132 |
|
135 | |||
133 | Issue683: peculiarity with hg revert of an removed then added file |
|
136 | Issue683: peculiarity with hg revert of an removed then added file | |
134 |
|
137 | |||
135 | $ hg forget a |
|
138 | $ hg forget a | |
136 | $ hg add a |
|
139 | $ hg add a | |
137 | $ hg st |
|
140 | $ hg st | |
138 | ? a.orig |
|
141 | ? a.orig | |
139 | $ hg rm a |
|
142 | $ hg rm a | |
140 | $ hg st |
|
143 | $ hg st | |
141 | R a |
|
144 | R a | |
142 | ? a.orig |
|
145 | ? a.orig | |
143 | $ echo a > a |
|
146 | $ echo a > a | |
144 | $ hg add a |
|
147 | $ hg add a | |
145 | $ hg st |
|
148 | $ hg st | |
146 | M a |
|
149 | M a | |
147 | ? a.orig |
|
150 | ? a.orig | |
148 |
|
151 | |||
149 | excluded file shouldn't be added even if it is explicitly specified |
|
152 | excluded file shouldn't be added even if it is explicitly specified | |
150 |
|
153 | |||
151 | $ hg add a.orig -X '*.orig' |
|
154 | $ hg add a.orig -X '*.orig' | |
152 | $ hg st |
|
155 | $ hg st | |
153 | M a |
|
156 | M a | |
154 | ? a.orig |
|
157 | ? a.orig | |
155 |
|
158 | |||
156 | Forgotten file can be added back (as either clean or modified) |
|
159 | Forgotten file can be added back (as either clean or modified) | |
157 |
|
160 | |||
158 | $ hg forget b |
|
161 | $ hg forget b | |
159 | $ hg add b |
|
162 | $ hg add b | |
160 | $ hg st -A b |
|
163 | $ hg st -A b | |
161 | C b |
|
164 | C b | |
162 | $ hg forget b |
|
165 | $ hg forget b | |
163 | $ echo modified > b |
|
166 | $ echo modified > b | |
164 | $ hg add b |
|
167 | $ hg add b | |
165 | $ hg st -A b |
|
168 | $ hg st -A b | |
166 | M b |
|
169 | M b | |
167 | $ hg revert -qC b |
|
170 | $ hg revert -qC b | |
168 |
|
171 | |||
169 | $ hg add c && echo "unexpected addition of missing file" |
|
172 | $ hg add c && echo "unexpected addition of missing file" | |
170 | c: * (glob) |
|
173 | c: * (glob) | |
171 | [1] |
|
174 | [1] | |
172 | $ echo c > c |
|
175 | $ echo c > c | |
173 | $ hg add d c && echo "unexpected addition of missing file" |
|
176 | $ hg add d c && echo "unexpected addition of missing file" | |
174 | d: * (glob) |
|
177 | d: * (glob) | |
175 | [1] |
|
178 | [1] | |
176 | $ hg st |
|
179 | $ hg st | |
177 | M a |
|
180 | M a | |
178 | A c |
|
181 | A c | |
179 | ? a.orig |
|
182 | ? a.orig | |
180 | $ hg up -C |
|
183 | $ hg up -C | |
181 | 1 files updated, 0 files merged, 0 files removed, 0 files unresolved |
|
184 | 1 files updated, 0 files merged, 0 files removed, 0 files unresolved | |
182 |
|
185 | |||
183 | forget and get should have the right order: added but missing dir should be |
|
186 | forget and get should have the right order: added but missing dir should be | |
184 | forgotten before file with same name is added |
|
187 | forgotten before file with same name is added | |
185 |
|
188 | |||
186 | $ echo file d > d |
|
189 | $ echo file d > d | |
187 | $ hg add d |
|
190 | $ hg add d | |
188 | $ hg ci -md |
|
191 | $ hg ci -md | |
189 | $ hg rm d |
|
192 | $ hg rm d | |
190 | $ mkdir d |
|
193 | $ mkdir d | |
191 | $ echo a > d/a |
|
194 | $ echo a > d/a | |
192 | $ hg add d/a |
|
195 | $ hg add d/a | |
193 | $ rm -r d |
|
196 | $ rm -r d | |
194 | $ hg up -C |
|
197 | $ hg up -C | |
195 | 1 files updated, 0 files merged, 0 files removed, 0 files unresolved |
|
198 | 1 files updated, 0 files merged, 0 files removed, 0 files unresolved | |
196 | $ cat d |
|
199 | $ cat d | |
197 | file d |
|
200 | file d | |
198 |
|
201 | |||
199 | Test that adding a directory doesn't require case matching (issue4578) |
|
202 | Test that adding a directory doesn't require case matching (issue4578) | |
200 | #if icasefs |
|
203 | #if icasefs | |
201 | $ mkdir -p CapsDir1/CapsDir |
|
204 | $ mkdir -p CapsDir1/CapsDir | |
202 | $ echo abc > CapsDir1/CapsDir/AbC.txt |
|
205 | $ echo abc > CapsDir1/CapsDir/AbC.txt | |
203 | $ mkdir CapsDir1/CapsDir/SubDir |
|
206 | $ mkdir CapsDir1/CapsDir/SubDir | |
204 | $ echo def > CapsDir1/CapsDir/SubDir/Def.txt |
|
207 | $ echo def > CapsDir1/CapsDir/SubDir/Def.txt | |
205 |
|
208 | |||
206 | $ hg add capsdir1/capsdir |
|
209 | $ hg add capsdir1/capsdir | |
207 | adding CapsDir1/CapsDir/AbC.txt |
|
210 | adding CapsDir1/CapsDir/AbC.txt | |
208 | adding CapsDir1/CapsDir/SubDir/Def.txt |
|
211 | adding CapsDir1/CapsDir/SubDir/Def.txt | |
209 |
|
212 | |||
210 | $ hg forget capsdir1/capsdir/abc.txt |
|
213 | $ hg forget capsdir1/capsdir/abc.txt | |
211 |
|
214 | |||
212 | $ hg forget capsdir1/capsdir |
|
215 | $ hg forget capsdir1/capsdir | |
213 | removing CapsDir1/CapsDir/SubDir/Def.txt |
|
216 | removing CapsDir1/CapsDir/SubDir/Def.txt | |
214 |
|
217 | |||
215 | $ hg add capsdir1 |
|
218 | $ hg add capsdir1 | |
216 | adding CapsDir1/CapsDir/AbC.txt |
|
219 | adding CapsDir1/CapsDir/AbC.txt | |
217 | adding CapsDir1/CapsDir/SubDir/Def.txt |
|
220 | adding CapsDir1/CapsDir/SubDir/Def.txt | |
218 |
|
221 | |||
219 | $ hg ci -m "AbCDef" capsdir1/capsdir |
|
222 | $ hg ci -m "AbCDef" capsdir1/capsdir | |
220 |
|
223 | |||
221 | $ hg status -A capsdir1/capsdir |
|
224 | $ hg status -A capsdir1/capsdir | |
222 | C CapsDir1/CapsDir/AbC.txt |
|
225 | C CapsDir1/CapsDir/AbC.txt | |
223 | C CapsDir1/CapsDir/SubDir/Def.txt |
|
226 | C CapsDir1/CapsDir/SubDir/Def.txt | |
224 |
|
227 | |||
225 | $ hg files capsdir1/capsdir |
|
228 | $ hg files capsdir1/capsdir | |
226 | CapsDir1/CapsDir/AbC.txt |
|
229 | CapsDir1/CapsDir/AbC.txt | |
227 | CapsDir1/CapsDir/SubDir/Def.txt |
|
230 | CapsDir1/CapsDir/SubDir/Def.txt | |
228 |
|
231 | |||
229 | $ echo xyz > CapsDir1/CapsDir/SubDir/Def.txt |
|
232 | $ echo xyz > CapsDir1/CapsDir/SubDir/Def.txt | |
230 | $ hg ci -m xyz capsdir1/capsdir/subdir/def.txt |
|
233 | $ hg ci -m xyz capsdir1/capsdir/subdir/def.txt | |
231 |
|
234 | |||
232 | $ hg revert -r '.^' capsdir1/capsdir |
|
235 | $ hg revert -r '.^' capsdir1/capsdir | |
233 | reverting CapsDir1/CapsDir/SubDir/Def.txt |
|
236 | reverting CapsDir1/CapsDir/SubDir/Def.txt | |
234 |
|
237 | |||
235 | The conditional tests above mean the hash on the diff line differs on Windows |
|
238 | The conditional tests above mean the hash on the diff line differs on Windows | |
236 | and OS X |
|
239 | and OS X | |
237 | $ hg diff capsdir1/capsdir |
|
240 | $ hg diff capsdir1/capsdir | |
238 | diff -r * CapsDir1/CapsDir/SubDir/Def.txt (glob) |
|
241 | diff -r * CapsDir1/CapsDir/SubDir/Def.txt (glob) | |
239 | --- a/CapsDir1/CapsDir/SubDir/Def.txt Thu Jan 01 00:00:00 1970 +0000 |
|
242 | --- a/CapsDir1/CapsDir/SubDir/Def.txt Thu Jan 01 00:00:00 1970 +0000 | |
240 | +++ b/CapsDir1/CapsDir/SubDir/Def.txt * (glob) |
|
243 | +++ b/CapsDir1/CapsDir/SubDir/Def.txt * (glob) | |
241 | @@ -1,1 +1,1 @@ |
|
244 | @@ -1,1 +1,1 @@ | |
242 | -xyz |
|
245 | -xyz | |
243 | +def |
|
246 | +def | |
244 |
|
247 | |||
245 | $ hg mv CapsDir1/CapsDir/abc.txt CapsDir1/CapsDir/ABC.txt |
|
248 | $ hg mv CapsDir1/CapsDir/abc.txt CapsDir1/CapsDir/ABC.txt | |
246 | $ hg ci -m "case changing rename" CapsDir1/CapsDir/AbC.txt CapsDir1/CapsDir/ABC.txt |
|
249 | $ hg ci -m "case changing rename" CapsDir1/CapsDir/AbC.txt CapsDir1/CapsDir/ABC.txt | |
247 |
|
250 | |||
248 | $ hg status -A capsdir1/capsdir |
|
251 | $ hg status -A capsdir1/capsdir | |
249 | M CapsDir1/CapsDir/SubDir/Def.txt |
|
252 | M CapsDir1/CapsDir/SubDir/Def.txt | |
250 | C CapsDir1/CapsDir/ABC.txt |
|
253 | C CapsDir1/CapsDir/ABC.txt | |
251 |
|
254 | |||
252 | $ hg remove -f 'glob:**.txt' -X capsdir1/capsdir |
|
255 | $ hg remove -f 'glob:**.txt' -X capsdir1/capsdir | |
253 | $ hg remove -f 'glob:**.txt' -I capsdir1/capsdir |
|
256 | $ hg remove -f 'glob:**.txt' -I capsdir1/capsdir | |
254 | removing CapsDir1/CapsDir/ABC.txt |
|
257 | removing CapsDir1/CapsDir/ABC.txt | |
255 | removing CapsDir1/CapsDir/SubDir/Def.txt |
|
258 | removing CapsDir1/CapsDir/SubDir/Def.txt | |
256 | #endif |
|
259 | #endif | |
257 |
|
260 | |||
258 | $ cd .. |
|
261 | $ cd .. | |
259 |
|
262 | |||
260 | test --dry-run mode in forget |
|
263 | test --dry-run mode in forget | |
261 |
|
264 | |||
262 | $ hg init testdir_forget |
|
265 | $ hg init testdir_forget | |
263 | $ cd testdir_forget |
|
266 | $ cd testdir_forget | |
264 | $ echo foo > foo |
|
267 | $ echo foo > foo | |
265 | $ hg add foo |
|
268 | $ hg add foo | |
266 | $ hg commit -m "foo" |
|
269 | $ hg commit -m "foo" | |
267 | $ hg forget foo --dry-run -v |
|
270 | $ hg forget foo --dry-run -v | |
268 | removing foo |
|
271 | removing foo | |
269 | $ hg diff |
|
272 | $ hg diff | |
270 | $ hg forget not_exist -n |
|
273 | $ hg forget not_exist -n | |
271 | not_exist: $ENOENT$ |
|
274 | not_exist: $ENOENT$ | |
272 | [1] |
|
275 | [1] | |
273 |
|
276 | |||
274 | $ cd .. |
|
277 | $ cd .. | |
275 |
|
278 | |||
276 | test --interactive mode in forget |
|
279 | test --interactive mode in forget | |
277 |
|
280 | |||
278 | $ hg init interactiveforget |
|
281 | $ hg init interactiveforget | |
279 | $ cd interactiveforget |
|
282 | $ cd interactiveforget | |
280 | $ echo foo > foo |
|
283 | $ echo foo > foo | |
281 | $ hg commit -qAm "foo" |
|
284 | $ hg commit -qAm "foo" | |
282 | $ echo bar > bar |
|
285 | $ echo bar > bar | |
283 | $ hg commit -qAm "bar" |
|
286 | $ hg commit -qAm "bar" | |
284 | $ hg forget foo --dry-run -i |
|
287 | $ hg forget foo --dry-run -i | |
285 | abort: cannot specify both --dry-run and --interactive |
|
288 | abort: cannot specify both --dry-run and --interactive | |
286 | [255] |
|
289 | [255] | |
287 |
|
290 | |||
288 | $ hg forget foo --config ui.interactive=True -i << EOF |
|
291 | $ hg forget foo --config ui.interactive=True -i << EOF | |
289 | > ? |
|
292 | > ? | |
290 | > n |
|
293 | > n | |
291 | > EOF |
|
294 | > EOF | |
292 | forget foo [Ynsa?] ? |
|
295 | forget foo [Ynsa?] ? | |
293 | y - yes, forget this file |
|
296 | y - yes, forget this file | |
294 | n - no, skip this file |
|
297 | n - no, skip this file | |
295 | s - skip remaining files |
|
298 | s - skip remaining files | |
296 | a - include all remaining files |
|
299 | a - include all remaining files | |
297 | ? - ? (display help) |
|
300 | ? - ? (display help) | |
298 | forget foo [Ynsa?] n |
|
301 | forget foo [Ynsa?] n | |
299 |
|
302 | |||
300 | $ hg forget foo bar --config ui.interactive=True -i << EOF |
|
303 | $ hg forget foo bar --config ui.interactive=True -i << EOF | |
301 | > y |
|
304 | > y | |
302 | > n |
|
305 | > n | |
303 | > EOF |
|
306 | > EOF | |
304 | forget bar [Ynsa?] y |
|
307 | forget bar [Ynsa?] y | |
305 | forget foo [Ynsa?] n |
|
308 | forget foo [Ynsa?] n | |
306 | removing bar |
|
309 | removing bar | |
307 | $ hg status |
|
310 | $ hg status | |
308 | R bar |
|
311 | R bar | |
309 | $ hg up -qC . |
|
312 | $ hg up -qC . | |
310 |
|
313 | |||
311 | $ hg forget foo bar --config ui.interactive=True -i << EOF |
|
314 | $ hg forget foo bar --config ui.interactive=True -i << EOF | |
312 | > s |
|
315 | > s | |
313 | > EOF |
|
316 | > EOF | |
314 | forget bar [Ynsa?] s |
|
317 | forget bar [Ynsa?] s | |
315 | $ hg st |
|
318 | $ hg st | |
316 | $ hg up -qC . |
|
319 | $ hg up -qC . | |
317 |
|
320 | |||
318 | $ hg forget foo bar --config ui.interactive=True -i << EOF |
|
321 | $ hg forget foo bar --config ui.interactive=True -i << EOF | |
319 | > a |
|
322 | > a | |
320 | > EOF |
|
323 | > EOF | |
321 | forget bar [Ynsa?] a |
|
324 | forget bar [Ynsa?] a | |
322 | removing bar |
|
325 | removing bar | |
323 | removing foo |
|
326 | removing foo | |
324 | $ hg status |
|
327 | $ hg status | |
325 | R bar |
|
328 | R bar | |
326 | R foo |
|
329 | R foo | |
327 | $ hg up -qC . |
|
330 | $ hg up -qC . | |
328 |
|
331 | |||
329 | $ cd .. |
|
332 | $ cd .. |
General Comments 0
You need to be logged in to leave comments.
Login now