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