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