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