##// END OF EJS Templates
forget: pass around uipathfn and use instead of m.rel() (API)...
Martin von Zweigbergk -
r41802:16a49c77 default
parent child Browse files
Show More
@@ -1,1516 +1,1516 b''
1 # Copyright 2009-2010 Gregory P. Ward
1 # Copyright 2009-2010 Gregory P. Ward
2 # Copyright 2009-2010 Intelerad Medical Systems Incorporated
2 # Copyright 2009-2010 Intelerad Medical Systems Incorporated
3 # Copyright 2010-2011 Fog Creek Software
3 # Copyright 2010-2011 Fog Creek Software
4 # Copyright 2010-2011 Unity Technologies
4 # Copyright 2010-2011 Unity Technologies
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 '''Overridden Mercurial commands and functions for the largefiles extension'''
9 '''Overridden Mercurial commands and functions for the largefiles extension'''
10 from __future__ import absolute_import
10 from __future__ import absolute_import
11
11
12 import copy
12 import copy
13 import os
13 import os
14
14
15 from mercurial.i18n import _
15 from mercurial.i18n import _
16
16
17 from mercurial.hgweb import (
17 from mercurial.hgweb import (
18 webcommands,
18 webcommands,
19 )
19 )
20
20
21 from mercurial import (
21 from mercurial import (
22 archival,
22 archival,
23 cmdutil,
23 cmdutil,
24 copies as copiesmod,
24 copies as copiesmod,
25 error,
25 error,
26 exchange,
26 exchange,
27 extensions,
27 extensions,
28 exthelper,
28 exthelper,
29 filemerge,
29 filemerge,
30 hg,
30 hg,
31 logcmdutil,
31 logcmdutil,
32 match as matchmod,
32 match as matchmod,
33 merge,
33 merge,
34 pathutil,
34 pathutil,
35 pycompat,
35 pycompat,
36 scmutil,
36 scmutil,
37 smartset,
37 smartset,
38 subrepo,
38 subrepo,
39 upgrade,
39 upgrade,
40 url as urlmod,
40 url as urlmod,
41 util,
41 util,
42 )
42 )
43
43
44 from . import (
44 from . import (
45 lfcommands,
45 lfcommands,
46 lfutil,
46 lfutil,
47 storefactory,
47 storefactory,
48 )
48 )
49
49
50 eh = exthelper.exthelper()
50 eh = exthelper.exthelper()
51
51
52 # -- Utility functions: commonly/repeatedly needed functionality ---------------
52 # -- Utility functions: commonly/repeatedly needed functionality ---------------
53
53
54 def composelargefilematcher(match, manifest):
54 def composelargefilematcher(match, manifest):
55 '''create a matcher that matches only the largefiles in the original
55 '''create a matcher that matches only the largefiles in the original
56 matcher'''
56 matcher'''
57 m = copy.copy(match)
57 m = copy.copy(match)
58 lfile = lambda f: lfutil.standin(f) in manifest
58 lfile = lambda f: lfutil.standin(f) in manifest
59 m._files = [lf for lf in m._files if lfile(lf)]
59 m._files = [lf for lf in m._files if lfile(lf)]
60 m._fileset = set(m._files)
60 m._fileset = set(m._files)
61 m.always = lambda: False
61 m.always = lambda: False
62 origmatchfn = m.matchfn
62 origmatchfn = m.matchfn
63 m.matchfn = lambda f: lfile(f) and origmatchfn(f)
63 m.matchfn = lambda f: lfile(f) and origmatchfn(f)
64 return m
64 return m
65
65
66 def composenormalfilematcher(match, manifest, exclude=None):
66 def composenormalfilematcher(match, manifest, exclude=None):
67 excluded = set()
67 excluded = set()
68 if exclude is not None:
68 if exclude is not None:
69 excluded.update(exclude)
69 excluded.update(exclude)
70
70
71 m = copy.copy(match)
71 m = copy.copy(match)
72 notlfile = lambda f: not (lfutil.isstandin(f) or lfutil.standin(f) in
72 notlfile = lambda f: not (lfutil.isstandin(f) or lfutil.standin(f) in
73 manifest or f in excluded)
73 manifest or f in excluded)
74 m._files = [lf for lf in m._files if notlfile(lf)]
74 m._files = [lf for lf in m._files if notlfile(lf)]
75 m._fileset = set(m._files)
75 m._fileset = set(m._files)
76 m.always = lambda: False
76 m.always = lambda: False
77 origmatchfn = m.matchfn
77 origmatchfn = m.matchfn
78 m.matchfn = lambda f: notlfile(f) and origmatchfn(f)
78 m.matchfn = lambda f: notlfile(f) and origmatchfn(f)
79 return m
79 return m
80
80
81 def addlargefiles(ui, repo, isaddremove, matcher, **opts):
81 def addlargefiles(ui, repo, isaddremove, matcher, **opts):
82 large = opts.get(r'large')
82 large = opts.get(r'large')
83 lfsize = lfutil.getminsize(
83 lfsize = lfutil.getminsize(
84 ui, lfutil.islfilesrepo(repo), opts.get(r'lfsize'))
84 ui, lfutil.islfilesrepo(repo), opts.get(r'lfsize'))
85
85
86 lfmatcher = None
86 lfmatcher = None
87 if lfutil.islfilesrepo(repo):
87 if lfutil.islfilesrepo(repo):
88 lfpats = ui.configlist(lfutil.longname, 'patterns')
88 lfpats = ui.configlist(lfutil.longname, 'patterns')
89 if lfpats:
89 if lfpats:
90 lfmatcher = matchmod.match(repo.root, '', list(lfpats))
90 lfmatcher = matchmod.match(repo.root, '', list(lfpats))
91
91
92 lfnames = []
92 lfnames = []
93 m = matcher
93 m = matcher
94
94
95 wctx = repo[None]
95 wctx = repo[None]
96 for f in wctx.walk(matchmod.badmatch(m, lambda x, y: None)):
96 for f in wctx.walk(matchmod.badmatch(m, lambda x, y: None)):
97 exact = m.exact(f)
97 exact = m.exact(f)
98 lfile = lfutil.standin(f) in wctx
98 lfile = lfutil.standin(f) in wctx
99 nfile = f in wctx
99 nfile = f in wctx
100 exists = lfile or nfile
100 exists = lfile or nfile
101
101
102 # addremove in core gets fancy with the name, add doesn't
102 # addremove in core gets fancy with the name, add doesn't
103 if isaddremove:
103 if isaddremove:
104 name = m.uipath(f)
104 name = m.uipath(f)
105 else:
105 else:
106 name = m.rel(f)
106 name = m.rel(f)
107
107
108 # Don't warn the user when they attempt to add a normal tracked file.
108 # Don't warn the user when they attempt to add a normal tracked file.
109 # The normal add code will do that for us.
109 # The normal add code will do that for us.
110 if exact and exists:
110 if exact and exists:
111 if lfile:
111 if lfile:
112 ui.warn(_('%s already a largefile\n') % name)
112 ui.warn(_('%s already a largefile\n') % name)
113 continue
113 continue
114
114
115 if (exact or not exists) and not lfutil.isstandin(f):
115 if (exact or not exists) and not lfutil.isstandin(f):
116 # In case the file was removed previously, but not committed
116 # In case the file was removed previously, but not committed
117 # (issue3507)
117 # (issue3507)
118 if not repo.wvfs.exists(f):
118 if not repo.wvfs.exists(f):
119 continue
119 continue
120
120
121 abovemin = (lfsize and
121 abovemin = (lfsize and
122 repo.wvfs.lstat(f).st_size >= lfsize * 1024 * 1024)
122 repo.wvfs.lstat(f).st_size >= lfsize * 1024 * 1024)
123 if large or abovemin or (lfmatcher and lfmatcher(f)):
123 if large or abovemin or (lfmatcher and lfmatcher(f)):
124 lfnames.append(f)
124 lfnames.append(f)
125 if ui.verbose or not exact:
125 if ui.verbose or not exact:
126 ui.status(_('adding %s as a largefile\n') % name)
126 ui.status(_('adding %s as a largefile\n') % name)
127
127
128 bad = []
128 bad = []
129
129
130 # Need to lock, otherwise there could be a race condition between
130 # Need to lock, otherwise there could be a race condition between
131 # when standins are created and added to the repo.
131 # when standins are created and added to the repo.
132 with repo.wlock():
132 with repo.wlock():
133 if not opts.get(r'dry_run'):
133 if not opts.get(r'dry_run'):
134 standins = []
134 standins = []
135 lfdirstate = lfutil.openlfdirstate(ui, repo)
135 lfdirstate = lfutil.openlfdirstate(ui, repo)
136 for f in lfnames:
136 for f in lfnames:
137 standinname = lfutil.standin(f)
137 standinname = lfutil.standin(f)
138 lfutil.writestandin(repo, standinname, hash='',
138 lfutil.writestandin(repo, standinname, hash='',
139 executable=lfutil.getexecutable(repo.wjoin(f)))
139 executable=lfutil.getexecutable(repo.wjoin(f)))
140 standins.append(standinname)
140 standins.append(standinname)
141 if lfdirstate[f] == 'r':
141 if lfdirstate[f] == 'r':
142 lfdirstate.normallookup(f)
142 lfdirstate.normallookup(f)
143 else:
143 else:
144 lfdirstate.add(f)
144 lfdirstate.add(f)
145 lfdirstate.write()
145 lfdirstate.write()
146 bad += [lfutil.splitstandin(f)
146 bad += [lfutil.splitstandin(f)
147 for f in repo[None].add(standins)
147 for f in repo[None].add(standins)
148 if f in m.files()]
148 if f in m.files()]
149
149
150 added = [f for f in lfnames if f not in bad]
150 added = [f for f in lfnames if f not in bad]
151 return added, bad
151 return added, bad
152
152
153 def removelargefiles(ui, repo, isaddremove, matcher, dryrun, **opts):
153 def removelargefiles(ui, repo, isaddremove, matcher, dryrun, **opts):
154 after = opts.get(r'after')
154 after = opts.get(r'after')
155 m = composelargefilematcher(matcher, repo[None].manifest())
155 m = composelargefilematcher(matcher, repo[None].manifest())
156 try:
156 try:
157 repo.lfstatus = True
157 repo.lfstatus = True
158 s = repo.status(match=m, clean=not isaddremove)
158 s = repo.status(match=m, clean=not isaddremove)
159 finally:
159 finally:
160 repo.lfstatus = False
160 repo.lfstatus = False
161 manifest = repo[None].manifest()
161 manifest = repo[None].manifest()
162 modified, added, deleted, clean = [[f for f in list
162 modified, added, deleted, clean = [[f for f in list
163 if lfutil.standin(f) in manifest]
163 if lfutil.standin(f) in manifest]
164 for list in (s.modified, s.added,
164 for list in (s.modified, s.added,
165 s.deleted, s.clean)]
165 s.deleted, s.clean)]
166
166
167 def warn(files, msg):
167 def warn(files, msg):
168 for f in files:
168 for f in files:
169 ui.warn(msg % m.rel(f))
169 ui.warn(msg % m.rel(f))
170 return int(len(files) > 0)
170 return int(len(files) > 0)
171
171
172 if after:
172 if after:
173 remove = deleted
173 remove = deleted
174 result = warn(modified + added + clean,
174 result = warn(modified + added + clean,
175 _('not removing %s: file still exists\n'))
175 _('not removing %s: file still exists\n'))
176 else:
176 else:
177 remove = deleted + clean
177 remove = deleted + clean
178 result = warn(modified, _('not removing %s: file is modified (use -f'
178 result = warn(modified, _('not removing %s: file is modified (use -f'
179 ' to force removal)\n'))
179 ' to force removal)\n'))
180 result = warn(added, _('not removing %s: file has been marked for add'
180 result = warn(added, _('not removing %s: file has been marked for add'
181 ' (use forget to undo)\n')) or result
181 ' (use forget to undo)\n')) or result
182
182
183 # Need to lock because standin files are deleted then removed from the
183 # Need to lock because standin files are deleted then removed from the
184 # repository and we could race in-between.
184 # repository and we could race in-between.
185 with repo.wlock():
185 with repo.wlock():
186 lfdirstate = lfutil.openlfdirstate(ui, repo)
186 lfdirstate = lfutil.openlfdirstate(ui, repo)
187 for f in sorted(remove):
187 for f in sorted(remove):
188 if ui.verbose or not m.exact(f):
188 if ui.verbose or not m.exact(f):
189 # addremove in core gets fancy with the name, remove doesn't
189 # addremove in core gets fancy with the name, remove doesn't
190 if isaddremove:
190 if isaddremove:
191 name = m.uipath(f)
191 name = m.uipath(f)
192 else:
192 else:
193 name = m.rel(f)
193 name = m.rel(f)
194 ui.status(_('removing %s\n') % name)
194 ui.status(_('removing %s\n') % name)
195
195
196 if not dryrun:
196 if not dryrun:
197 if not after:
197 if not after:
198 repo.wvfs.unlinkpath(f, ignoremissing=True)
198 repo.wvfs.unlinkpath(f, ignoremissing=True)
199
199
200 if dryrun:
200 if dryrun:
201 return result
201 return result
202
202
203 remove = [lfutil.standin(f) for f in remove]
203 remove = [lfutil.standin(f) for f in remove]
204 # If this is being called by addremove, let the original addremove
204 # If this is being called by addremove, let the original addremove
205 # function handle this.
205 # function handle this.
206 if not isaddremove:
206 if not isaddremove:
207 for f in remove:
207 for f in remove:
208 repo.wvfs.unlinkpath(f, ignoremissing=True)
208 repo.wvfs.unlinkpath(f, ignoremissing=True)
209 repo[None].forget(remove)
209 repo[None].forget(remove)
210
210
211 for f in remove:
211 for f in remove:
212 lfutil.synclfdirstate(repo, lfdirstate, lfutil.splitstandin(f),
212 lfutil.synclfdirstate(repo, lfdirstate, lfutil.splitstandin(f),
213 False)
213 False)
214
214
215 lfdirstate.write()
215 lfdirstate.write()
216
216
217 return result
217 return result
218
218
219 # For overriding mercurial.hgweb.webcommands so that largefiles will
219 # For overriding mercurial.hgweb.webcommands so that largefiles will
220 # appear at their right place in the manifests.
220 # appear at their right place in the manifests.
221 @eh.wrapfunction(webcommands, 'decodepath')
221 @eh.wrapfunction(webcommands, 'decodepath')
222 def decodepath(orig, path):
222 def decodepath(orig, path):
223 return lfutil.splitstandin(path) or path
223 return lfutil.splitstandin(path) or path
224
224
225 # -- Wrappers: modify existing commands --------------------------------
225 # -- Wrappers: modify existing commands --------------------------------
226
226
227 @eh.wrapcommand('add',
227 @eh.wrapcommand('add',
228 opts=[('', 'large', None, _('add as largefile')),
228 opts=[('', 'large', None, _('add as largefile')),
229 ('', 'normal', None, _('add as normal file')),
229 ('', 'normal', None, _('add as normal file')),
230 ('', 'lfsize', '', _('add all files above this size (in megabytes) '
230 ('', 'lfsize', '', _('add all files above this size (in megabytes) '
231 'as largefiles (default: 10)'))])
231 'as largefiles (default: 10)'))])
232 def overrideadd(orig, ui, repo, *pats, **opts):
232 def overrideadd(orig, ui, repo, *pats, **opts):
233 if opts.get(r'normal') and opts.get(r'large'):
233 if opts.get(r'normal') and opts.get(r'large'):
234 raise error.Abort(_('--normal cannot be used with --large'))
234 raise error.Abort(_('--normal cannot be used with --large'))
235 return orig(ui, repo, *pats, **opts)
235 return orig(ui, repo, *pats, **opts)
236
236
237 @eh.wrapfunction(cmdutil, 'add')
237 @eh.wrapfunction(cmdutil, 'add')
238 def cmdutiladd(orig, ui, repo, matcher, prefix, uipathfn, explicitonly, **opts):
238 def cmdutiladd(orig, ui, repo, matcher, prefix, uipathfn, explicitonly, **opts):
239 # The --normal flag short circuits this override
239 # The --normal flag short circuits this override
240 if opts.get(r'normal'):
240 if opts.get(r'normal'):
241 return orig(ui, repo, matcher, prefix, uipathfn, explicitonly, **opts)
241 return orig(ui, repo, matcher, prefix, uipathfn, explicitonly, **opts)
242
242
243 ladded, lbad = addlargefiles(ui, repo, False, matcher, **opts)
243 ladded, lbad = addlargefiles(ui, repo, False, matcher, **opts)
244 normalmatcher = composenormalfilematcher(matcher, repo[None].manifest(),
244 normalmatcher = composenormalfilematcher(matcher, repo[None].manifest(),
245 ladded)
245 ladded)
246 bad = orig(ui, repo, normalmatcher, prefix, uipathfn, explicitonly, **opts)
246 bad = orig(ui, repo, normalmatcher, prefix, uipathfn, explicitonly, **opts)
247
247
248 bad.extend(f for f in lbad)
248 bad.extend(f for f in lbad)
249 return bad
249 return bad
250
250
251 @eh.wrapfunction(cmdutil, 'remove')
251 @eh.wrapfunction(cmdutil, 'remove')
252 def cmdutilremove(orig, ui, repo, matcher, prefix, uipathfn, after, force,
252 def cmdutilremove(orig, ui, repo, matcher, prefix, uipathfn, after, force,
253 subrepos, dryrun):
253 subrepos, dryrun):
254 normalmatcher = composenormalfilematcher(matcher, repo[None].manifest())
254 normalmatcher = composenormalfilematcher(matcher, repo[None].manifest())
255 result = orig(ui, repo, normalmatcher, prefix, uipathfn, after, force,
255 result = orig(ui, repo, normalmatcher, prefix, uipathfn, after, force,
256 subrepos, dryrun)
256 subrepos, dryrun)
257 return removelargefiles(ui, repo, False, matcher, dryrun, after=after,
257 return removelargefiles(ui, repo, False, matcher, dryrun, after=after,
258 force=force) or result
258 force=force) or result
259
259
260 @eh.wrapfunction(subrepo.hgsubrepo, 'status')
260 @eh.wrapfunction(subrepo.hgsubrepo, 'status')
261 def overridestatusfn(orig, repo, rev2, **opts):
261 def overridestatusfn(orig, repo, rev2, **opts):
262 try:
262 try:
263 repo._repo.lfstatus = True
263 repo._repo.lfstatus = True
264 return orig(repo, rev2, **opts)
264 return orig(repo, rev2, **opts)
265 finally:
265 finally:
266 repo._repo.lfstatus = False
266 repo._repo.lfstatus = False
267
267
268 @eh.wrapcommand('status')
268 @eh.wrapcommand('status')
269 def overridestatus(orig, ui, repo, *pats, **opts):
269 def overridestatus(orig, ui, repo, *pats, **opts):
270 try:
270 try:
271 repo.lfstatus = True
271 repo.lfstatus = True
272 return orig(ui, repo, *pats, **opts)
272 return orig(ui, repo, *pats, **opts)
273 finally:
273 finally:
274 repo.lfstatus = False
274 repo.lfstatus = False
275
275
276 @eh.wrapfunction(subrepo.hgsubrepo, 'dirty')
276 @eh.wrapfunction(subrepo.hgsubrepo, 'dirty')
277 def overridedirty(orig, repo, ignoreupdate=False, missing=False):
277 def overridedirty(orig, repo, ignoreupdate=False, missing=False):
278 try:
278 try:
279 repo._repo.lfstatus = True
279 repo._repo.lfstatus = True
280 return orig(repo, ignoreupdate=ignoreupdate, missing=missing)
280 return orig(repo, ignoreupdate=ignoreupdate, missing=missing)
281 finally:
281 finally:
282 repo._repo.lfstatus = False
282 repo._repo.lfstatus = False
283
283
284 @eh.wrapcommand('log')
284 @eh.wrapcommand('log')
285 def overridelog(orig, ui, repo, *pats, **opts):
285 def overridelog(orig, ui, repo, *pats, **opts):
286 def overridematchandpats(orig, ctx, pats=(), opts=None, globbed=False,
286 def overridematchandpats(orig, ctx, pats=(), opts=None, globbed=False,
287 default='relpath', badfn=None):
287 default='relpath', badfn=None):
288 """Matcher that merges root directory with .hglf, suitable for log.
288 """Matcher that merges root directory with .hglf, suitable for log.
289 It is still possible to match .hglf directly.
289 It is still possible to match .hglf directly.
290 For any listed files run log on the standin too.
290 For any listed files run log on the standin too.
291 matchfn tries both the given filename and with .hglf stripped.
291 matchfn tries both the given filename and with .hglf stripped.
292 """
292 """
293 if opts is None:
293 if opts is None:
294 opts = {}
294 opts = {}
295 matchandpats = orig(ctx, pats, opts, globbed, default, badfn=badfn)
295 matchandpats = orig(ctx, pats, opts, globbed, default, badfn=badfn)
296 m, p = copy.copy(matchandpats)
296 m, p = copy.copy(matchandpats)
297
297
298 if m.always():
298 if m.always():
299 # We want to match everything anyway, so there's no benefit trying
299 # We want to match everything anyway, so there's no benefit trying
300 # to add standins.
300 # to add standins.
301 return matchandpats
301 return matchandpats
302
302
303 pats = set(p)
303 pats = set(p)
304
304
305 def fixpats(pat, tostandin=lfutil.standin):
305 def fixpats(pat, tostandin=lfutil.standin):
306 if pat.startswith('set:'):
306 if pat.startswith('set:'):
307 return pat
307 return pat
308
308
309 kindpat = matchmod._patsplit(pat, None)
309 kindpat = matchmod._patsplit(pat, None)
310
310
311 if kindpat[0] is not None:
311 if kindpat[0] is not None:
312 return kindpat[0] + ':' + tostandin(kindpat[1])
312 return kindpat[0] + ':' + tostandin(kindpat[1])
313 return tostandin(kindpat[1])
313 return tostandin(kindpat[1])
314
314
315 if m._cwd:
315 if m._cwd:
316 hglf = lfutil.shortname
316 hglf = lfutil.shortname
317 back = util.pconvert(m.rel(hglf)[:-len(hglf)])
317 back = util.pconvert(m.rel(hglf)[:-len(hglf)])
318
318
319 def tostandin(f):
319 def tostandin(f):
320 # The file may already be a standin, so truncate the back
320 # The file may already be a standin, so truncate the back
321 # prefix and test before mangling it. This avoids turning
321 # prefix and test before mangling it. This avoids turning
322 # 'glob:../.hglf/foo*' into 'glob:../.hglf/../.hglf/foo*'.
322 # 'glob:../.hglf/foo*' into 'glob:../.hglf/../.hglf/foo*'.
323 if f.startswith(back) and lfutil.splitstandin(f[len(back):]):
323 if f.startswith(back) and lfutil.splitstandin(f[len(back):]):
324 return f
324 return f
325
325
326 # An absolute path is from outside the repo, so truncate the
326 # An absolute path is from outside the repo, so truncate the
327 # path to the root before building the standin. Otherwise cwd
327 # path to the root before building the standin. Otherwise cwd
328 # is somewhere in the repo, relative to root, and needs to be
328 # is somewhere in the repo, relative to root, and needs to be
329 # prepended before building the standin.
329 # prepended before building the standin.
330 if os.path.isabs(m._cwd):
330 if os.path.isabs(m._cwd):
331 f = f[len(back):]
331 f = f[len(back):]
332 else:
332 else:
333 f = m._cwd + '/' + f
333 f = m._cwd + '/' + f
334 return back + lfutil.standin(f)
334 return back + lfutil.standin(f)
335 else:
335 else:
336 def tostandin(f):
336 def tostandin(f):
337 if lfutil.isstandin(f):
337 if lfutil.isstandin(f):
338 return f
338 return f
339 return lfutil.standin(f)
339 return lfutil.standin(f)
340 pats.update(fixpats(f, tostandin) for f in p)
340 pats.update(fixpats(f, tostandin) for f in p)
341
341
342 for i in range(0, len(m._files)):
342 for i in range(0, len(m._files)):
343 # Don't add '.hglf' to m.files, since that is already covered by '.'
343 # Don't add '.hglf' to m.files, since that is already covered by '.'
344 if m._files[i] == '.':
344 if m._files[i] == '.':
345 continue
345 continue
346 standin = lfutil.standin(m._files[i])
346 standin = lfutil.standin(m._files[i])
347 # If the "standin" is a directory, append instead of replace to
347 # If the "standin" is a directory, append instead of replace to
348 # support naming a directory on the command line with only
348 # support naming a directory on the command line with only
349 # largefiles. The original directory is kept to support normal
349 # largefiles. The original directory is kept to support normal
350 # files.
350 # files.
351 if standin in ctx:
351 if standin in ctx:
352 m._files[i] = standin
352 m._files[i] = standin
353 elif m._files[i] not in ctx and repo.wvfs.isdir(standin):
353 elif m._files[i] not in ctx and repo.wvfs.isdir(standin):
354 m._files.append(standin)
354 m._files.append(standin)
355
355
356 m._fileset = set(m._files)
356 m._fileset = set(m._files)
357 m.always = lambda: False
357 m.always = lambda: False
358 origmatchfn = m.matchfn
358 origmatchfn = m.matchfn
359 def lfmatchfn(f):
359 def lfmatchfn(f):
360 lf = lfutil.splitstandin(f)
360 lf = lfutil.splitstandin(f)
361 if lf is not None and origmatchfn(lf):
361 if lf is not None and origmatchfn(lf):
362 return True
362 return True
363 r = origmatchfn(f)
363 r = origmatchfn(f)
364 return r
364 return r
365 m.matchfn = lfmatchfn
365 m.matchfn = lfmatchfn
366
366
367 ui.debug('updated patterns: %s\n' % ', '.join(sorted(pats)))
367 ui.debug('updated patterns: %s\n' % ', '.join(sorted(pats)))
368 return m, pats
368 return m, pats
369
369
370 # For hg log --patch, the match object is used in two different senses:
370 # For hg log --patch, the match object is used in two different senses:
371 # (1) to determine what revisions should be printed out, and
371 # (1) to determine what revisions should be printed out, and
372 # (2) to determine what files to print out diffs for.
372 # (2) to determine what files to print out diffs for.
373 # The magic matchandpats override should be used for case (1) but not for
373 # The magic matchandpats override should be used for case (1) but not for
374 # case (2).
374 # case (2).
375 oldmatchandpats = scmutil.matchandpats
375 oldmatchandpats = scmutil.matchandpats
376 def overridemakefilematcher(orig, repo, pats, opts, badfn=None):
376 def overridemakefilematcher(orig, repo, pats, opts, badfn=None):
377 wctx = repo[None]
377 wctx = repo[None]
378 match, pats = oldmatchandpats(wctx, pats, opts, badfn=badfn)
378 match, pats = oldmatchandpats(wctx, pats, opts, badfn=badfn)
379 return lambda ctx: match
379 return lambda ctx: match
380
380
381 wrappedmatchandpats = extensions.wrappedfunction(scmutil, 'matchandpats',
381 wrappedmatchandpats = extensions.wrappedfunction(scmutil, 'matchandpats',
382 overridematchandpats)
382 overridematchandpats)
383 wrappedmakefilematcher = extensions.wrappedfunction(
383 wrappedmakefilematcher = extensions.wrappedfunction(
384 logcmdutil, '_makenofollowfilematcher', overridemakefilematcher)
384 logcmdutil, '_makenofollowfilematcher', overridemakefilematcher)
385 with wrappedmatchandpats, wrappedmakefilematcher:
385 with wrappedmatchandpats, wrappedmakefilematcher:
386 return orig(ui, repo, *pats, **opts)
386 return orig(ui, repo, *pats, **opts)
387
387
388 @eh.wrapcommand('verify',
388 @eh.wrapcommand('verify',
389 opts=[('', 'large', None,
389 opts=[('', 'large', None,
390 _('verify that all largefiles in current revision exists')),
390 _('verify that all largefiles in current revision exists')),
391 ('', 'lfa', None,
391 ('', 'lfa', None,
392 _('verify largefiles in all revisions, not just current')),
392 _('verify largefiles in all revisions, not just current')),
393 ('', 'lfc', None,
393 ('', 'lfc', None,
394 _('verify local largefile contents, not just existence'))])
394 _('verify local largefile contents, not just existence'))])
395 def overrideverify(orig, ui, repo, *pats, **opts):
395 def overrideverify(orig, ui, repo, *pats, **opts):
396 large = opts.pop(r'large', False)
396 large = opts.pop(r'large', False)
397 all = opts.pop(r'lfa', False)
397 all = opts.pop(r'lfa', False)
398 contents = opts.pop(r'lfc', False)
398 contents = opts.pop(r'lfc', False)
399
399
400 result = orig(ui, repo, *pats, **opts)
400 result = orig(ui, repo, *pats, **opts)
401 if large or all or contents:
401 if large or all or contents:
402 result = result or lfcommands.verifylfiles(ui, repo, all, contents)
402 result = result or lfcommands.verifylfiles(ui, repo, all, contents)
403 return result
403 return result
404
404
405 @eh.wrapcommand('debugstate',
405 @eh.wrapcommand('debugstate',
406 opts=[('', 'large', None, _('display largefiles dirstate'))])
406 opts=[('', 'large', None, _('display largefiles dirstate'))])
407 def overridedebugstate(orig, ui, repo, *pats, **opts):
407 def overridedebugstate(orig, ui, repo, *pats, **opts):
408 large = opts.pop(r'large', False)
408 large = opts.pop(r'large', False)
409 if large:
409 if large:
410 class fakerepo(object):
410 class fakerepo(object):
411 dirstate = lfutil.openlfdirstate(ui, repo)
411 dirstate = lfutil.openlfdirstate(ui, repo)
412 orig(ui, fakerepo, *pats, **opts)
412 orig(ui, fakerepo, *pats, **opts)
413 else:
413 else:
414 orig(ui, repo, *pats, **opts)
414 orig(ui, repo, *pats, **opts)
415
415
416 # Before starting the manifest merge, merge.updates will call
416 # Before starting the manifest merge, merge.updates will call
417 # _checkunknownfile to check if there are any files in the merged-in
417 # _checkunknownfile to check if there are any files in the merged-in
418 # changeset that collide with unknown files in the working copy.
418 # changeset that collide with unknown files in the working copy.
419 #
419 #
420 # The largefiles are seen as unknown, so this prevents us from merging
420 # The largefiles are seen as unknown, so this prevents us from merging
421 # in a file 'foo' if we already have a largefile with the same name.
421 # in a file 'foo' if we already have a largefile with the same name.
422 #
422 #
423 # The overridden function filters the unknown files by removing any
423 # The overridden function filters the unknown files by removing any
424 # largefiles. This makes the merge proceed and we can then handle this
424 # largefiles. This makes the merge proceed and we can then handle this
425 # case further in the overridden calculateupdates function below.
425 # case further in the overridden calculateupdates function below.
426 @eh.wrapfunction(merge, '_checkunknownfile')
426 @eh.wrapfunction(merge, '_checkunknownfile')
427 def overridecheckunknownfile(origfn, repo, wctx, mctx, f, f2=None):
427 def overridecheckunknownfile(origfn, repo, wctx, mctx, f, f2=None):
428 if lfutil.standin(repo.dirstate.normalize(f)) in wctx:
428 if lfutil.standin(repo.dirstate.normalize(f)) in wctx:
429 return False
429 return False
430 return origfn(repo, wctx, mctx, f, f2)
430 return origfn(repo, wctx, mctx, f, f2)
431
431
432 # The manifest merge handles conflicts on the manifest level. We want
432 # The manifest merge handles conflicts on the manifest level. We want
433 # to handle changes in largefile-ness of files at this level too.
433 # to handle changes in largefile-ness of files at this level too.
434 #
434 #
435 # The strategy is to run the original calculateupdates and then process
435 # The strategy is to run the original calculateupdates and then process
436 # the action list it outputs. There are two cases we need to deal with:
436 # the action list it outputs. There are two cases we need to deal with:
437 #
437 #
438 # 1. Normal file in p1, largefile in p2. Here the largefile is
438 # 1. Normal file in p1, largefile in p2. Here the largefile is
439 # detected via its standin file, which will enter the working copy
439 # detected via its standin file, which will enter the working copy
440 # with a "get" action. It is not "merge" since the standin is all
440 # with a "get" action. It is not "merge" since the standin is all
441 # Mercurial is concerned with at this level -- the link to the
441 # Mercurial is concerned with at this level -- the link to the
442 # existing normal file is not relevant here.
442 # existing normal file is not relevant here.
443 #
443 #
444 # 2. Largefile in p1, normal file in p2. Here we get a "merge" action
444 # 2. Largefile in p1, normal file in p2. Here we get a "merge" action
445 # since the largefile will be present in the working copy and
445 # since the largefile will be present in the working copy and
446 # different from the normal file in p2. Mercurial therefore
446 # different from the normal file in p2. Mercurial therefore
447 # triggers a merge action.
447 # triggers a merge action.
448 #
448 #
449 # In both cases, we prompt the user and emit new actions to either
449 # In both cases, we prompt the user and emit new actions to either
450 # remove the standin (if the normal file was kept) or to remove the
450 # remove the standin (if the normal file was kept) or to remove the
451 # normal file and get the standin (if the largefile was kept). The
451 # normal file and get the standin (if the largefile was kept). The
452 # default prompt answer is to use the largefile version since it was
452 # default prompt answer is to use the largefile version since it was
453 # presumably changed on purpose.
453 # presumably changed on purpose.
454 #
454 #
455 # Finally, the merge.applyupdates function will then take care of
455 # Finally, the merge.applyupdates function will then take care of
456 # writing the files into the working copy and lfcommands.updatelfiles
456 # writing the files into the working copy and lfcommands.updatelfiles
457 # will update the largefiles.
457 # will update the largefiles.
458 @eh.wrapfunction(merge, 'calculateupdates')
458 @eh.wrapfunction(merge, 'calculateupdates')
459 def overridecalculateupdates(origfn, repo, p1, p2, pas, branchmerge, force,
459 def overridecalculateupdates(origfn, repo, p1, p2, pas, branchmerge, force,
460 acceptremote, *args, **kwargs):
460 acceptremote, *args, **kwargs):
461 overwrite = force and not branchmerge
461 overwrite = force and not branchmerge
462 actions, diverge, renamedelete = origfn(
462 actions, diverge, renamedelete = origfn(
463 repo, p1, p2, pas, branchmerge, force, acceptremote, *args, **kwargs)
463 repo, p1, p2, pas, branchmerge, force, acceptremote, *args, **kwargs)
464
464
465 if overwrite:
465 if overwrite:
466 return actions, diverge, renamedelete
466 return actions, diverge, renamedelete
467
467
468 # Convert to dictionary with filename as key and action as value.
468 # Convert to dictionary with filename as key and action as value.
469 lfiles = set()
469 lfiles = set()
470 for f in actions:
470 for f in actions:
471 splitstandin = lfutil.splitstandin(f)
471 splitstandin = lfutil.splitstandin(f)
472 if splitstandin in p1:
472 if splitstandin in p1:
473 lfiles.add(splitstandin)
473 lfiles.add(splitstandin)
474 elif lfutil.standin(f) in p1:
474 elif lfutil.standin(f) in p1:
475 lfiles.add(f)
475 lfiles.add(f)
476
476
477 for lfile in sorted(lfiles):
477 for lfile in sorted(lfiles):
478 standin = lfutil.standin(lfile)
478 standin = lfutil.standin(lfile)
479 (lm, largs, lmsg) = actions.get(lfile, (None, None, None))
479 (lm, largs, lmsg) = actions.get(lfile, (None, None, None))
480 (sm, sargs, smsg) = actions.get(standin, (None, None, None))
480 (sm, sargs, smsg) = actions.get(standin, (None, None, None))
481 if sm in ('g', 'dc') and lm != 'r':
481 if sm in ('g', 'dc') and lm != 'r':
482 if sm == 'dc':
482 if sm == 'dc':
483 f1, f2, fa, move, anc = sargs
483 f1, f2, fa, move, anc = sargs
484 sargs = (p2[f2].flags(), False)
484 sargs = (p2[f2].flags(), False)
485 # Case 1: normal file in the working copy, largefile in
485 # Case 1: normal file in the working copy, largefile in
486 # the second parent
486 # the second parent
487 usermsg = _('remote turned local normal file %s into a largefile\n'
487 usermsg = _('remote turned local normal file %s into a largefile\n'
488 'use (l)argefile or keep (n)ormal file?'
488 'use (l)argefile or keep (n)ormal file?'
489 '$$ &Largefile $$ &Normal file') % lfile
489 '$$ &Largefile $$ &Normal file') % lfile
490 if repo.ui.promptchoice(usermsg, 0) == 0: # pick remote largefile
490 if repo.ui.promptchoice(usermsg, 0) == 0: # pick remote largefile
491 actions[lfile] = ('r', None, 'replaced by standin')
491 actions[lfile] = ('r', None, 'replaced by standin')
492 actions[standin] = ('g', sargs, 'replaces standin')
492 actions[standin] = ('g', sargs, 'replaces standin')
493 else: # keep local normal file
493 else: # keep local normal file
494 actions[lfile] = ('k', None, 'replaces standin')
494 actions[lfile] = ('k', None, 'replaces standin')
495 if branchmerge:
495 if branchmerge:
496 actions[standin] = ('k', None, 'replaced by non-standin')
496 actions[standin] = ('k', None, 'replaced by non-standin')
497 else:
497 else:
498 actions[standin] = ('r', None, 'replaced by non-standin')
498 actions[standin] = ('r', None, 'replaced by non-standin')
499 elif lm in ('g', 'dc') and sm != 'r':
499 elif lm in ('g', 'dc') and sm != 'r':
500 if lm == 'dc':
500 if lm == 'dc':
501 f1, f2, fa, move, anc = largs
501 f1, f2, fa, move, anc = largs
502 largs = (p2[f2].flags(), False)
502 largs = (p2[f2].flags(), False)
503 # Case 2: largefile in the working copy, normal file in
503 # Case 2: largefile in the working copy, normal file in
504 # the second parent
504 # the second parent
505 usermsg = _('remote turned local largefile %s into a normal file\n'
505 usermsg = _('remote turned local largefile %s into a normal file\n'
506 'keep (l)argefile or use (n)ormal file?'
506 'keep (l)argefile or use (n)ormal file?'
507 '$$ &Largefile $$ &Normal file') % lfile
507 '$$ &Largefile $$ &Normal file') % lfile
508 if repo.ui.promptchoice(usermsg, 0) == 0: # keep local largefile
508 if repo.ui.promptchoice(usermsg, 0) == 0: # keep local largefile
509 if branchmerge:
509 if branchmerge:
510 # largefile can be restored from standin safely
510 # largefile can be restored from standin safely
511 actions[lfile] = ('k', None, 'replaced by standin')
511 actions[lfile] = ('k', None, 'replaced by standin')
512 actions[standin] = ('k', None, 'replaces standin')
512 actions[standin] = ('k', None, 'replaces standin')
513 else:
513 else:
514 # "lfile" should be marked as "removed" without
514 # "lfile" should be marked as "removed" without
515 # removal of itself
515 # removal of itself
516 actions[lfile] = ('lfmr', None,
516 actions[lfile] = ('lfmr', None,
517 'forget non-standin largefile')
517 'forget non-standin largefile')
518
518
519 # linear-merge should treat this largefile as 're-added'
519 # linear-merge should treat this largefile as 're-added'
520 actions[standin] = ('a', None, 'keep standin')
520 actions[standin] = ('a', None, 'keep standin')
521 else: # pick remote normal file
521 else: # pick remote normal file
522 actions[lfile] = ('g', largs, 'replaces standin')
522 actions[lfile] = ('g', largs, 'replaces standin')
523 actions[standin] = ('r', None, 'replaced by non-standin')
523 actions[standin] = ('r', None, 'replaced by non-standin')
524
524
525 return actions, diverge, renamedelete
525 return actions, diverge, renamedelete
526
526
527 @eh.wrapfunction(merge, 'recordupdates')
527 @eh.wrapfunction(merge, 'recordupdates')
528 def mergerecordupdates(orig, repo, actions, branchmerge):
528 def mergerecordupdates(orig, repo, actions, branchmerge):
529 if 'lfmr' in actions:
529 if 'lfmr' in actions:
530 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
530 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
531 for lfile, args, msg in actions['lfmr']:
531 for lfile, args, msg in actions['lfmr']:
532 # this should be executed before 'orig', to execute 'remove'
532 # this should be executed before 'orig', to execute 'remove'
533 # before all other actions
533 # before all other actions
534 repo.dirstate.remove(lfile)
534 repo.dirstate.remove(lfile)
535 # make sure lfile doesn't get synclfdirstate'd as normal
535 # make sure lfile doesn't get synclfdirstate'd as normal
536 lfdirstate.add(lfile)
536 lfdirstate.add(lfile)
537 lfdirstate.write()
537 lfdirstate.write()
538
538
539 return orig(repo, actions, branchmerge)
539 return orig(repo, actions, branchmerge)
540
540
541 # Override filemerge to prompt the user about how they wish to merge
541 # Override filemerge to prompt the user about how they wish to merge
542 # largefiles. This will handle identical edits without prompting the user.
542 # largefiles. This will handle identical edits without prompting the user.
543 @eh.wrapfunction(filemerge, '_filemerge')
543 @eh.wrapfunction(filemerge, '_filemerge')
544 def overridefilemerge(origfn, premerge, repo, wctx, mynode, orig, fcd, fco, fca,
544 def overridefilemerge(origfn, premerge, repo, wctx, mynode, orig, fcd, fco, fca,
545 labels=None):
545 labels=None):
546 if not lfutil.isstandin(orig) or fcd.isabsent() or fco.isabsent():
546 if not lfutil.isstandin(orig) or fcd.isabsent() or fco.isabsent():
547 return origfn(premerge, repo, wctx, mynode, orig, fcd, fco, fca,
547 return origfn(premerge, repo, wctx, mynode, orig, fcd, fco, fca,
548 labels=labels)
548 labels=labels)
549
549
550 ahash = lfutil.readasstandin(fca).lower()
550 ahash = lfutil.readasstandin(fca).lower()
551 dhash = lfutil.readasstandin(fcd).lower()
551 dhash = lfutil.readasstandin(fcd).lower()
552 ohash = lfutil.readasstandin(fco).lower()
552 ohash = lfutil.readasstandin(fco).lower()
553 if (ohash != ahash and
553 if (ohash != ahash and
554 ohash != dhash and
554 ohash != dhash and
555 (dhash == ahash or
555 (dhash == ahash or
556 repo.ui.promptchoice(
556 repo.ui.promptchoice(
557 _('largefile %s has a merge conflict\nancestor was %s\n'
557 _('largefile %s has a merge conflict\nancestor was %s\n'
558 'keep (l)ocal %s or\ntake (o)ther %s?'
558 'keep (l)ocal %s or\ntake (o)ther %s?'
559 '$$ &Local $$ &Other') %
559 '$$ &Local $$ &Other') %
560 (lfutil.splitstandin(orig), ahash, dhash, ohash),
560 (lfutil.splitstandin(orig), ahash, dhash, ohash),
561 0) == 1)):
561 0) == 1)):
562 repo.wwrite(fcd.path(), fco.data(), fco.flags())
562 repo.wwrite(fcd.path(), fco.data(), fco.flags())
563 return True, 0, False
563 return True, 0, False
564
564
565 @eh.wrapfunction(copiesmod, 'pathcopies')
565 @eh.wrapfunction(copiesmod, 'pathcopies')
566 def copiespathcopies(orig, ctx1, ctx2, match=None):
566 def copiespathcopies(orig, ctx1, ctx2, match=None):
567 copies = orig(ctx1, ctx2, match=match)
567 copies = orig(ctx1, ctx2, match=match)
568 updated = {}
568 updated = {}
569
569
570 for k, v in copies.iteritems():
570 for k, v in copies.iteritems():
571 updated[lfutil.splitstandin(k) or k] = lfutil.splitstandin(v) or v
571 updated[lfutil.splitstandin(k) or k] = lfutil.splitstandin(v) or v
572
572
573 return updated
573 return updated
574
574
575 # Copy first changes the matchers to match standins instead of
575 # Copy first changes the matchers to match standins instead of
576 # largefiles. Then it overrides util.copyfile in that function it
576 # largefiles. Then it overrides util.copyfile in that function it
577 # checks if the destination largefile already exists. It also keeps a
577 # checks if the destination largefile already exists. It also keeps a
578 # list of copied files so that the largefiles can be copied and the
578 # list of copied files so that the largefiles can be copied and the
579 # dirstate updated.
579 # dirstate updated.
580 @eh.wrapfunction(cmdutil, 'copy')
580 @eh.wrapfunction(cmdutil, 'copy')
581 def overridecopy(orig, ui, repo, pats, opts, rename=False):
581 def overridecopy(orig, ui, repo, pats, opts, rename=False):
582 # doesn't remove largefile on rename
582 # doesn't remove largefile on rename
583 if len(pats) < 2:
583 if len(pats) < 2:
584 # this isn't legal, let the original function deal with it
584 # this isn't legal, let the original function deal with it
585 return orig(ui, repo, pats, opts, rename)
585 return orig(ui, repo, pats, opts, rename)
586
586
587 # This could copy both lfiles and normal files in one command,
587 # This could copy both lfiles and normal files in one command,
588 # but we don't want to do that. First replace their matcher to
588 # but we don't want to do that. First replace their matcher to
589 # only match normal files and run it, then replace it to just
589 # only match normal files and run it, then replace it to just
590 # match largefiles and run it again.
590 # match largefiles and run it again.
591 nonormalfiles = False
591 nonormalfiles = False
592 nolfiles = False
592 nolfiles = False
593 manifest = repo[None].manifest()
593 manifest = repo[None].manifest()
594 def normalfilesmatchfn(orig, ctx, pats=(), opts=None, globbed=False,
594 def normalfilesmatchfn(orig, ctx, pats=(), opts=None, globbed=False,
595 default='relpath', badfn=None):
595 default='relpath', badfn=None):
596 if opts is None:
596 if opts is None:
597 opts = {}
597 opts = {}
598 match = orig(ctx, pats, opts, globbed, default, badfn=badfn)
598 match = orig(ctx, pats, opts, globbed, default, badfn=badfn)
599 return composenormalfilematcher(match, manifest)
599 return composenormalfilematcher(match, manifest)
600 with extensions.wrappedfunction(scmutil, 'match', normalfilesmatchfn):
600 with extensions.wrappedfunction(scmutil, 'match', normalfilesmatchfn):
601 try:
601 try:
602 result = orig(ui, repo, pats, opts, rename)
602 result = orig(ui, repo, pats, opts, rename)
603 except error.Abort as e:
603 except error.Abort as e:
604 if pycompat.bytestr(e) != _('no files to copy'):
604 if pycompat.bytestr(e) != _('no files to copy'):
605 raise e
605 raise e
606 else:
606 else:
607 nonormalfiles = True
607 nonormalfiles = True
608 result = 0
608 result = 0
609
609
610 # The first rename can cause our current working directory to be removed.
610 # The first rename can cause our current working directory to be removed.
611 # In that case there is nothing left to copy/rename so just quit.
611 # In that case there is nothing left to copy/rename so just quit.
612 try:
612 try:
613 repo.getcwd()
613 repo.getcwd()
614 except OSError:
614 except OSError:
615 return result
615 return result
616
616
617 def makestandin(relpath):
617 def makestandin(relpath):
618 path = pathutil.canonpath(repo.root, repo.getcwd(), relpath)
618 path = pathutil.canonpath(repo.root, repo.getcwd(), relpath)
619 return repo.wvfs.join(lfutil.standin(path))
619 return repo.wvfs.join(lfutil.standin(path))
620
620
621 fullpats = scmutil.expandpats(pats)
621 fullpats = scmutil.expandpats(pats)
622 dest = fullpats[-1]
622 dest = fullpats[-1]
623
623
624 if os.path.isdir(dest):
624 if os.path.isdir(dest):
625 if not os.path.isdir(makestandin(dest)):
625 if not os.path.isdir(makestandin(dest)):
626 os.makedirs(makestandin(dest))
626 os.makedirs(makestandin(dest))
627
627
628 try:
628 try:
629 # When we call orig below it creates the standins but we don't add
629 # When we call orig below it creates the standins but we don't add
630 # them to the dir state until later so lock during that time.
630 # them to the dir state until later so lock during that time.
631 wlock = repo.wlock()
631 wlock = repo.wlock()
632
632
633 manifest = repo[None].manifest()
633 manifest = repo[None].manifest()
634 def overridematch(orig, ctx, pats=(), opts=None, globbed=False,
634 def overridematch(orig, ctx, pats=(), opts=None, globbed=False,
635 default='relpath', badfn=None):
635 default='relpath', badfn=None):
636 if opts is None:
636 if opts is None:
637 opts = {}
637 opts = {}
638 newpats = []
638 newpats = []
639 # The patterns were previously mangled to add the standin
639 # The patterns were previously mangled to add the standin
640 # directory; we need to remove that now
640 # directory; we need to remove that now
641 for pat in pats:
641 for pat in pats:
642 if matchmod.patkind(pat) is None and lfutil.shortname in pat:
642 if matchmod.patkind(pat) is None and lfutil.shortname in pat:
643 newpats.append(pat.replace(lfutil.shortname, ''))
643 newpats.append(pat.replace(lfutil.shortname, ''))
644 else:
644 else:
645 newpats.append(pat)
645 newpats.append(pat)
646 match = orig(ctx, newpats, opts, globbed, default, badfn=badfn)
646 match = orig(ctx, newpats, opts, globbed, default, badfn=badfn)
647 m = copy.copy(match)
647 m = copy.copy(match)
648 lfile = lambda f: lfutil.standin(f) in manifest
648 lfile = lambda f: lfutil.standin(f) in manifest
649 m._files = [lfutil.standin(f) for f in m._files if lfile(f)]
649 m._files = [lfutil.standin(f) for f in m._files if lfile(f)]
650 m._fileset = set(m._files)
650 m._fileset = set(m._files)
651 origmatchfn = m.matchfn
651 origmatchfn = m.matchfn
652 def matchfn(f):
652 def matchfn(f):
653 lfile = lfutil.splitstandin(f)
653 lfile = lfutil.splitstandin(f)
654 return (lfile is not None and
654 return (lfile is not None and
655 (f in manifest) and
655 (f in manifest) and
656 origmatchfn(lfile) or
656 origmatchfn(lfile) or
657 None)
657 None)
658 m.matchfn = matchfn
658 m.matchfn = matchfn
659 return m
659 return m
660 listpats = []
660 listpats = []
661 for pat in pats:
661 for pat in pats:
662 if matchmod.patkind(pat) is not None:
662 if matchmod.patkind(pat) is not None:
663 listpats.append(pat)
663 listpats.append(pat)
664 else:
664 else:
665 listpats.append(makestandin(pat))
665 listpats.append(makestandin(pat))
666
666
667 copiedfiles = []
667 copiedfiles = []
668 def overridecopyfile(orig, src, dest, *args, **kwargs):
668 def overridecopyfile(orig, src, dest, *args, **kwargs):
669 if (lfutil.shortname in src and
669 if (lfutil.shortname in src and
670 dest.startswith(repo.wjoin(lfutil.shortname))):
670 dest.startswith(repo.wjoin(lfutil.shortname))):
671 destlfile = dest.replace(lfutil.shortname, '')
671 destlfile = dest.replace(lfutil.shortname, '')
672 if not opts['force'] and os.path.exists(destlfile):
672 if not opts['force'] and os.path.exists(destlfile):
673 raise IOError('',
673 raise IOError('',
674 _('destination largefile already exists'))
674 _('destination largefile already exists'))
675 copiedfiles.append((src, dest))
675 copiedfiles.append((src, dest))
676 orig(src, dest, *args, **kwargs)
676 orig(src, dest, *args, **kwargs)
677 with extensions.wrappedfunction(util, 'copyfile', overridecopyfile), \
677 with extensions.wrappedfunction(util, 'copyfile', overridecopyfile), \
678 extensions.wrappedfunction(scmutil, 'match', overridematch):
678 extensions.wrappedfunction(scmutil, 'match', overridematch):
679 result += orig(ui, repo, listpats, opts, rename)
679 result += orig(ui, repo, listpats, opts, rename)
680
680
681 lfdirstate = lfutil.openlfdirstate(ui, repo)
681 lfdirstate = lfutil.openlfdirstate(ui, repo)
682 for (src, dest) in copiedfiles:
682 for (src, dest) in copiedfiles:
683 if (lfutil.shortname in src and
683 if (lfutil.shortname in src and
684 dest.startswith(repo.wjoin(lfutil.shortname))):
684 dest.startswith(repo.wjoin(lfutil.shortname))):
685 srclfile = src.replace(repo.wjoin(lfutil.standin('')), '')
685 srclfile = src.replace(repo.wjoin(lfutil.standin('')), '')
686 destlfile = dest.replace(repo.wjoin(lfutil.standin('')), '')
686 destlfile = dest.replace(repo.wjoin(lfutil.standin('')), '')
687 destlfiledir = repo.wvfs.dirname(repo.wjoin(destlfile)) or '.'
687 destlfiledir = repo.wvfs.dirname(repo.wjoin(destlfile)) or '.'
688 if not os.path.isdir(destlfiledir):
688 if not os.path.isdir(destlfiledir):
689 os.makedirs(destlfiledir)
689 os.makedirs(destlfiledir)
690 if rename:
690 if rename:
691 os.rename(repo.wjoin(srclfile), repo.wjoin(destlfile))
691 os.rename(repo.wjoin(srclfile), repo.wjoin(destlfile))
692
692
693 # The file is gone, but this deletes any empty parent
693 # The file is gone, but this deletes any empty parent
694 # directories as a side-effect.
694 # directories as a side-effect.
695 repo.wvfs.unlinkpath(srclfile, ignoremissing=True)
695 repo.wvfs.unlinkpath(srclfile, ignoremissing=True)
696 lfdirstate.remove(srclfile)
696 lfdirstate.remove(srclfile)
697 else:
697 else:
698 util.copyfile(repo.wjoin(srclfile),
698 util.copyfile(repo.wjoin(srclfile),
699 repo.wjoin(destlfile))
699 repo.wjoin(destlfile))
700
700
701 lfdirstate.add(destlfile)
701 lfdirstate.add(destlfile)
702 lfdirstate.write()
702 lfdirstate.write()
703 except error.Abort as e:
703 except error.Abort as e:
704 if pycompat.bytestr(e) != _('no files to copy'):
704 if pycompat.bytestr(e) != _('no files to copy'):
705 raise e
705 raise e
706 else:
706 else:
707 nolfiles = True
707 nolfiles = True
708 finally:
708 finally:
709 wlock.release()
709 wlock.release()
710
710
711 if nolfiles and nonormalfiles:
711 if nolfiles and nonormalfiles:
712 raise error.Abort(_('no files to copy'))
712 raise error.Abort(_('no files to copy'))
713
713
714 return result
714 return result
715
715
716 # When the user calls revert, we have to be careful to not revert any
716 # When the user calls revert, we have to be careful to not revert any
717 # changes to other largefiles accidentally. This means we have to keep
717 # changes to other largefiles accidentally. This means we have to keep
718 # track of the largefiles that are being reverted so we only pull down
718 # track of the largefiles that are being reverted so we only pull down
719 # the necessary largefiles.
719 # the necessary largefiles.
720 #
720 #
721 # Standins are only updated (to match the hash of largefiles) before
721 # Standins are only updated (to match the hash of largefiles) before
722 # commits. Update the standins then run the original revert, changing
722 # commits. Update the standins then run the original revert, changing
723 # the matcher to hit standins instead of largefiles. Based on the
723 # the matcher to hit standins instead of largefiles. Based on the
724 # resulting standins update the largefiles.
724 # resulting standins update the largefiles.
725 @eh.wrapfunction(cmdutil, 'revert')
725 @eh.wrapfunction(cmdutil, 'revert')
726 def overriderevert(orig, ui, repo, ctx, parents, *pats, **opts):
726 def overriderevert(orig, ui, repo, ctx, parents, *pats, **opts):
727 # Because we put the standins in a bad state (by updating them)
727 # Because we put the standins in a bad state (by updating them)
728 # and then return them to a correct state we need to lock to
728 # and then return them to a correct state we need to lock to
729 # prevent others from changing them in their incorrect state.
729 # prevent others from changing them in their incorrect state.
730 with repo.wlock():
730 with repo.wlock():
731 lfdirstate = lfutil.openlfdirstate(ui, repo)
731 lfdirstate = lfutil.openlfdirstate(ui, repo)
732 s = lfutil.lfdirstatestatus(lfdirstate, repo)
732 s = lfutil.lfdirstatestatus(lfdirstate, repo)
733 lfdirstate.write()
733 lfdirstate.write()
734 for lfile in s.modified:
734 for lfile in s.modified:
735 lfutil.updatestandin(repo, lfile, lfutil.standin(lfile))
735 lfutil.updatestandin(repo, lfile, lfutil.standin(lfile))
736 for lfile in s.deleted:
736 for lfile in s.deleted:
737 fstandin = lfutil.standin(lfile)
737 fstandin = lfutil.standin(lfile)
738 if (repo.wvfs.exists(fstandin)):
738 if (repo.wvfs.exists(fstandin)):
739 repo.wvfs.unlink(fstandin)
739 repo.wvfs.unlink(fstandin)
740
740
741 oldstandins = lfutil.getstandinsstate(repo)
741 oldstandins = lfutil.getstandinsstate(repo)
742
742
743 def overridematch(orig, mctx, pats=(), opts=None, globbed=False,
743 def overridematch(orig, mctx, pats=(), opts=None, globbed=False,
744 default='relpath', badfn=None):
744 default='relpath', badfn=None):
745 if opts is None:
745 if opts is None:
746 opts = {}
746 opts = {}
747 match = orig(mctx, pats, opts, globbed, default, badfn=badfn)
747 match = orig(mctx, pats, opts, globbed, default, badfn=badfn)
748 m = copy.copy(match)
748 m = copy.copy(match)
749
749
750 # revert supports recursing into subrepos, and though largefiles
750 # revert supports recursing into subrepos, and though largefiles
751 # currently doesn't work correctly in that case, this match is
751 # currently doesn't work correctly in that case, this match is
752 # called, so the lfdirstate above may not be the correct one for
752 # called, so the lfdirstate above may not be the correct one for
753 # this invocation of match.
753 # this invocation of match.
754 lfdirstate = lfutil.openlfdirstate(mctx.repo().ui, mctx.repo(),
754 lfdirstate = lfutil.openlfdirstate(mctx.repo().ui, mctx.repo(),
755 False)
755 False)
756
756
757 wctx = repo[None]
757 wctx = repo[None]
758 matchfiles = []
758 matchfiles = []
759 for f in m._files:
759 for f in m._files:
760 standin = lfutil.standin(f)
760 standin = lfutil.standin(f)
761 if standin in ctx or standin in mctx:
761 if standin in ctx or standin in mctx:
762 matchfiles.append(standin)
762 matchfiles.append(standin)
763 elif standin in wctx or lfdirstate[f] == 'r':
763 elif standin in wctx or lfdirstate[f] == 'r':
764 continue
764 continue
765 else:
765 else:
766 matchfiles.append(f)
766 matchfiles.append(f)
767 m._files = matchfiles
767 m._files = matchfiles
768 m._fileset = set(m._files)
768 m._fileset = set(m._files)
769 origmatchfn = m.matchfn
769 origmatchfn = m.matchfn
770 def matchfn(f):
770 def matchfn(f):
771 lfile = lfutil.splitstandin(f)
771 lfile = lfutil.splitstandin(f)
772 if lfile is not None:
772 if lfile is not None:
773 return (origmatchfn(lfile) and
773 return (origmatchfn(lfile) and
774 (f in ctx or f in mctx))
774 (f in ctx or f in mctx))
775 return origmatchfn(f)
775 return origmatchfn(f)
776 m.matchfn = matchfn
776 m.matchfn = matchfn
777 return m
777 return m
778 with extensions.wrappedfunction(scmutil, 'match', overridematch):
778 with extensions.wrappedfunction(scmutil, 'match', overridematch):
779 orig(ui, repo, ctx, parents, *pats, **opts)
779 orig(ui, repo, ctx, parents, *pats, **opts)
780
780
781 newstandins = lfutil.getstandinsstate(repo)
781 newstandins = lfutil.getstandinsstate(repo)
782 filelist = lfutil.getlfilestoupdate(oldstandins, newstandins)
782 filelist = lfutil.getlfilestoupdate(oldstandins, newstandins)
783 # lfdirstate should be 'normallookup'-ed for updated files,
783 # lfdirstate should be 'normallookup'-ed for updated files,
784 # because reverting doesn't touch dirstate for 'normal' files
784 # because reverting doesn't touch dirstate for 'normal' files
785 # when target revision is explicitly specified: in such case,
785 # when target revision is explicitly specified: in such case,
786 # 'n' and valid timestamp in dirstate doesn't ensure 'clean'
786 # 'n' and valid timestamp in dirstate doesn't ensure 'clean'
787 # of target (standin) file.
787 # of target (standin) file.
788 lfcommands.updatelfiles(ui, repo, filelist, printmessage=False,
788 lfcommands.updatelfiles(ui, repo, filelist, printmessage=False,
789 normallookup=True)
789 normallookup=True)
790
790
791 # after pulling changesets, we need to take some extra care to get
791 # after pulling changesets, we need to take some extra care to get
792 # largefiles updated remotely
792 # largefiles updated remotely
793 @eh.wrapcommand('pull',
793 @eh.wrapcommand('pull',
794 opts=[('', 'all-largefiles', None,
794 opts=[('', 'all-largefiles', None,
795 _('download all pulled versions of largefiles (DEPRECATED)')),
795 _('download all pulled versions of largefiles (DEPRECATED)')),
796 ('', 'lfrev', [],
796 ('', 'lfrev', [],
797 _('download largefiles for these revisions'), _('REV'))])
797 _('download largefiles for these revisions'), _('REV'))])
798 def overridepull(orig, ui, repo, source=None, **opts):
798 def overridepull(orig, ui, repo, source=None, **opts):
799 revsprepull = len(repo)
799 revsprepull = len(repo)
800 if not source:
800 if not source:
801 source = 'default'
801 source = 'default'
802 repo.lfpullsource = source
802 repo.lfpullsource = source
803 result = orig(ui, repo, source, **opts)
803 result = orig(ui, repo, source, **opts)
804 revspostpull = len(repo)
804 revspostpull = len(repo)
805 lfrevs = opts.get(r'lfrev', [])
805 lfrevs = opts.get(r'lfrev', [])
806 if opts.get(r'all_largefiles'):
806 if opts.get(r'all_largefiles'):
807 lfrevs.append('pulled()')
807 lfrevs.append('pulled()')
808 if lfrevs and revspostpull > revsprepull:
808 if lfrevs and revspostpull > revsprepull:
809 numcached = 0
809 numcached = 0
810 repo.firstpulled = revsprepull # for pulled() revset expression
810 repo.firstpulled = revsprepull # for pulled() revset expression
811 try:
811 try:
812 for rev in scmutil.revrange(repo, lfrevs):
812 for rev in scmutil.revrange(repo, lfrevs):
813 ui.note(_('pulling largefiles for revision %d\n') % rev)
813 ui.note(_('pulling largefiles for revision %d\n') % rev)
814 (cached, missing) = lfcommands.cachelfiles(ui, repo, rev)
814 (cached, missing) = lfcommands.cachelfiles(ui, repo, rev)
815 numcached += len(cached)
815 numcached += len(cached)
816 finally:
816 finally:
817 del repo.firstpulled
817 del repo.firstpulled
818 ui.status(_("%d largefiles cached\n") % numcached)
818 ui.status(_("%d largefiles cached\n") % numcached)
819 return result
819 return result
820
820
821 @eh.wrapcommand('push',
821 @eh.wrapcommand('push',
822 opts=[('', 'lfrev', [],
822 opts=[('', 'lfrev', [],
823 _('upload largefiles for these revisions'), _('REV'))])
823 _('upload largefiles for these revisions'), _('REV'))])
824 def overridepush(orig, ui, repo, *args, **kwargs):
824 def overridepush(orig, ui, repo, *args, **kwargs):
825 """Override push command and store --lfrev parameters in opargs"""
825 """Override push command and store --lfrev parameters in opargs"""
826 lfrevs = kwargs.pop(r'lfrev', None)
826 lfrevs = kwargs.pop(r'lfrev', None)
827 if lfrevs:
827 if lfrevs:
828 opargs = kwargs.setdefault(r'opargs', {})
828 opargs = kwargs.setdefault(r'opargs', {})
829 opargs['lfrevs'] = scmutil.revrange(repo, lfrevs)
829 opargs['lfrevs'] = scmutil.revrange(repo, lfrevs)
830 return orig(ui, repo, *args, **kwargs)
830 return orig(ui, repo, *args, **kwargs)
831
831
832 @eh.wrapfunction(exchange, 'pushoperation')
832 @eh.wrapfunction(exchange, 'pushoperation')
833 def exchangepushoperation(orig, *args, **kwargs):
833 def exchangepushoperation(orig, *args, **kwargs):
834 """Override pushoperation constructor and store lfrevs parameter"""
834 """Override pushoperation constructor and store lfrevs parameter"""
835 lfrevs = kwargs.pop(r'lfrevs', None)
835 lfrevs = kwargs.pop(r'lfrevs', None)
836 pushop = orig(*args, **kwargs)
836 pushop = orig(*args, **kwargs)
837 pushop.lfrevs = lfrevs
837 pushop.lfrevs = lfrevs
838 return pushop
838 return pushop
839
839
840 @eh.revsetpredicate('pulled()')
840 @eh.revsetpredicate('pulled()')
841 def pulledrevsetsymbol(repo, subset, x):
841 def pulledrevsetsymbol(repo, subset, x):
842 """Changesets that just has been pulled.
842 """Changesets that just has been pulled.
843
843
844 Only available with largefiles from pull --lfrev expressions.
844 Only available with largefiles from pull --lfrev expressions.
845
845
846 .. container:: verbose
846 .. container:: verbose
847
847
848 Some examples:
848 Some examples:
849
849
850 - pull largefiles for all new changesets::
850 - pull largefiles for all new changesets::
851
851
852 hg pull -lfrev "pulled()"
852 hg pull -lfrev "pulled()"
853
853
854 - pull largefiles for all new branch heads::
854 - pull largefiles for all new branch heads::
855
855
856 hg pull -lfrev "head(pulled()) and not closed()"
856 hg pull -lfrev "head(pulled()) and not closed()"
857
857
858 """
858 """
859
859
860 try:
860 try:
861 firstpulled = repo.firstpulled
861 firstpulled = repo.firstpulled
862 except AttributeError:
862 except AttributeError:
863 raise error.Abort(_("pulled() only available in --lfrev"))
863 raise error.Abort(_("pulled() only available in --lfrev"))
864 return smartset.baseset([r for r in subset if r >= firstpulled])
864 return smartset.baseset([r for r in subset if r >= firstpulled])
865
865
866 @eh.wrapcommand('clone',
866 @eh.wrapcommand('clone',
867 opts=[('', 'all-largefiles', None,
867 opts=[('', 'all-largefiles', None,
868 _('download all versions of all largefiles'))])
868 _('download all versions of all largefiles'))])
869 def overrideclone(orig, ui, source, dest=None, **opts):
869 def overrideclone(orig, ui, source, dest=None, **opts):
870 d = dest
870 d = dest
871 if d is None:
871 if d is None:
872 d = hg.defaultdest(source)
872 d = hg.defaultdest(source)
873 if opts.get(r'all_largefiles') and not hg.islocal(d):
873 if opts.get(r'all_largefiles') and not hg.islocal(d):
874 raise error.Abort(_(
874 raise error.Abort(_(
875 '--all-largefiles is incompatible with non-local destination %s') %
875 '--all-largefiles is incompatible with non-local destination %s') %
876 d)
876 d)
877
877
878 return orig(ui, source, dest, **opts)
878 return orig(ui, source, dest, **opts)
879
879
880 @eh.wrapfunction(hg, 'clone')
880 @eh.wrapfunction(hg, 'clone')
881 def hgclone(orig, ui, opts, *args, **kwargs):
881 def hgclone(orig, ui, opts, *args, **kwargs):
882 result = orig(ui, opts, *args, **kwargs)
882 result = orig(ui, opts, *args, **kwargs)
883
883
884 if result is not None:
884 if result is not None:
885 sourcerepo, destrepo = result
885 sourcerepo, destrepo = result
886 repo = destrepo.local()
886 repo = destrepo.local()
887
887
888 # When cloning to a remote repo (like through SSH), no repo is available
888 # When cloning to a remote repo (like through SSH), no repo is available
889 # from the peer. Therefore the largefiles can't be downloaded and the
889 # from the peer. Therefore the largefiles can't be downloaded and the
890 # hgrc can't be updated.
890 # hgrc can't be updated.
891 if not repo:
891 if not repo:
892 return result
892 return result
893
893
894 # Caching is implicitly limited to 'rev' option, since the dest repo was
894 # Caching is implicitly limited to 'rev' option, since the dest repo was
895 # truncated at that point. The user may expect a download count with
895 # truncated at that point. The user may expect a download count with
896 # this option, so attempt whether or not this is a largefile repo.
896 # this option, so attempt whether or not this is a largefile repo.
897 if opts.get('all_largefiles'):
897 if opts.get('all_largefiles'):
898 success, missing = lfcommands.downloadlfiles(ui, repo, None)
898 success, missing = lfcommands.downloadlfiles(ui, repo, None)
899
899
900 if missing != 0:
900 if missing != 0:
901 return None
901 return None
902
902
903 return result
903 return result
904
904
905 @eh.wrapcommand('rebase', extension='rebase')
905 @eh.wrapcommand('rebase', extension='rebase')
906 def overriderebase(orig, ui, repo, **opts):
906 def overriderebase(orig, ui, repo, **opts):
907 if not util.safehasattr(repo, '_largefilesenabled'):
907 if not util.safehasattr(repo, '_largefilesenabled'):
908 return orig(ui, repo, **opts)
908 return orig(ui, repo, **opts)
909
909
910 resuming = opts.get(r'continue')
910 resuming = opts.get(r'continue')
911 repo._lfcommithooks.append(lfutil.automatedcommithook(resuming))
911 repo._lfcommithooks.append(lfutil.automatedcommithook(resuming))
912 repo._lfstatuswriters.append(lambda *msg, **opts: None)
912 repo._lfstatuswriters.append(lambda *msg, **opts: None)
913 try:
913 try:
914 return orig(ui, repo, **opts)
914 return orig(ui, repo, **opts)
915 finally:
915 finally:
916 repo._lfstatuswriters.pop()
916 repo._lfstatuswriters.pop()
917 repo._lfcommithooks.pop()
917 repo._lfcommithooks.pop()
918
918
919 @eh.wrapcommand('archive')
919 @eh.wrapcommand('archive')
920 def overridearchivecmd(orig, ui, repo, dest, **opts):
920 def overridearchivecmd(orig, ui, repo, dest, **opts):
921 repo.unfiltered().lfstatus = True
921 repo.unfiltered().lfstatus = True
922
922
923 try:
923 try:
924 return orig(ui, repo.unfiltered(), dest, **opts)
924 return orig(ui, repo.unfiltered(), dest, **opts)
925 finally:
925 finally:
926 repo.unfiltered().lfstatus = False
926 repo.unfiltered().lfstatus = False
927
927
928 @eh.wrapfunction(webcommands, 'archive')
928 @eh.wrapfunction(webcommands, 'archive')
929 def hgwebarchive(orig, web):
929 def hgwebarchive(orig, web):
930 web.repo.lfstatus = True
930 web.repo.lfstatus = True
931
931
932 try:
932 try:
933 return orig(web)
933 return orig(web)
934 finally:
934 finally:
935 web.repo.lfstatus = False
935 web.repo.lfstatus = False
936
936
937 @eh.wrapfunction(archival, 'archive')
937 @eh.wrapfunction(archival, 'archive')
938 def overridearchive(orig, repo, dest, node, kind, decode=True, match=None,
938 def overridearchive(orig, repo, dest, node, kind, decode=True, match=None,
939 prefix='', mtime=None, subrepos=None):
939 prefix='', mtime=None, subrepos=None):
940 # For some reason setting repo.lfstatus in hgwebarchive only changes the
940 # For some reason setting repo.lfstatus in hgwebarchive only changes the
941 # unfiltered repo's attr, so check that as well.
941 # unfiltered repo's attr, so check that as well.
942 if not repo.lfstatus and not repo.unfiltered().lfstatus:
942 if not repo.lfstatus and not repo.unfiltered().lfstatus:
943 return orig(repo, dest, node, kind, decode, match, prefix, mtime,
943 return orig(repo, dest, node, kind, decode, match, prefix, mtime,
944 subrepos)
944 subrepos)
945
945
946 # No need to lock because we are only reading history and
946 # No need to lock because we are only reading history and
947 # largefile caches, neither of which are modified.
947 # largefile caches, neither of which are modified.
948 if node is not None:
948 if node is not None:
949 lfcommands.cachelfiles(repo.ui, repo, node)
949 lfcommands.cachelfiles(repo.ui, repo, node)
950
950
951 if kind not in archival.archivers:
951 if kind not in archival.archivers:
952 raise error.Abort(_("unknown archive type '%s'") % kind)
952 raise error.Abort(_("unknown archive type '%s'") % kind)
953
953
954 ctx = repo[node]
954 ctx = repo[node]
955
955
956 if kind == 'files':
956 if kind == 'files':
957 if prefix:
957 if prefix:
958 raise error.Abort(
958 raise error.Abort(
959 _('cannot give prefix when archiving to files'))
959 _('cannot give prefix when archiving to files'))
960 else:
960 else:
961 prefix = archival.tidyprefix(dest, kind, prefix)
961 prefix = archival.tidyprefix(dest, kind, prefix)
962
962
963 def write(name, mode, islink, getdata):
963 def write(name, mode, islink, getdata):
964 if match and not match(name):
964 if match and not match(name):
965 return
965 return
966 data = getdata()
966 data = getdata()
967 if decode:
967 if decode:
968 data = repo.wwritedata(name, data)
968 data = repo.wwritedata(name, data)
969 archiver.addfile(prefix + name, mode, islink, data)
969 archiver.addfile(prefix + name, mode, islink, data)
970
970
971 archiver = archival.archivers[kind](dest, mtime or ctx.date()[0])
971 archiver = archival.archivers[kind](dest, mtime or ctx.date()[0])
972
972
973 if repo.ui.configbool("ui", "archivemeta"):
973 if repo.ui.configbool("ui", "archivemeta"):
974 write('.hg_archival.txt', 0o644, False,
974 write('.hg_archival.txt', 0o644, False,
975 lambda: archival.buildmetadata(ctx))
975 lambda: archival.buildmetadata(ctx))
976
976
977 for f in ctx:
977 for f in ctx:
978 ff = ctx.flags(f)
978 ff = ctx.flags(f)
979 getdata = ctx[f].data
979 getdata = ctx[f].data
980 lfile = lfutil.splitstandin(f)
980 lfile = lfutil.splitstandin(f)
981 if lfile is not None:
981 if lfile is not None:
982 if node is not None:
982 if node is not None:
983 path = lfutil.findfile(repo, getdata().strip())
983 path = lfutil.findfile(repo, getdata().strip())
984
984
985 if path is None:
985 if path is None:
986 raise error.Abort(
986 raise error.Abort(
987 _('largefile %s not found in repo store or system cache')
987 _('largefile %s not found in repo store or system cache')
988 % lfile)
988 % lfile)
989 else:
989 else:
990 path = lfile
990 path = lfile
991
991
992 f = lfile
992 f = lfile
993
993
994 getdata = lambda: util.readfile(path)
994 getdata = lambda: util.readfile(path)
995 write(f, 'x' in ff and 0o755 or 0o644, 'l' in ff, getdata)
995 write(f, 'x' in ff and 0o755 or 0o644, 'l' in ff, getdata)
996
996
997 if subrepos:
997 if subrepos:
998 for subpath in sorted(ctx.substate):
998 for subpath in sorted(ctx.substate):
999 sub = ctx.workingsub(subpath)
999 sub = ctx.workingsub(subpath)
1000 submatch = matchmod.subdirmatcher(subpath, match)
1000 submatch = matchmod.subdirmatcher(subpath, match)
1001 subprefix = prefix + subpath + '/'
1001 subprefix = prefix + subpath + '/'
1002 sub._repo.lfstatus = True
1002 sub._repo.lfstatus = True
1003 sub.archive(archiver, subprefix, submatch)
1003 sub.archive(archiver, subprefix, submatch)
1004
1004
1005 archiver.done()
1005 archiver.done()
1006
1006
1007 @eh.wrapfunction(subrepo.hgsubrepo, 'archive')
1007 @eh.wrapfunction(subrepo.hgsubrepo, 'archive')
1008 def hgsubrepoarchive(orig, repo, archiver, prefix, match=None, decode=True):
1008 def hgsubrepoarchive(orig, repo, archiver, prefix, match=None, decode=True):
1009 lfenabled = util.safehasattr(repo._repo, '_largefilesenabled')
1009 lfenabled = util.safehasattr(repo._repo, '_largefilesenabled')
1010 if not lfenabled or not repo._repo.lfstatus:
1010 if not lfenabled or not repo._repo.lfstatus:
1011 return orig(repo, archiver, prefix, match, decode)
1011 return orig(repo, archiver, prefix, match, decode)
1012
1012
1013 repo._get(repo._state + ('hg',))
1013 repo._get(repo._state + ('hg',))
1014 rev = repo._state[1]
1014 rev = repo._state[1]
1015 ctx = repo._repo[rev]
1015 ctx = repo._repo[rev]
1016
1016
1017 if ctx.node() is not None:
1017 if ctx.node() is not None:
1018 lfcommands.cachelfiles(repo.ui, repo._repo, ctx.node())
1018 lfcommands.cachelfiles(repo.ui, repo._repo, ctx.node())
1019
1019
1020 def write(name, mode, islink, getdata):
1020 def write(name, mode, islink, getdata):
1021 # At this point, the standin has been replaced with the largefile name,
1021 # At this point, the standin has been replaced with the largefile name,
1022 # so the normal matcher works here without the lfutil variants.
1022 # so the normal matcher works here without the lfutil variants.
1023 if match and not match(f):
1023 if match and not match(f):
1024 return
1024 return
1025 data = getdata()
1025 data = getdata()
1026 if decode:
1026 if decode:
1027 data = repo._repo.wwritedata(name, data)
1027 data = repo._repo.wwritedata(name, data)
1028
1028
1029 archiver.addfile(prefix + name, mode, islink, data)
1029 archiver.addfile(prefix + name, mode, islink, data)
1030
1030
1031 for f in ctx:
1031 for f in ctx:
1032 ff = ctx.flags(f)
1032 ff = ctx.flags(f)
1033 getdata = ctx[f].data
1033 getdata = ctx[f].data
1034 lfile = lfutil.splitstandin(f)
1034 lfile = lfutil.splitstandin(f)
1035 if lfile is not None:
1035 if lfile is not None:
1036 if ctx.node() is not None:
1036 if ctx.node() is not None:
1037 path = lfutil.findfile(repo._repo, getdata().strip())
1037 path = lfutil.findfile(repo._repo, getdata().strip())
1038
1038
1039 if path is None:
1039 if path is None:
1040 raise error.Abort(
1040 raise error.Abort(
1041 _('largefile %s not found in repo store or system cache')
1041 _('largefile %s not found in repo store or system cache')
1042 % lfile)
1042 % lfile)
1043 else:
1043 else:
1044 path = lfile
1044 path = lfile
1045
1045
1046 f = lfile
1046 f = lfile
1047
1047
1048 getdata = lambda: util.readfile(os.path.join(prefix, path))
1048 getdata = lambda: util.readfile(os.path.join(prefix, path))
1049
1049
1050 write(f, 'x' in ff and 0o755 or 0o644, 'l' in ff, getdata)
1050 write(f, 'x' in ff and 0o755 or 0o644, 'l' in ff, getdata)
1051
1051
1052 for subpath in sorted(ctx.substate):
1052 for subpath in sorted(ctx.substate):
1053 sub = ctx.workingsub(subpath)
1053 sub = ctx.workingsub(subpath)
1054 submatch = matchmod.subdirmatcher(subpath, match)
1054 submatch = matchmod.subdirmatcher(subpath, match)
1055 subprefix = prefix + subpath + '/'
1055 subprefix = prefix + subpath + '/'
1056 sub._repo.lfstatus = True
1056 sub._repo.lfstatus = True
1057 sub.archive(archiver, subprefix, submatch, decode)
1057 sub.archive(archiver, subprefix, submatch, decode)
1058
1058
1059 # If a largefile is modified, the change is not reflected in its
1059 # If a largefile is modified, the change is not reflected in its
1060 # standin until a commit. cmdutil.bailifchanged() raises an exception
1060 # standin until a commit. cmdutil.bailifchanged() raises an exception
1061 # if the repo has uncommitted changes. Wrap it to also check if
1061 # if the repo has uncommitted changes. Wrap it to also check if
1062 # largefiles were changed. This is used by bisect, backout and fetch.
1062 # largefiles were changed. This is used by bisect, backout and fetch.
1063 @eh.wrapfunction(cmdutil, 'bailifchanged')
1063 @eh.wrapfunction(cmdutil, 'bailifchanged')
1064 def overridebailifchanged(orig, repo, *args, **kwargs):
1064 def overridebailifchanged(orig, repo, *args, **kwargs):
1065 orig(repo, *args, **kwargs)
1065 orig(repo, *args, **kwargs)
1066 repo.lfstatus = True
1066 repo.lfstatus = True
1067 s = repo.status()
1067 s = repo.status()
1068 repo.lfstatus = False
1068 repo.lfstatus = False
1069 if s.modified or s.added or s.removed or s.deleted:
1069 if s.modified or s.added or s.removed or s.deleted:
1070 raise error.Abort(_('uncommitted changes'))
1070 raise error.Abort(_('uncommitted changes'))
1071
1071
1072 @eh.wrapfunction(cmdutil, 'postcommitstatus')
1072 @eh.wrapfunction(cmdutil, 'postcommitstatus')
1073 def postcommitstatus(orig, repo, *args, **kwargs):
1073 def postcommitstatus(orig, repo, *args, **kwargs):
1074 repo.lfstatus = True
1074 repo.lfstatus = True
1075 try:
1075 try:
1076 return orig(repo, *args, **kwargs)
1076 return orig(repo, *args, **kwargs)
1077 finally:
1077 finally:
1078 repo.lfstatus = False
1078 repo.lfstatus = False
1079
1079
1080 @eh.wrapfunction(cmdutil, 'forget')
1080 @eh.wrapfunction(cmdutil, 'forget')
1081 def cmdutilforget(orig, ui, repo, match, prefix, explicitonly, dryrun,
1081 def cmdutilforget(orig, ui, repo, match, prefix, uipathfn, explicitonly, dryrun,
1082 interactive):
1082 interactive):
1083 normalmatcher = composenormalfilematcher(match, repo[None].manifest())
1083 normalmatcher = composenormalfilematcher(match, repo[None].manifest())
1084 bad, forgot = orig(ui, repo, normalmatcher, prefix, explicitonly, dryrun,
1084 bad, forgot = orig(ui, repo, normalmatcher, prefix, uipathfn, explicitonly,
1085 interactive)
1085 dryrun, interactive)
1086 m = composelargefilematcher(match, repo[None].manifest())
1086 m = composelargefilematcher(match, repo[None].manifest())
1087
1087
1088 try:
1088 try:
1089 repo.lfstatus = True
1089 repo.lfstatus = True
1090 s = repo.status(match=m, clean=True)
1090 s = repo.status(match=m, clean=True)
1091 finally:
1091 finally:
1092 repo.lfstatus = False
1092 repo.lfstatus = False
1093 manifest = repo[None].manifest()
1093 manifest = repo[None].manifest()
1094 forget = sorted(s.modified + s.added + s.deleted + s.clean)
1094 forget = sorted(s.modified + s.added + s.deleted + s.clean)
1095 forget = [f for f in forget if lfutil.standin(f) in manifest]
1095 forget = [f for f in forget if lfutil.standin(f) in manifest]
1096
1096
1097 for f in forget:
1097 for f in forget:
1098 fstandin = lfutil.standin(f)
1098 fstandin = lfutil.standin(f)
1099 if fstandin not in repo.dirstate and not repo.wvfs.isdir(fstandin):
1099 if fstandin not in repo.dirstate and not repo.wvfs.isdir(fstandin):
1100 ui.warn(_('not removing %s: file is already untracked\n')
1100 ui.warn(_('not removing %s: file is already untracked\n')
1101 % m.rel(f))
1101 % uipathfn(f))
1102 bad.append(f)
1102 bad.append(f)
1103
1103
1104 for f in forget:
1104 for f in forget:
1105 if ui.verbose or not m.exact(f):
1105 if ui.verbose or not m.exact(f):
1106 ui.status(_('removing %s\n') % m.rel(f))
1106 ui.status(_('removing %s\n') % uipathfn(f))
1107
1107
1108 # Need to lock because standin files are deleted then removed from the
1108 # Need to lock because standin files are deleted then removed from the
1109 # repository and we could race in-between.
1109 # repository and we could race in-between.
1110 with repo.wlock():
1110 with repo.wlock():
1111 lfdirstate = lfutil.openlfdirstate(ui, repo)
1111 lfdirstate = lfutil.openlfdirstate(ui, repo)
1112 for f in forget:
1112 for f in forget:
1113 if lfdirstate[f] == 'a':
1113 if lfdirstate[f] == 'a':
1114 lfdirstate.drop(f)
1114 lfdirstate.drop(f)
1115 else:
1115 else:
1116 lfdirstate.remove(f)
1116 lfdirstate.remove(f)
1117 lfdirstate.write()
1117 lfdirstate.write()
1118 standins = [lfutil.standin(f) for f in forget]
1118 standins = [lfutil.standin(f) for f in forget]
1119 for f in standins:
1119 for f in standins:
1120 repo.wvfs.unlinkpath(f, ignoremissing=True)
1120 repo.wvfs.unlinkpath(f, ignoremissing=True)
1121 rejected = repo[None].forget(standins)
1121 rejected = repo[None].forget(standins)
1122
1122
1123 bad.extend(f for f in rejected if f in m.files())
1123 bad.extend(f for f in rejected if f in m.files())
1124 forgot.extend(f for f in forget if f not in rejected)
1124 forgot.extend(f for f in forget if f not in rejected)
1125 return bad, forgot
1125 return bad, forgot
1126
1126
1127 def _getoutgoings(repo, other, missing, addfunc):
1127 def _getoutgoings(repo, other, missing, addfunc):
1128 """get pairs of filename and largefile hash in outgoing revisions
1128 """get pairs of filename and largefile hash in outgoing revisions
1129 in 'missing'.
1129 in 'missing'.
1130
1130
1131 largefiles already existing on 'other' repository are ignored.
1131 largefiles already existing on 'other' repository are ignored.
1132
1132
1133 'addfunc' is invoked with each unique pairs of filename and
1133 'addfunc' is invoked with each unique pairs of filename and
1134 largefile hash value.
1134 largefile hash value.
1135 """
1135 """
1136 knowns = set()
1136 knowns = set()
1137 lfhashes = set()
1137 lfhashes = set()
1138 def dedup(fn, lfhash):
1138 def dedup(fn, lfhash):
1139 k = (fn, lfhash)
1139 k = (fn, lfhash)
1140 if k not in knowns:
1140 if k not in knowns:
1141 knowns.add(k)
1141 knowns.add(k)
1142 lfhashes.add(lfhash)
1142 lfhashes.add(lfhash)
1143 lfutil.getlfilestoupload(repo, missing, dedup)
1143 lfutil.getlfilestoupload(repo, missing, dedup)
1144 if lfhashes:
1144 if lfhashes:
1145 lfexists = storefactory.openstore(repo, other).exists(lfhashes)
1145 lfexists = storefactory.openstore(repo, other).exists(lfhashes)
1146 for fn, lfhash in knowns:
1146 for fn, lfhash in knowns:
1147 if not lfexists[lfhash]: # lfhash doesn't exist on "other"
1147 if not lfexists[lfhash]: # lfhash doesn't exist on "other"
1148 addfunc(fn, lfhash)
1148 addfunc(fn, lfhash)
1149
1149
1150 def outgoinghook(ui, repo, other, opts, missing):
1150 def outgoinghook(ui, repo, other, opts, missing):
1151 if opts.pop('large', None):
1151 if opts.pop('large', None):
1152 lfhashes = set()
1152 lfhashes = set()
1153 if ui.debugflag:
1153 if ui.debugflag:
1154 toupload = {}
1154 toupload = {}
1155 def addfunc(fn, lfhash):
1155 def addfunc(fn, lfhash):
1156 if fn not in toupload:
1156 if fn not in toupload:
1157 toupload[fn] = []
1157 toupload[fn] = []
1158 toupload[fn].append(lfhash)
1158 toupload[fn].append(lfhash)
1159 lfhashes.add(lfhash)
1159 lfhashes.add(lfhash)
1160 def showhashes(fn):
1160 def showhashes(fn):
1161 for lfhash in sorted(toupload[fn]):
1161 for lfhash in sorted(toupload[fn]):
1162 ui.debug(' %s\n' % (lfhash))
1162 ui.debug(' %s\n' % (lfhash))
1163 else:
1163 else:
1164 toupload = set()
1164 toupload = set()
1165 def addfunc(fn, lfhash):
1165 def addfunc(fn, lfhash):
1166 toupload.add(fn)
1166 toupload.add(fn)
1167 lfhashes.add(lfhash)
1167 lfhashes.add(lfhash)
1168 def showhashes(fn):
1168 def showhashes(fn):
1169 pass
1169 pass
1170 _getoutgoings(repo, other, missing, addfunc)
1170 _getoutgoings(repo, other, missing, addfunc)
1171
1171
1172 if not toupload:
1172 if not toupload:
1173 ui.status(_('largefiles: no files to upload\n'))
1173 ui.status(_('largefiles: no files to upload\n'))
1174 else:
1174 else:
1175 ui.status(_('largefiles to upload (%d entities):\n')
1175 ui.status(_('largefiles to upload (%d entities):\n')
1176 % (len(lfhashes)))
1176 % (len(lfhashes)))
1177 for file in sorted(toupload):
1177 for file in sorted(toupload):
1178 ui.status(lfutil.splitstandin(file) + '\n')
1178 ui.status(lfutil.splitstandin(file) + '\n')
1179 showhashes(file)
1179 showhashes(file)
1180 ui.status('\n')
1180 ui.status('\n')
1181
1181
1182 @eh.wrapcommand('outgoing',
1182 @eh.wrapcommand('outgoing',
1183 opts=[('', 'large', None, _('display outgoing largefiles'))])
1183 opts=[('', 'large', None, _('display outgoing largefiles'))])
1184 def _outgoingcmd(orig, *args, **kwargs):
1184 def _outgoingcmd(orig, *args, **kwargs):
1185 # Nothing to do here other than add the extra help option- the hook above
1185 # Nothing to do here other than add the extra help option- the hook above
1186 # processes it.
1186 # processes it.
1187 return orig(*args, **kwargs)
1187 return orig(*args, **kwargs)
1188
1188
1189 def summaryremotehook(ui, repo, opts, changes):
1189 def summaryremotehook(ui, repo, opts, changes):
1190 largeopt = opts.get('large', False)
1190 largeopt = opts.get('large', False)
1191 if changes is None:
1191 if changes is None:
1192 if largeopt:
1192 if largeopt:
1193 return (False, True) # only outgoing check is needed
1193 return (False, True) # only outgoing check is needed
1194 else:
1194 else:
1195 return (False, False)
1195 return (False, False)
1196 elif largeopt:
1196 elif largeopt:
1197 url, branch, peer, outgoing = changes[1]
1197 url, branch, peer, outgoing = changes[1]
1198 if peer is None:
1198 if peer is None:
1199 # i18n: column positioning for "hg summary"
1199 # i18n: column positioning for "hg summary"
1200 ui.status(_('largefiles: (no remote repo)\n'))
1200 ui.status(_('largefiles: (no remote repo)\n'))
1201 return
1201 return
1202
1202
1203 toupload = set()
1203 toupload = set()
1204 lfhashes = set()
1204 lfhashes = set()
1205 def addfunc(fn, lfhash):
1205 def addfunc(fn, lfhash):
1206 toupload.add(fn)
1206 toupload.add(fn)
1207 lfhashes.add(lfhash)
1207 lfhashes.add(lfhash)
1208 _getoutgoings(repo, peer, outgoing.missing, addfunc)
1208 _getoutgoings(repo, peer, outgoing.missing, addfunc)
1209
1209
1210 if not toupload:
1210 if not toupload:
1211 # i18n: column positioning for "hg summary"
1211 # i18n: column positioning for "hg summary"
1212 ui.status(_('largefiles: (no files to upload)\n'))
1212 ui.status(_('largefiles: (no files to upload)\n'))
1213 else:
1213 else:
1214 # i18n: column positioning for "hg summary"
1214 # i18n: column positioning for "hg summary"
1215 ui.status(_('largefiles: %d entities for %d files to upload\n')
1215 ui.status(_('largefiles: %d entities for %d files to upload\n')
1216 % (len(lfhashes), len(toupload)))
1216 % (len(lfhashes), len(toupload)))
1217
1217
1218 @eh.wrapcommand('summary',
1218 @eh.wrapcommand('summary',
1219 opts=[('', 'large', None, _('display outgoing largefiles'))])
1219 opts=[('', 'large', None, _('display outgoing largefiles'))])
1220 def overridesummary(orig, ui, repo, *pats, **opts):
1220 def overridesummary(orig, ui, repo, *pats, **opts):
1221 try:
1221 try:
1222 repo.lfstatus = True
1222 repo.lfstatus = True
1223 orig(ui, repo, *pats, **opts)
1223 orig(ui, repo, *pats, **opts)
1224 finally:
1224 finally:
1225 repo.lfstatus = False
1225 repo.lfstatus = False
1226
1226
1227 @eh.wrapfunction(scmutil, 'addremove')
1227 @eh.wrapfunction(scmutil, 'addremove')
1228 def scmutiladdremove(orig, repo, matcher, prefix, uipathfn, opts=None):
1228 def scmutiladdremove(orig, repo, matcher, prefix, uipathfn, opts=None):
1229 if opts is None:
1229 if opts is None:
1230 opts = {}
1230 opts = {}
1231 if not lfutil.islfilesrepo(repo):
1231 if not lfutil.islfilesrepo(repo):
1232 return orig(repo, matcher, prefix, uipathfn, opts)
1232 return orig(repo, matcher, prefix, uipathfn, opts)
1233 # Get the list of missing largefiles so we can remove them
1233 # Get the list of missing largefiles so we can remove them
1234 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
1234 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
1235 unsure, s = lfdirstate.status(matchmod.always(repo.root, repo.getcwd()),
1235 unsure, s = lfdirstate.status(matchmod.always(repo.root, repo.getcwd()),
1236 subrepos=[], ignored=False, clean=False,
1236 subrepos=[], ignored=False, clean=False,
1237 unknown=False)
1237 unknown=False)
1238
1238
1239 # Call into the normal remove code, but the removing of the standin, we want
1239 # Call into the normal remove code, but the removing of the standin, we want
1240 # to have handled by original addremove. Monkey patching here makes sure
1240 # to have handled by original addremove. Monkey patching here makes sure
1241 # we don't remove the standin in the largefiles code, preventing a very
1241 # we don't remove the standin in the largefiles code, preventing a very
1242 # confused state later.
1242 # confused state later.
1243 if s.deleted:
1243 if s.deleted:
1244 m = copy.copy(matcher)
1244 m = copy.copy(matcher)
1245
1245
1246 # The m._files and m._map attributes are not changed to the deleted list
1246 # The m._files and m._map attributes are not changed to the deleted list
1247 # because that affects the m.exact() test, which in turn governs whether
1247 # because that affects the m.exact() test, which in turn governs whether
1248 # or not the file name is printed, and how. Simply limit the original
1248 # or not the file name is printed, and how. Simply limit the original
1249 # matches to those in the deleted status list.
1249 # matches to those in the deleted status list.
1250 matchfn = m.matchfn
1250 matchfn = m.matchfn
1251 m.matchfn = lambda f: f in s.deleted and matchfn(f)
1251 m.matchfn = lambda f: f in s.deleted and matchfn(f)
1252
1252
1253 removelargefiles(repo.ui, repo, True, m, opts.get('dry_run'),
1253 removelargefiles(repo.ui, repo, True, m, opts.get('dry_run'),
1254 **pycompat.strkwargs(opts))
1254 **pycompat.strkwargs(opts))
1255 # Call into the normal add code, and any files that *should* be added as
1255 # Call into the normal add code, and any files that *should* be added as
1256 # largefiles will be
1256 # largefiles will be
1257 added, bad = addlargefiles(repo.ui, repo, True, matcher,
1257 added, bad = addlargefiles(repo.ui, repo, True, matcher,
1258 **pycompat.strkwargs(opts))
1258 **pycompat.strkwargs(opts))
1259 # Now that we've handled largefiles, hand off to the original addremove
1259 # Now that we've handled largefiles, hand off to the original addremove
1260 # function to take care of the rest. Make sure it doesn't do anything with
1260 # function to take care of the rest. Make sure it doesn't do anything with
1261 # largefiles by passing a matcher that will ignore them.
1261 # largefiles by passing a matcher that will ignore them.
1262 matcher = composenormalfilematcher(matcher, repo[None].manifest(), added)
1262 matcher = composenormalfilematcher(matcher, repo[None].manifest(), added)
1263 return orig(repo, matcher, prefix, uipathfn, opts)
1263 return orig(repo, matcher, prefix, uipathfn, opts)
1264
1264
1265 # Calling purge with --all will cause the largefiles to be deleted.
1265 # Calling purge with --all will cause the largefiles to be deleted.
1266 # Override repo.status to prevent this from happening.
1266 # Override repo.status to prevent this from happening.
1267 @eh.wrapcommand('purge', extension='purge')
1267 @eh.wrapcommand('purge', extension='purge')
1268 def overridepurge(orig, ui, repo, *dirs, **opts):
1268 def overridepurge(orig, ui, repo, *dirs, **opts):
1269 # XXX Monkey patching a repoview will not work. The assigned attribute will
1269 # XXX Monkey patching a repoview will not work. The assigned attribute will
1270 # be set on the unfiltered repo, but we will only lookup attributes in the
1270 # be set on the unfiltered repo, but we will only lookup attributes in the
1271 # unfiltered repo if the lookup in the repoview object itself fails. As the
1271 # unfiltered repo if the lookup in the repoview object itself fails. As the
1272 # monkey patched method exists on the repoview class the lookup will not
1272 # monkey patched method exists on the repoview class the lookup will not
1273 # fail. As a result, the original version will shadow the monkey patched
1273 # fail. As a result, the original version will shadow the monkey patched
1274 # one, defeating the monkey patch.
1274 # one, defeating the monkey patch.
1275 #
1275 #
1276 # As a work around we use an unfiltered repo here. We should do something
1276 # As a work around we use an unfiltered repo here. We should do something
1277 # cleaner instead.
1277 # cleaner instead.
1278 repo = repo.unfiltered()
1278 repo = repo.unfiltered()
1279 oldstatus = repo.status
1279 oldstatus = repo.status
1280 def overridestatus(node1='.', node2=None, match=None, ignored=False,
1280 def overridestatus(node1='.', node2=None, match=None, ignored=False,
1281 clean=False, unknown=False, listsubrepos=False):
1281 clean=False, unknown=False, listsubrepos=False):
1282 r = oldstatus(node1, node2, match, ignored, clean, unknown,
1282 r = oldstatus(node1, node2, match, ignored, clean, unknown,
1283 listsubrepos)
1283 listsubrepos)
1284 lfdirstate = lfutil.openlfdirstate(ui, repo)
1284 lfdirstate = lfutil.openlfdirstate(ui, repo)
1285 unknown = [f for f in r.unknown if lfdirstate[f] == '?']
1285 unknown = [f for f in r.unknown if lfdirstate[f] == '?']
1286 ignored = [f for f in r.ignored if lfdirstate[f] == '?']
1286 ignored = [f for f in r.ignored if lfdirstate[f] == '?']
1287 return scmutil.status(r.modified, r.added, r.removed, r.deleted,
1287 return scmutil.status(r.modified, r.added, r.removed, r.deleted,
1288 unknown, ignored, r.clean)
1288 unknown, ignored, r.clean)
1289 repo.status = overridestatus
1289 repo.status = overridestatus
1290 orig(ui, repo, *dirs, **opts)
1290 orig(ui, repo, *dirs, **opts)
1291 repo.status = oldstatus
1291 repo.status = oldstatus
1292
1292
1293 @eh.wrapcommand('rollback')
1293 @eh.wrapcommand('rollback')
1294 def overriderollback(orig, ui, repo, **opts):
1294 def overriderollback(orig, ui, repo, **opts):
1295 with repo.wlock():
1295 with repo.wlock():
1296 before = repo.dirstate.parents()
1296 before = repo.dirstate.parents()
1297 orphans = set(f for f in repo.dirstate
1297 orphans = set(f for f in repo.dirstate
1298 if lfutil.isstandin(f) and repo.dirstate[f] != 'r')
1298 if lfutil.isstandin(f) and repo.dirstate[f] != 'r')
1299 result = orig(ui, repo, **opts)
1299 result = orig(ui, repo, **opts)
1300 after = repo.dirstate.parents()
1300 after = repo.dirstate.parents()
1301 if before == after:
1301 if before == after:
1302 return result # no need to restore standins
1302 return result # no need to restore standins
1303
1303
1304 pctx = repo['.']
1304 pctx = repo['.']
1305 for f in repo.dirstate:
1305 for f in repo.dirstate:
1306 if lfutil.isstandin(f):
1306 if lfutil.isstandin(f):
1307 orphans.discard(f)
1307 orphans.discard(f)
1308 if repo.dirstate[f] == 'r':
1308 if repo.dirstate[f] == 'r':
1309 repo.wvfs.unlinkpath(f, ignoremissing=True)
1309 repo.wvfs.unlinkpath(f, ignoremissing=True)
1310 elif f in pctx:
1310 elif f in pctx:
1311 fctx = pctx[f]
1311 fctx = pctx[f]
1312 repo.wwrite(f, fctx.data(), fctx.flags())
1312 repo.wwrite(f, fctx.data(), fctx.flags())
1313 else:
1313 else:
1314 # content of standin is not so important in 'a',
1314 # content of standin is not so important in 'a',
1315 # 'm' or 'n' (coming from the 2nd parent) cases
1315 # 'm' or 'n' (coming from the 2nd parent) cases
1316 lfutil.writestandin(repo, f, '', False)
1316 lfutil.writestandin(repo, f, '', False)
1317 for standin in orphans:
1317 for standin in orphans:
1318 repo.wvfs.unlinkpath(standin, ignoremissing=True)
1318 repo.wvfs.unlinkpath(standin, ignoremissing=True)
1319
1319
1320 lfdirstate = lfutil.openlfdirstate(ui, repo)
1320 lfdirstate = lfutil.openlfdirstate(ui, repo)
1321 orphans = set(lfdirstate)
1321 orphans = set(lfdirstate)
1322 lfiles = lfutil.listlfiles(repo)
1322 lfiles = lfutil.listlfiles(repo)
1323 for file in lfiles:
1323 for file in lfiles:
1324 lfutil.synclfdirstate(repo, lfdirstate, file, True)
1324 lfutil.synclfdirstate(repo, lfdirstate, file, True)
1325 orphans.discard(file)
1325 orphans.discard(file)
1326 for lfile in orphans:
1326 for lfile in orphans:
1327 lfdirstate.drop(lfile)
1327 lfdirstate.drop(lfile)
1328 lfdirstate.write()
1328 lfdirstate.write()
1329 return result
1329 return result
1330
1330
1331 @eh.wrapcommand('transplant', extension='transplant')
1331 @eh.wrapcommand('transplant', extension='transplant')
1332 def overridetransplant(orig, ui, repo, *revs, **opts):
1332 def overridetransplant(orig, ui, repo, *revs, **opts):
1333 resuming = opts.get(r'continue')
1333 resuming = opts.get(r'continue')
1334 repo._lfcommithooks.append(lfutil.automatedcommithook(resuming))
1334 repo._lfcommithooks.append(lfutil.automatedcommithook(resuming))
1335 repo._lfstatuswriters.append(lambda *msg, **opts: None)
1335 repo._lfstatuswriters.append(lambda *msg, **opts: None)
1336 try:
1336 try:
1337 result = orig(ui, repo, *revs, **opts)
1337 result = orig(ui, repo, *revs, **opts)
1338 finally:
1338 finally:
1339 repo._lfstatuswriters.pop()
1339 repo._lfstatuswriters.pop()
1340 repo._lfcommithooks.pop()
1340 repo._lfcommithooks.pop()
1341 return result
1341 return result
1342
1342
1343 @eh.wrapcommand('cat')
1343 @eh.wrapcommand('cat')
1344 def overridecat(orig, ui, repo, file1, *pats, **opts):
1344 def overridecat(orig, ui, repo, file1, *pats, **opts):
1345 opts = pycompat.byteskwargs(opts)
1345 opts = pycompat.byteskwargs(opts)
1346 ctx = scmutil.revsingle(repo, opts.get('rev'))
1346 ctx = scmutil.revsingle(repo, opts.get('rev'))
1347 err = 1
1347 err = 1
1348 notbad = set()
1348 notbad = set()
1349 m = scmutil.match(ctx, (file1,) + pats, opts)
1349 m = scmutil.match(ctx, (file1,) + pats, opts)
1350 origmatchfn = m.matchfn
1350 origmatchfn = m.matchfn
1351 def lfmatchfn(f):
1351 def lfmatchfn(f):
1352 if origmatchfn(f):
1352 if origmatchfn(f):
1353 return True
1353 return True
1354 lf = lfutil.splitstandin(f)
1354 lf = lfutil.splitstandin(f)
1355 if lf is None:
1355 if lf is None:
1356 return False
1356 return False
1357 notbad.add(lf)
1357 notbad.add(lf)
1358 return origmatchfn(lf)
1358 return origmatchfn(lf)
1359 m.matchfn = lfmatchfn
1359 m.matchfn = lfmatchfn
1360 origbadfn = m.bad
1360 origbadfn = m.bad
1361 def lfbadfn(f, msg):
1361 def lfbadfn(f, msg):
1362 if not f in notbad:
1362 if not f in notbad:
1363 origbadfn(f, msg)
1363 origbadfn(f, msg)
1364 m.bad = lfbadfn
1364 m.bad = lfbadfn
1365
1365
1366 origvisitdirfn = m.visitdir
1366 origvisitdirfn = m.visitdir
1367 def lfvisitdirfn(dir):
1367 def lfvisitdirfn(dir):
1368 if dir == lfutil.shortname:
1368 if dir == lfutil.shortname:
1369 return True
1369 return True
1370 ret = origvisitdirfn(dir)
1370 ret = origvisitdirfn(dir)
1371 if ret:
1371 if ret:
1372 return ret
1372 return ret
1373 lf = lfutil.splitstandin(dir)
1373 lf = lfutil.splitstandin(dir)
1374 if lf is None:
1374 if lf is None:
1375 return False
1375 return False
1376 return origvisitdirfn(lf)
1376 return origvisitdirfn(lf)
1377 m.visitdir = lfvisitdirfn
1377 m.visitdir = lfvisitdirfn
1378
1378
1379 for f in ctx.walk(m):
1379 for f in ctx.walk(m):
1380 with cmdutil.makefileobj(ctx, opts.get('output'), pathname=f) as fp:
1380 with cmdutil.makefileobj(ctx, opts.get('output'), pathname=f) as fp:
1381 lf = lfutil.splitstandin(f)
1381 lf = lfutil.splitstandin(f)
1382 if lf is None or origmatchfn(f):
1382 if lf is None or origmatchfn(f):
1383 # duplicating unreachable code from commands.cat
1383 # duplicating unreachable code from commands.cat
1384 data = ctx[f].data()
1384 data = ctx[f].data()
1385 if opts.get('decode'):
1385 if opts.get('decode'):
1386 data = repo.wwritedata(f, data)
1386 data = repo.wwritedata(f, data)
1387 fp.write(data)
1387 fp.write(data)
1388 else:
1388 else:
1389 hash = lfutil.readasstandin(ctx[f])
1389 hash = lfutil.readasstandin(ctx[f])
1390 if not lfutil.inusercache(repo.ui, hash):
1390 if not lfutil.inusercache(repo.ui, hash):
1391 store = storefactory.openstore(repo)
1391 store = storefactory.openstore(repo)
1392 success, missing = store.get([(lf, hash)])
1392 success, missing = store.get([(lf, hash)])
1393 if len(success) != 1:
1393 if len(success) != 1:
1394 raise error.Abort(
1394 raise error.Abort(
1395 _('largefile %s is not in cache and could not be '
1395 _('largefile %s is not in cache and could not be '
1396 'downloaded') % lf)
1396 'downloaded') % lf)
1397 path = lfutil.usercachepath(repo.ui, hash)
1397 path = lfutil.usercachepath(repo.ui, hash)
1398 with open(path, "rb") as fpin:
1398 with open(path, "rb") as fpin:
1399 for chunk in util.filechunkiter(fpin):
1399 for chunk in util.filechunkiter(fpin):
1400 fp.write(chunk)
1400 fp.write(chunk)
1401 err = 0
1401 err = 0
1402 return err
1402 return err
1403
1403
1404 @eh.wrapfunction(merge, 'update')
1404 @eh.wrapfunction(merge, 'update')
1405 def mergeupdate(orig, repo, node, branchmerge, force,
1405 def mergeupdate(orig, repo, node, branchmerge, force,
1406 *args, **kwargs):
1406 *args, **kwargs):
1407 matcher = kwargs.get(r'matcher', None)
1407 matcher = kwargs.get(r'matcher', None)
1408 # note if this is a partial update
1408 # note if this is a partial update
1409 partial = matcher and not matcher.always()
1409 partial = matcher and not matcher.always()
1410 with repo.wlock():
1410 with repo.wlock():
1411 # branch | | |
1411 # branch | | |
1412 # merge | force | partial | action
1412 # merge | force | partial | action
1413 # -------+-------+---------+--------------
1413 # -------+-------+---------+--------------
1414 # x | x | x | linear-merge
1414 # x | x | x | linear-merge
1415 # o | x | x | branch-merge
1415 # o | x | x | branch-merge
1416 # x | o | x | overwrite (as clean update)
1416 # x | o | x | overwrite (as clean update)
1417 # o | o | x | force-branch-merge (*1)
1417 # o | o | x | force-branch-merge (*1)
1418 # x | x | o | (*)
1418 # x | x | o | (*)
1419 # o | x | o | (*)
1419 # o | x | o | (*)
1420 # x | o | o | overwrite (as revert)
1420 # x | o | o | overwrite (as revert)
1421 # o | o | o | (*)
1421 # o | o | o | (*)
1422 #
1422 #
1423 # (*) don't care
1423 # (*) don't care
1424 # (*1) deprecated, but used internally (e.g: "rebase --collapse")
1424 # (*1) deprecated, but used internally (e.g: "rebase --collapse")
1425
1425
1426 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
1426 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
1427 unsure, s = lfdirstate.status(matchmod.always(repo.root,
1427 unsure, s = lfdirstate.status(matchmod.always(repo.root,
1428 repo.getcwd()),
1428 repo.getcwd()),
1429 subrepos=[], ignored=False,
1429 subrepos=[], ignored=False,
1430 clean=True, unknown=False)
1430 clean=True, unknown=False)
1431 oldclean = set(s.clean)
1431 oldclean = set(s.clean)
1432 pctx = repo['.']
1432 pctx = repo['.']
1433 dctx = repo[node]
1433 dctx = repo[node]
1434 for lfile in unsure + s.modified:
1434 for lfile in unsure + s.modified:
1435 lfileabs = repo.wvfs.join(lfile)
1435 lfileabs = repo.wvfs.join(lfile)
1436 if not repo.wvfs.exists(lfileabs):
1436 if not repo.wvfs.exists(lfileabs):
1437 continue
1437 continue
1438 lfhash = lfutil.hashfile(lfileabs)
1438 lfhash = lfutil.hashfile(lfileabs)
1439 standin = lfutil.standin(lfile)
1439 standin = lfutil.standin(lfile)
1440 lfutil.writestandin(repo, standin, lfhash,
1440 lfutil.writestandin(repo, standin, lfhash,
1441 lfutil.getexecutable(lfileabs))
1441 lfutil.getexecutable(lfileabs))
1442 if (standin in pctx and
1442 if (standin in pctx and
1443 lfhash == lfutil.readasstandin(pctx[standin])):
1443 lfhash == lfutil.readasstandin(pctx[standin])):
1444 oldclean.add(lfile)
1444 oldclean.add(lfile)
1445 for lfile in s.added:
1445 for lfile in s.added:
1446 fstandin = lfutil.standin(lfile)
1446 fstandin = lfutil.standin(lfile)
1447 if fstandin not in dctx:
1447 if fstandin not in dctx:
1448 # in this case, content of standin file is meaningless
1448 # in this case, content of standin file is meaningless
1449 # (in dctx, lfile is unknown, or normal file)
1449 # (in dctx, lfile is unknown, or normal file)
1450 continue
1450 continue
1451 lfutil.updatestandin(repo, lfile, fstandin)
1451 lfutil.updatestandin(repo, lfile, fstandin)
1452 # mark all clean largefiles as dirty, just in case the update gets
1452 # mark all clean largefiles as dirty, just in case the update gets
1453 # interrupted before largefiles and lfdirstate are synchronized
1453 # interrupted before largefiles and lfdirstate are synchronized
1454 for lfile in oldclean:
1454 for lfile in oldclean:
1455 lfdirstate.normallookup(lfile)
1455 lfdirstate.normallookup(lfile)
1456 lfdirstate.write()
1456 lfdirstate.write()
1457
1457
1458 oldstandins = lfutil.getstandinsstate(repo)
1458 oldstandins = lfutil.getstandinsstate(repo)
1459 # Make sure the merge runs on disk, not in-memory. largefiles is not a
1459 # Make sure the merge runs on disk, not in-memory. largefiles is not a
1460 # good candidate for in-memory merge (large files, custom dirstate,
1460 # good candidate for in-memory merge (large files, custom dirstate,
1461 # matcher usage).
1461 # matcher usage).
1462 kwargs[r'wc'] = repo[None]
1462 kwargs[r'wc'] = repo[None]
1463 result = orig(repo, node, branchmerge, force, *args, **kwargs)
1463 result = orig(repo, node, branchmerge, force, *args, **kwargs)
1464
1464
1465 newstandins = lfutil.getstandinsstate(repo)
1465 newstandins = lfutil.getstandinsstate(repo)
1466 filelist = lfutil.getlfilestoupdate(oldstandins, newstandins)
1466 filelist = lfutil.getlfilestoupdate(oldstandins, newstandins)
1467
1467
1468 # to avoid leaving all largefiles as dirty and thus rehash them, mark
1468 # to avoid leaving all largefiles as dirty and thus rehash them, mark
1469 # all the ones that didn't change as clean
1469 # all the ones that didn't change as clean
1470 for lfile in oldclean.difference(filelist):
1470 for lfile in oldclean.difference(filelist):
1471 lfdirstate.normal(lfile)
1471 lfdirstate.normal(lfile)
1472 lfdirstate.write()
1472 lfdirstate.write()
1473
1473
1474 if branchmerge or force or partial:
1474 if branchmerge or force or partial:
1475 filelist.extend(s.deleted + s.removed)
1475 filelist.extend(s.deleted + s.removed)
1476
1476
1477 lfcommands.updatelfiles(repo.ui, repo, filelist=filelist,
1477 lfcommands.updatelfiles(repo.ui, repo, filelist=filelist,
1478 normallookup=partial)
1478 normallookup=partial)
1479
1479
1480 return result
1480 return result
1481
1481
1482 @eh.wrapfunction(scmutil, 'marktouched')
1482 @eh.wrapfunction(scmutil, 'marktouched')
1483 def scmutilmarktouched(orig, repo, files, *args, **kwargs):
1483 def scmutilmarktouched(orig, repo, files, *args, **kwargs):
1484 result = orig(repo, files, *args, **kwargs)
1484 result = orig(repo, files, *args, **kwargs)
1485
1485
1486 filelist = []
1486 filelist = []
1487 for f in files:
1487 for f in files:
1488 lf = lfutil.splitstandin(f)
1488 lf = lfutil.splitstandin(f)
1489 if lf is not None:
1489 if lf is not None:
1490 filelist.append(lf)
1490 filelist.append(lf)
1491 if filelist:
1491 if filelist:
1492 lfcommands.updatelfiles(repo.ui, repo, filelist=filelist,
1492 lfcommands.updatelfiles(repo.ui, repo, filelist=filelist,
1493 printmessage=False, normallookup=True)
1493 printmessage=False, normallookup=True)
1494
1494
1495 return result
1495 return result
1496
1496
1497 @eh.wrapfunction(upgrade, 'preservedrequirements')
1497 @eh.wrapfunction(upgrade, 'preservedrequirements')
1498 @eh.wrapfunction(upgrade, 'supporteddestrequirements')
1498 @eh.wrapfunction(upgrade, 'supporteddestrequirements')
1499 def upgraderequirements(orig, repo):
1499 def upgraderequirements(orig, repo):
1500 reqs = orig(repo)
1500 reqs = orig(repo)
1501 if 'largefiles' in repo.requirements:
1501 if 'largefiles' in repo.requirements:
1502 reqs.add('largefiles')
1502 reqs.add('largefiles')
1503 return reqs
1503 return reqs
1504
1504
1505 _lfscheme = 'largefile://'
1505 _lfscheme = 'largefile://'
1506
1506
1507 @eh.wrapfunction(urlmod, 'open')
1507 @eh.wrapfunction(urlmod, 'open')
1508 def openlargefile(orig, ui, url_, data=None):
1508 def openlargefile(orig, ui, url_, data=None):
1509 if url_.startswith(_lfscheme):
1509 if url_.startswith(_lfscheme):
1510 if data:
1510 if data:
1511 msg = "cannot use data on a 'largefile://' url"
1511 msg = "cannot use data on a 'largefile://' url"
1512 raise error.ProgrammingError(msg)
1512 raise error.ProgrammingError(msg)
1513 lfid = url_[len(_lfscheme):]
1513 lfid = url_[len(_lfscheme):]
1514 return storefactory.getlfile(ui, lfid)
1514 return storefactory.getlfile(ui, lfid)
1515 else:
1515 else:
1516 return orig(ui, url_, data=data)
1516 return orig(ui, url_, data=data)
@@ -1,3342 +1,3345 b''
1 # cmdutil.py - help for command processing in mercurial
1 # cmdutil.py - help for command processing in mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import os
11 import os
12 import re
12 import re
13
13
14 from .i18n import _
14 from .i18n import _
15 from .node import (
15 from .node import (
16 hex,
16 hex,
17 nullid,
17 nullid,
18 nullrev,
18 nullrev,
19 short,
19 short,
20 )
20 )
21
21
22 from . import (
22 from . import (
23 bookmarks,
23 bookmarks,
24 changelog,
24 changelog,
25 copies,
25 copies,
26 crecord as crecordmod,
26 crecord as crecordmod,
27 dirstateguard,
27 dirstateguard,
28 encoding,
28 encoding,
29 error,
29 error,
30 formatter,
30 formatter,
31 logcmdutil,
31 logcmdutil,
32 match as matchmod,
32 match as matchmod,
33 merge as mergemod,
33 merge as mergemod,
34 mergeutil,
34 mergeutil,
35 obsolete,
35 obsolete,
36 patch,
36 patch,
37 pathutil,
37 pathutil,
38 phases,
38 phases,
39 pycompat,
39 pycompat,
40 revlog,
40 revlog,
41 rewriteutil,
41 rewriteutil,
42 scmutil,
42 scmutil,
43 smartset,
43 smartset,
44 subrepoutil,
44 subrepoutil,
45 templatekw,
45 templatekw,
46 templater,
46 templater,
47 util,
47 util,
48 vfs as vfsmod,
48 vfs as vfsmod,
49 )
49 )
50
50
51 from .utils import (
51 from .utils import (
52 dateutil,
52 dateutil,
53 stringutil,
53 stringutil,
54 )
54 )
55
55
56 stringio = util.stringio
56 stringio = util.stringio
57
57
58 # templates of common command options
58 # templates of common command options
59
59
60 dryrunopts = [
60 dryrunopts = [
61 ('n', 'dry-run', None,
61 ('n', 'dry-run', None,
62 _('do not perform actions, just print output')),
62 _('do not perform actions, just print output')),
63 ]
63 ]
64
64
65 confirmopts = [
65 confirmopts = [
66 ('', 'confirm', None,
66 ('', 'confirm', None,
67 _('ask before applying actions')),
67 _('ask before applying actions')),
68 ]
68 ]
69
69
70 remoteopts = [
70 remoteopts = [
71 ('e', 'ssh', '',
71 ('e', 'ssh', '',
72 _('specify ssh command to use'), _('CMD')),
72 _('specify ssh command to use'), _('CMD')),
73 ('', 'remotecmd', '',
73 ('', 'remotecmd', '',
74 _('specify hg command to run on the remote side'), _('CMD')),
74 _('specify hg command to run on the remote side'), _('CMD')),
75 ('', 'insecure', None,
75 ('', 'insecure', None,
76 _('do not verify server certificate (ignoring web.cacerts config)')),
76 _('do not verify server certificate (ignoring web.cacerts config)')),
77 ]
77 ]
78
78
79 walkopts = [
79 walkopts = [
80 ('I', 'include', [],
80 ('I', 'include', [],
81 _('include names matching the given patterns'), _('PATTERN')),
81 _('include names matching the given patterns'), _('PATTERN')),
82 ('X', 'exclude', [],
82 ('X', 'exclude', [],
83 _('exclude names matching the given patterns'), _('PATTERN')),
83 _('exclude names matching the given patterns'), _('PATTERN')),
84 ]
84 ]
85
85
86 commitopts = [
86 commitopts = [
87 ('m', 'message', '',
87 ('m', 'message', '',
88 _('use text as commit message'), _('TEXT')),
88 _('use text as commit message'), _('TEXT')),
89 ('l', 'logfile', '',
89 ('l', 'logfile', '',
90 _('read commit message from file'), _('FILE')),
90 _('read commit message from file'), _('FILE')),
91 ]
91 ]
92
92
93 commitopts2 = [
93 commitopts2 = [
94 ('d', 'date', '',
94 ('d', 'date', '',
95 _('record the specified date as commit date'), _('DATE')),
95 _('record the specified date as commit date'), _('DATE')),
96 ('u', 'user', '',
96 ('u', 'user', '',
97 _('record the specified user as committer'), _('USER')),
97 _('record the specified user as committer'), _('USER')),
98 ]
98 ]
99
99
100 formatteropts = [
100 formatteropts = [
101 ('T', 'template', '',
101 ('T', 'template', '',
102 _('display with template'), _('TEMPLATE')),
102 _('display with template'), _('TEMPLATE')),
103 ]
103 ]
104
104
105 templateopts = [
105 templateopts = [
106 ('', 'style', '',
106 ('', 'style', '',
107 _('display using template map file (DEPRECATED)'), _('STYLE')),
107 _('display using template map file (DEPRECATED)'), _('STYLE')),
108 ('T', 'template', '',
108 ('T', 'template', '',
109 _('display with template'), _('TEMPLATE')),
109 _('display with template'), _('TEMPLATE')),
110 ]
110 ]
111
111
112 logopts = [
112 logopts = [
113 ('p', 'patch', None, _('show patch')),
113 ('p', 'patch', None, _('show patch')),
114 ('g', 'git', None, _('use git extended diff format')),
114 ('g', 'git', None, _('use git extended diff format')),
115 ('l', 'limit', '',
115 ('l', 'limit', '',
116 _('limit number of changes displayed'), _('NUM')),
116 _('limit number of changes displayed'), _('NUM')),
117 ('M', 'no-merges', None, _('do not show merges')),
117 ('M', 'no-merges', None, _('do not show merges')),
118 ('', 'stat', None, _('output diffstat-style summary of changes')),
118 ('', 'stat', None, _('output diffstat-style summary of changes')),
119 ('G', 'graph', None, _("show the revision DAG")),
119 ('G', 'graph', None, _("show the revision DAG")),
120 ] + templateopts
120 ] + templateopts
121
121
122 diffopts = [
122 diffopts = [
123 ('a', 'text', None, _('treat all files as text')),
123 ('a', 'text', None, _('treat all files as text')),
124 ('g', 'git', None, _('use git extended diff format')),
124 ('g', 'git', None, _('use git extended diff format')),
125 ('', 'binary', None, _('generate binary diffs in git mode (default)')),
125 ('', 'binary', None, _('generate binary diffs in git mode (default)')),
126 ('', 'nodates', None, _('omit dates from diff headers'))
126 ('', 'nodates', None, _('omit dates from diff headers'))
127 ]
127 ]
128
128
129 diffwsopts = [
129 diffwsopts = [
130 ('w', 'ignore-all-space', None,
130 ('w', 'ignore-all-space', None,
131 _('ignore white space when comparing lines')),
131 _('ignore white space when comparing lines')),
132 ('b', 'ignore-space-change', None,
132 ('b', 'ignore-space-change', None,
133 _('ignore changes in the amount of white space')),
133 _('ignore changes in the amount of white space')),
134 ('B', 'ignore-blank-lines', None,
134 ('B', 'ignore-blank-lines', None,
135 _('ignore changes whose lines are all blank')),
135 _('ignore changes whose lines are all blank')),
136 ('Z', 'ignore-space-at-eol', None,
136 ('Z', 'ignore-space-at-eol', None,
137 _('ignore changes in whitespace at EOL')),
137 _('ignore changes in whitespace at EOL')),
138 ]
138 ]
139
139
140 diffopts2 = [
140 diffopts2 = [
141 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
141 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
142 ('p', 'show-function', None, _('show which function each change is in')),
142 ('p', 'show-function', None, _('show which function each change is in')),
143 ('', 'reverse', None, _('produce a diff that undoes the changes')),
143 ('', 'reverse', None, _('produce a diff that undoes the changes')),
144 ] + diffwsopts + [
144 ] + diffwsopts + [
145 ('U', 'unified', '',
145 ('U', 'unified', '',
146 _('number of lines of context to show'), _('NUM')),
146 _('number of lines of context to show'), _('NUM')),
147 ('', 'stat', None, _('output diffstat-style summary of changes')),
147 ('', 'stat', None, _('output diffstat-style summary of changes')),
148 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
148 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
149 ]
149 ]
150
150
151 mergetoolopts = [
151 mergetoolopts = [
152 ('t', 'tool', '', _('specify merge tool'), _('TOOL')),
152 ('t', 'tool', '', _('specify merge tool'), _('TOOL')),
153 ]
153 ]
154
154
155 similarityopts = [
155 similarityopts = [
156 ('s', 'similarity', '',
156 ('s', 'similarity', '',
157 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
157 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
158 ]
158 ]
159
159
160 subrepoopts = [
160 subrepoopts = [
161 ('S', 'subrepos', None,
161 ('S', 'subrepos', None,
162 _('recurse into subrepositories'))
162 _('recurse into subrepositories'))
163 ]
163 ]
164
164
165 debugrevlogopts = [
165 debugrevlogopts = [
166 ('c', 'changelog', False, _('open changelog')),
166 ('c', 'changelog', False, _('open changelog')),
167 ('m', 'manifest', False, _('open manifest')),
167 ('m', 'manifest', False, _('open manifest')),
168 ('', 'dir', '', _('open directory manifest')),
168 ('', 'dir', '', _('open directory manifest')),
169 ]
169 ]
170
170
171 # special string such that everything below this line will be ingored in the
171 # special string such that everything below this line will be ingored in the
172 # editor text
172 # editor text
173 _linebelow = "^HG: ------------------------ >8 ------------------------$"
173 _linebelow = "^HG: ------------------------ >8 ------------------------$"
174
174
175 def ishunk(x):
175 def ishunk(x):
176 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
176 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
177 return isinstance(x, hunkclasses)
177 return isinstance(x, hunkclasses)
178
178
179 def newandmodified(chunks, originalchunks):
179 def newandmodified(chunks, originalchunks):
180 newlyaddedandmodifiedfiles = set()
180 newlyaddedandmodifiedfiles = set()
181 for chunk in chunks:
181 for chunk in chunks:
182 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
182 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
183 originalchunks:
183 originalchunks:
184 newlyaddedandmodifiedfiles.add(chunk.header.filename())
184 newlyaddedandmodifiedfiles.add(chunk.header.filename())
185 return newlyaddedandmodifiedfiles
185 return newlyaddedandmodifiedfiles
186
186
187 def parsealiases(cmd):
187 def parsealiases(cmd):
188 return cmd.split("|")
188 return cmd.split("|")
189
189
190 def setupwrapcolorwrite(ui):
190 def setupwrapcolorwrite(ui):
191 # wrap ui.write so diff output can be labeled/colorized
191 # wrap ui.write so diff output can be labeled/colorized
192 def wrapwrite(orig, *args, **kw):
192 def wrapwrite(orig, *args, **kw):
193 label = kw.pop(r'label', '')
193 label = kw.pop(r'label', '')
194 for chunk, l in patch.difflabel(lambda: args):
194 for chunk, l in patch.difflabel(lambda: args):
195 orig(chunk, label=label + l)
195 orig(chunk, label=label + l)
196
196
197 oldwrite = ui.write
197 oldwrite = ui.write
198 def wrap(*args, **kwargs):
198 def wrap(*args, **kwargs):
199 return wrapwrite(oldwrite, *args, **kwargs)
199 return wrapwrite(oldwrite, *args, **kwargs)
200 setattr(ui, 'write', wrap)
200 setattr(ui, 'write', wrap)
201 return oldwrite
201 return oldwrite
202
202
203 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
203 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
204 try:
204 try:
205 if usecurses:
205 if usecurses:
206 if testfile:
206 if testfile:
207 recordfn = crecordmod.testdecorator(
207 recordfn = crecordmod.testdecorator(
208 testfile, crecordmod.testchunkselector)
208 testfile, crecordmod.testchunkselector)
209 else:
209 else:
210 recordfn = crecordmod.chunkselector
210 recordfn = crecordmod.chunkselector
211
211
212 return crecordmod.filterpatch(ui, originalhunks, recordfn,
212 return crecordmod.filterpatch(ui, originalhunks, recordfn,
213 operation)
213 operation)
214 except crecordmod.fallbackerror as e:
214 except crecordmod.fallbackerror as e:
215 ui.warn('%s\n' % e.message)
215 ui.warn('%s\n' % e.message)
216 ui.warn(_('falling back to text mode\n'))
216 ui.warn(_('falling back to text mode\n'))
217
217
218 return patch.filterpatch(ui, originalhunks, operation)
218 return patch.filterpatch(ui, originalhunks, operation)
219
219
220 def recordfilter(ui, originalhunks, operation=None):
220 def recordfilter(ui, originalhunks, operation=None):
221 """ Prompts the user to filter the originalhunks and return a list of
221 """ Prompts the user to filter the originalhunks and return a list of
222 selected hunks.
222 selected hunks.
223 *operation* is used for to build ui messages to indicate the user what
223 *operation* is used for to build ui messages to indicate the user what
224 kind of filtering they are doing: reverting, committing, shelving, etc.
224 kind of filtering they are doing: reverting, committing, shelving, etc.
225 (see patch.filterpatch).
225 (see patch.filterpatch).
226 """
226 """
227 usecurses = crecordmod.checkcurses(ui)
227 usecurses = crecordmod.checkcurses(ui)
228 testfile = ui.config('experimental', 'crecordtest')
228 testfile = ui.config('experimental', 'crecordtest')
229 oldwrite = setupwrapcolorwrite(ui)
229 oldwrite = setupwrapcolorwrite(ui)
230 try:
230 try:
231 newchunks, newopts = filterchunks(ui, originalhunks, usecurses,
231 newchunks, newopts = filterchunks(ui, originalhunks, usecurses,
232 testfile, operation)
232 testfile, operation)
233 finally:
233 finally:
234 ui.write = oldwrite
234 ui.write = oldwrite
235 return newchunks, newopts
235 return newchunks, newopts
236
236
237 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
237 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
238 filterfn, *pats, **opts):
238 filterfn, *pats, **opts):
239 opts = pycompat.byteskwargs(opts)
239 opts = pycompat.byteskwargs(opts)
240 if not ui.interactive():
240 if not ui.interactive():
241 if cmdsuggest:
241 if cmdsuggest:
242 msg = _('running non-interactively, use %s instead') % cmdsuggest
242 msg = _('running non-interactively, use %s instead') % cmdsuggest
243 else:
243 else:
244 msg = _('running non-interactively')
244 msg = _('running non-interactively')
245 raise error.Abort(msg)
245 raise error.Abort(msg)
246
246
247 # make sure username is set before going interactive
247 # make sure username is set before going interactive
248 if not opts.get('user'):
248 if not opts.get('user'):
249 ui.username() # raise exception, username not provided
249 ui.username() # raise exception, username not provided
250
250
251 def recordfunc(ui, repo, message, match, opts):
251 def recordfunc(ui, repo, message, match, opts):
252 """This is generic record driver.
252 """This is generic record driver.
253
253
254 Its job is to interactively filter local changes, and
254 Its job is to interactively filter local changes, and
255 accordingly prepare working directory into a state in which the
255 accordingly prepare working directory into a state in which the
256 job can be delegated to a non-interactive commit command such as
256 job can be delegated to a non-interactive commit command such as
257 'commit' or 'qrefresh'.
257 'commit' or 'qrefresh'.
258
258
259 After the actual job is done by non-interactive command, the
259 After the actual job is done by non-interactive command, the
260 working directory is restored to its original state.
260 working directory is restored to its original state.
261
261
262 In the end we'll record interesting changes, and everything else
262 In the end we'll record interesting changes, and everything else
263 will be left in place, so the user can continue working.
263 will be left in place, so the user can continue working.
264 """
264 """
265
265
266 checkunfinished(repo, commit=True)
266 checkunfinished(repo, commit=True)
267 wctx = repo[None]
267 wctx = repo[None]
268 merge = len(wctx.parents()) > 1
268 merge = len(wctx.parents()) > 1
269 if merge:
269 if merge:
270 raise error.Abort(_('cannot partially commit a merge '
270 raise error.Abort(_('cannot partially commit a merge '
271 '(use "hg commit" instead)'))
271 '(use "hg commit" instead)'))
272
272
273 def fail(f, msg):
273 def fail(f, msg):
274 raise error.Abort('%s: %s' % (f, msg))
274 raise error.Abort('%s: %s' % (f, msg))
275
275
276 force = opts.get('force')
276 force = opts.get('force')
277 if not force:
277 if not force:
278 vdirs = []
278 vdirs = []
279 match.explicitdir = vdirs.append
279 match.explicitdir = vdirs.append
280 match.bad = fail
280 match.bad = fail
281
281
282 status = repo.status(match=match)
282 status = repo.status(match=match)
283 if not force:
283 if not force:
284 repo.checkcommitpatterns(wctx, vdirs, match, status, fail)
284 repo.checkcommitpatterns(wctx, vdirs, match, status, fail)
285 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True,
285 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True,
286 section='commands',
286 section='commands',
287 configprefix='commit.interactive.')
287 configprefix='commit.interactive.')
288 diffopts.nodates = True
288 diffopts.nodates = True
289 diffopts.git = True
289 diffopts.git = True
290 diffopts.showfunc = True
290 diffopts.showfunc = True
291 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
291 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
292 originalchunks = patch.parsepatch(originaldiff)
292 originalchunks = patch.parsepatch(originaldiff)
293
293
294 # 1. filter patch, since we are intending to apply subset of it
294 # 1. filter patch, since we are intending to apply subset of it
295 try:
295 try:
296 chunks, newopts = filterfn(ui, originalchunks)
296 chunks, newopts = filterfn(ui, originalchunks)
297 except error.PatchError as err:
297 except error.PatchError as err:
298 raise error.Abort(_('error parsing patch: %s') % err)
298 raise error.Abort(_('error parsing patch: %s') % err)
299 opts.update(newopts)
299 opts.update(newopts)
300
300
301 # We need to keep a backup of files that have been newly added and
301 # We need to keep a backup of files that have been newly added and
302 # modified during the recording process because there is a previous
302 # modified during the recording process because there is a previous
303 # version without the edit in the workdir
303 # version without the edit in the workdir
304 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
304 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
305 contenders = set()
305 contenders = set()
306 for h in chunks:
306 for h in chunks:
307 try:
307 try:
308 contenders.update(set(h.files()))
308 contenders.update(set(h.files()))
309 except AttributeError:
309 except AttributeError:
310 pass
310 pass
311
311
312 changed = status.modified + status.added + status.removed
312 changed = status.modified + status.added + status.removed
313 newfiles = [f for f in changed if f in contenders]
313 newfiles = [f for f in changed if f in contenders]
314 if not newfiles:
314 if not newfiles:
315 ui.status(_('no changes to record\n'))
315 ui.status(_('no changes to record\n'))
316 return 0
316 return 0
317
317
318 modified = set(status.modified)
318 modified = set(status.modified)
319
319
320 # 2. backup changed files, so we can restore them in the end
320 # 2. backup changed files, so we can restore them in the end
321
321
322 if backupall:
322 if backupall:
323 tobackup = changed
323 tobackup = changed
324 else:
324 else:
325 tobackup = [f for f in newfiles if f in modified or f in \
325 tobackup = [f for f in newfiles if f in modified or f in \
326 newlyaddedandmodifiedfiles]
326 newlyaddedandmodifiedfiles]
327 backups = {}
327 backups = {}
328 if tobackup:
328 if tobackup:
329 backupdir = repo.vfs.join('record-backups')
329 backupdir = repo.vfs.join('record-backups')
330 try:
330 try:
331 os.mkdir(backupdir)
331 os.mkdir(backupdir)
332 except OSError as err:
332 except OSError as err:
333 if err.errno != errno.EEXIST:
333 if err.errno != errno.EEXIST:
334 raise
334 raise
335 try:
335 try:
336 # backup continues
336 # backup continues
337 for f in tobackup:
337 for f in tobackup:
338 fd, tmpname = pycompat.mkstemp(prefix=f.replace('/', '_') + '.',
338 fd, tmpname = pycompat.mkstemp(prefix=f.replace('/', '_') + '.',
339 dir=backupdir)
339 dir=backupdir)
340 os.close(fd)
340 os.close(fd)
341 ui.debug('backup %r as %r\n' % (f, tmpname))
341 ui.debug('backup %r as %r\n' % (f, tmpname))
342 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
342 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
343 backups[f] = tmpname
343 backups[f] = tmpname
344
344
345 fp = stringio()
345 fp = stringio()
346 for c in chunks:
346 for c in chunks:
347 fname = c.filename()
347 fname = c.filename()
348 if fname in backups:
348 if fname in backups:
349 c.write(fp)
349 c.write(fp)
350 dopatch = fp.tell()
350 dopatch = fp.tell()
351 fp.seek(0)
351 fp.seek(0)
352
352
353 # 2.5 optionally review / modify patch in text editor
353 # 2.5 optionally review / modify patch in text editor
354 if opts.get('review', False):
354 if opts.get('review', False):
355 patchtext = (crecordmod.diffhelptext
355 patchtext = (crecordmod.diffhelptext
356 + crecordmod.patchhelptext
356 + crecordmod.patchhelptext
357 + fp.read())
357 + fp.read())
358 reviewedpatch = ui.edit(patchtext, "",
358 reviewedpatch = ui.edit(patchtext, "",
359 action="diff",
359 action="diff",
360 repopath=repo.path)
360 repopath=repo.path)
361 fp.truncate(0)
361 fp.truncate(0)
362 fp.write(reviewedpatch)
362 fp.write(reviewedpatch)
363 fp.seek(0)
363 fp.seek(0)
364
364
365 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
365 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
366 # 3a. apply filtered patch to clean repo (clean)
366 # 3a. apply filtered patch to clean repo (clean)
367 if backups:
367 if backups:
368 # Equivalent to hg.revert
368 # Equivalent to hg.revert
369 m = scmutil.matchfiles(repo, backups.keys())
369 m = scmutil.matchfiles(repo, backups.keys())
370 mergemod.update(repo, repo.dirstate.p1(), branchmerge=False,
370 mergemod.update(repo, repo.dirstate.p1(), branchmerge=False,
371 force=True, matcher=m)
371 force=True, matcher=m)
372
372
373 # 3b. (apply)
373 # 3b. (apply)
374 if dopatch:
374 if dopatch:
375 try:
375 try:
376 ui.debug('applying patch\n')
376 ui.debug('applying patch\n')
377 ui.debug(fp.getvalue())
377 ui.debug(fp.getvalue())
378 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
378 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
379 except error.PatchError as err:
379 except error.PatchError as err:
380 raise error.Abort(pycompat.bytestr(err))
380 raise error.Abort(pycompat.bytestr(err))
381 del fp
381 del fp
382
382
383 # 4. We prepared working directory according to filtered
383 # 4. We prepared working directory according to filtered
384 # patch. Now is the time to delegate the job to
384 # patch. Now is the time to delegate the job to
385 # commit/qrefresh or the like!
385 # commit/qrefresh or the like!
386
386
387 # Make all of the pathnames absolute.
387 # Make all of the pathnames absolute.
388 newfiles = [repo.wjoin(nf) for nf in newfiles]
388 newfiles = [repo.wjoin(nf) for nf in newfiles]
389 return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts))
389 return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts))
390 finally:
390 finally:
391 # 5. finally restore backed-up files
391 # 5. finally restore backed-up files
392 try:
392 try:
393 dirstate = repo.dirstate
393 dirstate = repo.dirstate
394 for realname, tmpname in backups.iteritems():
394 for realname, tmpname in backups.iteritems():
395 ui.debug('restoring %r to %r\n' % (tmpname, realname))
395 ui.debug('restoring %r to %r\n' % (tmpname, realname))
396
396
397 if dirstate[realname] == 'n':
397 if dirstate[realname] == 'n':
398 # without normallookup, restoring timestamp
398 # without normallookup, restoring timestamp
399 # may cause partially committed files
399 # may cause partially committed files
400 # to be treated as unmodified
400 # to be treated as unmodified
401 dirstate.normallookup(realname)
401 dirstate.normallookup(realname)
402
402
403 # copystat=True here and above are a hack to trick any
403 # copystat=True here and above are a hack to trick any
404 # editors that have f open that we haven't modified them.
404 # editors that have f open that we haven't modified them.
405 #
405 #
406 # Also note that this racy as an editor could notice the
406 # Also note that this racy as an editor could notice the
407 # file's mtime before we've finished writing it.
407 # file's mtime before we've finished writing it.
408 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
408 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
409 os.unlink(tmpname)
409 os.unlink(tmpname)
410 if tobackup:
410 if tobackup:
411 os.rmdir(backupdir)
411 os.rmdir(backupdir)
412 except OSError:
412 except OSError:
413 pass
413 pass
414
414
415 def recordinwlock(ui, repo, message, match, opts):
415 def recordinwlock(ui, repo, message, match, opts):
416 with repo.wlock():
416 with repo.wlock():
417 return recordfunc(ui, repo, message, match, opts)
417 return recordfunc(ui, repo, message, match, opts)
418
418
419 return commit(ui, repo, recordinwlock, pats, opts)
419 return commit(ui, repo, recordinwlock, pats, opts)
420
420
421 class dirnode(object):
421 class dirnode(object):
422 """
422 """
423 Represent a directory in user working copy with information required for
423 Represent a directory in user working copy with information required for
424 the purpose of tersing its status.
424 the purpose of tersing its status.
425
425
426 path is the path to the directory, without a trailing '/'
426 path is the path to the directory, without a trailing '/'
427
427
428 statuses is a set of statuses of all files in this directory (this includes
428 statuses is a set of statuses of all files in this directory (this includes
429 all the files in all the subdirectories too)
429 all the files in all the subdirectories too)
430
430
431 files is a list of files which are direct child of this directory
431 files is a list of files which are direct child of this directory
432
432
433 subdirs is a dictionary of sub-directory name as the key and it's own
433 subdirs is a dictionary of sub-directory name as the key and it's own
434 dirnode object as the value
434 dirnode object as the value
435 """
435 """
436
436
437 def __init__(self, dirpath):
437 def __init__(self, dirpath):
438 self.path = dirpath
438 self.path = dirpath
439 self.statuses = set([])
439 self.statuses = set([])
440 self.files = []
440 self.files = []
441 self.subdirs = {}
441 self.subdirs = {}
442
442
443 def _addfileindir(self, filename, status):
443 def _addfileindir(self, filename, status):
444 """Add a file in this directory as a direct child."""
444 """Add a file in this directory as a direct child."""
445 self.files.append((filename, status))
445 self.files.append((filename, status))
446
446
447 def addfile(self, filename, status):
447 def addfile(self, filename, status):
448 """
448 """
449 Add a file to this directory or to its direct parent directory.
449 Add a file to this directory or to its direct parent directory.
450
450
451 If the file is not direct child of this directory, we traverse to the
451 If the file is not direct child of this directory, we traverse to the
452 directory of which this file is a direct child of and add the file
452 directory of which this file is a direct child of and add the file
453 there.
453 there.
454 """
454 """
455
455
456 # the filename contains a path separator, it means it's not the direct
456 # the filename contains a path separator, it means it's not the direct
457 # child of this directory
457 # child of this directory
458 if '/' in filename:
458 if '/' in filename:
459 subdir, filep = filename.split('/', 1)
459 subdir, filep = filename.split('/', 1)
460
460
461 # does the dirnode object for subdir exists
461 # does the dirnode object for subdir exists
462 if subdir not in self.subdirs:
462 if subdir not in self.subdirs:
463 subdirpath = pathutil.join(self.path, subdir)
463 subdirpath = pathutil.join(self.path, subdir)
464 self.subdirs[subdir] = dirnode(subdirpath)
464 self.subdirs[subdir] = dirnode(subdirpath)
465
465
466 # try adding the file in subdir
466 # try adding the file in subdir
467 self.subdirs[subdir].addfile(filep, status)
467 self.subdirs[subdir].addfile(filep, status)
468
468
469 else:
469 else:
470 self._addfileindir(filename, status)
470 self._addfileindir(filename, status)
471
471
472 if status not in self.statuses:
472 if status not in self.statuses:
473 self.statuses.add(status)
473 self.statuses.add(status)
474
474
475 def iterfilepaths(self):
475 def iterfilepaths(self):
476 """Yield (status, path) for files directly under this directory."""
476 """Yield (status, path) for files directly under this directory."""
477 for f, st in self.files:
477 for f, st in self.files:
478 yield st, pathutil.join(self.path, f)
478 yield st, pathutil.join(self.path, f)
479
479
480 def tersewalk(self, terseargs):
480 def tersewalk(self, terseargs):
481 """
481 """
482 Yield (status, path) obtained by processing the status of this
482 Yield (status, path) obtained by processing the status of this
483 dirnode.
483 dirnode.
484
484
485 terseargs is the string of arguments passed by the user with `--terse`
485 terseargs is the string of arguments passed by the user with `--terse`
486 flag.
486 flag.
487
487
488 Following are the cases which can happen:
488 Following are the cases which can happen:
489
489
490 1) All the files in the directory (including all the files in its
490 1) All the files in the directory (including all the files in its
491 subdirectories) share the same status and the user has asked us to terse
491 subdirectories) share the same status and the user has asked us to terse
492 that status. -> yield (status, dirpath). dirpath will end in '/'.
492 that status. -> yield (status, dirpath). dirpath will end in '/'.
493
493
494 2) Otherwise, we do following:
494 2) Otherwise, we do following:
495
495
496 a) Yield (status, filepath) for all the files which are in this
496 a) Yield (status, filepath) for all the files which are in this
497 directory (only the ones in this directory, not the subdirs)
497 directory (only the ones in this directory, not the subdirs)
498
498
499 b) Recurse the function on all the subdirectories of this
499 b) Recurse the function on all the subdirectories of this
500 directory
500 directory
501 """
501 """
502
502
503 if len(self.statuses) == 1:
503 if len(self.statuses) == 1:
504 onlyst = self.statuses.pop()
504 onlyst = self.statuses.pop()
505
505
506 # Making sure we terse only when the status abbreviation is
506 # Making sure we terse only when the status abbreviation is
507 # passed as terse argument
507 # passed as terse argument
508 if onlyst in terseargs:
508 if onlyst in terseargs:
509 yield onlyst, self.path + '/'
509 yield onlyst, self.path + '/'
510 return
510 return
511
511
512 # add the files to status list
512 # add the files to status list
513 for st, fpath in self.iterfilepaths():
513 for st, fpath in self.iterfilepaths():
514 yield st, fpath
514 yield st, fpath
515
515
516 #recurse on the subdirs
516 #recurse on the subdirs
517 for dirobj in self.subdirs.values():
517 for dirobj in self.subdirs.values():
518 for st, fpath in dirobj.tersewalk(terseargs):
518 for st, fpath in dirobj.tersewalk(terseargs):
519 yield st, fpath
519 yield st, fpath
520
520
521 def tersedir(statuslist, terseargs):
521 def tersedir(statuslist, terseargs):
522 """
522 """
523 Terse the status if all the files in a directory shares the same status.
523 Terse the status if all the files in a directory shares the same status.
524
524
525 statuslist is scmutil.status() object which contains a list of files for
525 statuslist is scmutil.status() object which contains a list of files for
526 each status.
526 each status.
527 terseargs is string which is passed by the user as the argument to `--terse`
527 terseargs is string which is passed by the user as the argument to `--terse`
528 flag.
528 flag.
529
529
530 The function makes a tree of objects of dirnode class, and at each node it
530 The function makes a tree of objects of dirnode class, and at each node it
531 stores the information required to know whether we can terse a certain
531 stores the information required to know whether we can terse a certain
532 directory or not.
532 directory or not.
533 """
533 """
534 # the order matters here as that is used to produce final list
534 # the order matters here as that is used to produce final list
535 allst = ('m', 'a', 'r', 'd', 'u', 'i', 'c')
535 allst = ('m', 'a', 'r', 'd', 'u', 'i', 'c')
536
536
537 # checking the argument validity
537 # checking the argument validity
538 for s in pycompat.bytestr(terseargs):
538 for s in pycompat.bytestr(terseargs):
539 if s not in allst:
539 if s not in allst:
540 raise error.Abort(_("'%s' not recognized") % s)
540 raise error.Abort(_("'%s' not recognized") % s)
541
541
542 # creating a dirnode object for the root of the repo
542 # creating a dirnode object for the root of the repo
543 rootobj = dirnode('')
543 rootobj = dirnode('')
544 pstatus = ('modified', 'added', 'deleted', 'clean', 'unknown',
544 pstatus = ('modified', 'added', 'deleted', 'clean', 'unknown',
545 'ignored', 'removed')
545 'ignored', 'removed')
546
546
547 tersedict = {}
547 tersedict = {}
548 for attrname in pstatus:
548 for attrname in pstatus:
549 statuschar = attrname[0:1]
549 statuschar = attrname[0:1]
550 for f in getattr(statuslist, attrname):
550 for f in getattr(statuslist, attrname):
551 rootobj.addfile(f, statuschar)
551 rootobj.addfile(f, statuschar)
552 tersedict[statuschar] = []
552 tersedict[statuschar] = []
553
553
554 # we won't be tersing the root dir, so add files in it
554 # we won't be tersing the root dir, so add files in it
555 for st, fpath in rootobj.iterfilepaths():
555 for st, fpath in rootobj.iterfilepaths():
556 tersedict[st].append(fpath)
556 tersedict[st].append(fpath)
557
557
558 # process each sub-directory and build tersedict
558 # process each sub-directory and build tersedict
559 for subdir in rootobj.subdirs.values():
559 for subdir in rootobj.subdirs.values():
560 for st, f in subdir.tersewalk(terseargs):
560 for st, f in subdir.tersewalk(terseargs):
561 tersedict[st].append(f)
561 tersedict[st].append(f)
562
562
563 tersedlist = []
563 tersedlist = []
564 for st in allst:
564 for st in allst:
565 tersedict[st].sort()
565 tersedict[st].sort()
566 tersedlist.append(tersedict[st])
566 tersedlist.append(tersedict[st])
567
567
568 return tersedlist
568 return tersedlist
569
569
570 def _commentlines(raw):
570 def _commentlines(raw):
571 '''Surround lineswith a comment char and a new line'''
571 '''Surround lineswith a comment char and a new line'''
572 lines = raw.splitlines()
572 lines = raw.splitlines()
573 commentedlines = ['# %s' % line for line in lines]
573 commentedlines = ['# %s' % line for line in lines]
574 return '\n'.join(commentedlines) + '\n'
574 return '\n'.join(commentedlines) + '\n'
575
575
576 def _conflictsmsg(repo):
576 def _conflictsmsg(repo):
577 mergestate = mergemod.mergestate.read(repo)
577 mergestate = mergemod.mergestate.read(repo)
578 if not mergestate.active():
578 if not mergestate.active():
579 return
579 return
580
580
581 m = scmutil.match(repo[None])
581 m = scmutil.match(repo[None])
582 unresolvedlist = [f for f in mergestate.unresolved() if m(f)]
582 unresolvedlist = [f for f in mergestate.unresolved() if m(f)]
583 if unresolvedlist:
583 if unresolvedlist:
584 mergeliststr = '\n'.join(
584 mergeliststr = '\n'.join(
585 [' %s' % util.pathto(repo.root, encoding.getcwd(), path)
585 [' %s' % util.pathto(repo.root, encoding.getcwd(), path)
586 for path in sorted(unresolvedlist)])
586 for path in sorted(unresolvedlist)])
587 msg = _('''Unresolved merge conflicts:
587 msg = _('''Unresolved merge conflicts:
588
588
589 %s
589 %s
590
590
591 To mark files as resolved: hg resolve --mark FILE''') % mergeliststr
591 To mark files as resolved: hg resolve --mark FILE''') % mergeliststr
592 else:
592 else:
593 msg = _('No unresolved merge conflicts.')
593 msg = _('No unresolved merge conflicts.')
594
594
595 return _commentlines(msg)
595 return _commentlines(msg)
596
596
597 def _helpmessage(continuecmd, abortcmd):
597 def _helpmessage(continuecmd, abortcmd):
598 msg = _('To continue: %s\n'
598 msg = _('To continue: %s\n'
599 'To abort: %s') % (continuecmd, abortcmd)
599 'To abort: %s') % (continuecmd, abortcmd)
600 return _commentlines(msg)
600 return _commentlines(msg)
601
601
602 def _rebasemsg():
602 def _rebasemsg():
603 return _helpmessage('hg rebase --continue', 'hg rebase --abort')
603 return _helpmessage('hg rebase --continue', 'hg rebase --abort')
604
604
605 def _histeditmsg():
605 def _histeditmsg():
606 return _helpmessage('hg histedit --continue', 'hg histedit --abort')
606 return _helpmessage('hg histedit --continue', 'hg histedit --abort')
607
607
608 def _unshelvemsg():
608 def _unshelvemsg():
609 return _helpmessage('hg unshelve --continue', 'hg unshelve --abort')
609 return _helpmessage('hg unshelve --continue', 'hg unshelve --abort')
610
610
611 def _graftmsg():
611 def _graftmsg():
612 return _helpmessage('hg graft --continue', 'hg graft --abort')
612 return _helpmessage('hg graft --continue', 'hg graft --abort')
613
613
614 def _mergemsg():
614 def _mergemsg():
615 return _helpmessage('hg commit', 'hg merge --abort')
615 return _helpmessage('hg commit', 'hg merge --abort')
616
616
617 def _bisectmsg():
617 def _bisectmsg():
618 msg = _('To mark the changeset good: hg bisect --good\n'
618 msg = _('To mark the changeset good: hg bisect --good\n'
619 'To mark the changeset bad: hg bisect --bad\n'
619 'To mark the changeset bad: hg bisect --bad\n'
620 'To abort: hg bisect --reset\n')
620 'To abort: hg bisect --reset\n')
621 return _commentlines(msg)
621 return _commentlines(msg)
622
622
623 def fileexistspredicate(filename):
623 def fileexistspredicate(filename):
624 return lambda repo: repo.vfs.exists(filename)
624 return lambda repo: repo.vfs.exists(filename)
625
625
626 def _mergepredicate(repo):
626 def _mergepredicate(repo):
627 return len(repo[None].parents()) > 1
627 return len(repo[None].parents()) > 1
628
628
629 STATES = (
629 STATES = (
630 # (state, predicate to detect states, helpful message function)
630 # (state, predicate to detect states, helpful message function)
631 ('histedit', fileexistspredicate('histedit-state'), _histeditmsg),
631 ('histedit', fileexistspredicate('histedit-state'), _histeditmsg),
632 ('bisect', fileexistspredicate('bisect.state'), _bisectmsg),
632 ('bisect', fileexistspredicate('bisect.state'), _bisectmsg),
633 ('graft', fileexistspredicate('graftstate'), _graftmsg),
633 ('graft', fileexistspredicate('graftstate'), _graftmsg),
634 ('unshelve', fileexistspredicate('shelvedstate'), _unshelvemsg),
634 ('unshelve', fileexistspredicate('shelvedstate'), _unshelvemsg),
635 ('rebase', fileexistspredicate('rebasestate'), _rebasemsg),
635 ('rebase', fileexistspredicate('rebasestate'), _rebasemsg),
636 # The merge state is part of a list that will be iterated over.
636 # The merge state is part of a list that will be iterated over.
637 # They need to be last because some of the other unfinished states may also
637 # They need to be last because some of the other unfinished states may also
638 # be in a merge or update state (eg. rebase, histedit, graft, etc).
638 # be in a merge or update state (eg. rebase, histedit, graft, etc).
639 # We want those to have priority.
639 # We want those to have priority.
640 ('merge', _mergepredicate, _mergemsg),
640 ('merge', _mergepredicate, _mergemsg),
641 )
641 )
642
642
643 def _getrepostate(repo):
643 def _getrepostate(repo):
644 # experimental config: commands.status.skipstates
644 # experimental config: commands.status.skipstates
645 skip = set(repo.ui.configlist('commands', 'status.skipstates'))
645 skip = set(repo.ui.configlist('commands', 'status.skipstates'))
646 for state, statedetectionpredicate, msgfn in STATES:
646 for state, statedetectionpredicate, msgfn in STATES:
647 if state in skip:
647 if state in skip:
648 continue
648 continue
649 if statedetectionpredicate(repo):
649 if statedetectionpredicate(repo):
650 return (state, statedetectionpredicate, msgfn)
650 return (state, statedetectionpredicate, msgfn)
651
651
652 def morestatus(repo, fm):
652 def morestatus(repo, fm):
653 statetuple = _getrepostate(repo)
653 statetuple = _getrepostate(repo)
654 label = 'status.morestatus'
654 label = 'status.morestatus'
655 if statetuple:
655 if statetuple:
656 state, statedetectionpredicate, helpfulmsg = statetuple
656 state, statedetectionpredicate, helpfulmsg = statetuple
657 statemsg = _('The repository is in an unfinished *%s* state.') % state
657 statemsg = _('The repository is in an unfinished *%s* state.') % state
658 fm.plain('%s\n' % _commentlines(statemsg), label=label)
658 fm.plain('%s\n' % _commentlines(statemsg), label=label)
659 conmsg = _conflictsmsg(repo)
659 conmsg = _conflictsmsg(repo)
660 if conmsg:
660 if conmsg:
661 fm.plain('%s\n' % conmsg, label=label)
661 fm.plain('%s\n' % conmsg, label=label)
662 if helpfulmsg:
662 if helpfulmsg:
663 helpmsg = helpfulmsg()
663 helpmsg = helpfulmsg()
664 fm.plain('%s\n' % helpmsg, label=label)
664 fm.plain('%s\n' % helpmsg, label=label)
665
665
666 def findpossible(cmd, table, strict=False):
666 def findpossible(cmd, table, strict=False):
667 """
667 """
668 Return cmd -> (aliases, command table entry)
668 Return cmd -> (aliases, command table entry)
669 for each matching command.
669 for each matching command.
670 Return debug commands (or their aliases) only if no normal command matches.
670 Return debug commands (or their aliases) only if no normal command matches.
671 """
671 """
672 choice = {}
672 choice = {}
673 debugchoice = {}
673 debugchoice = {}
674
674
675 if cmd in table:
675 if cmd in table:
676 # short-circuit exact matches, "log" alias beats "log|history"
676 # short-circuit exact matches, "log" alias beats "log|history"
677 keys = [cmd]
677 keys = [cmd]
678 else:
678 else:
679 keys = table.keys()
679 keys = table.keys()
680
680
681 allcmds = []
681 allcmds = []
682 for e in keys:
682 for e in keys:
683 aliases = parsealiases(e)
683 aliases = parsealiases(e)
684 allcmds.extend(aliases)
684 allcmds.extend(aliases)
685 found = None
685 found = None
686 if cmd in aliases:
686 if cmd in aliases:
687 found = cmd
687 found = cmd
688 elif not strict:
688 elif not strict:
689 for a in aliases:
689 for a in aliases:
690 if a.startswith(cmd):
690 if a.startswith(cmd):
691 found = a
691 found = a
692 break
692 break
693 if found is not None:
693 if found is not None:
694 if aliases[0].startswith("debug") or found.startswith("debug"):
694 if aliases[0].startswith("debug") or found.startswith("debug"):
695 debugchoice[found] = (aliases, table[e])
695 debugchoice[found] = (aliases, table[e])
696 else:
696 else:
697 choice[found] = (aliases, table[e])
697 choice[found] = (aliases, table[e])
698
698
699 if not choice and debugchoice:
699 if not choice and debugchoice:
700 choice = debugchoice
700 choice = debugchoice
701
701
702 return choice, allcmds
702 return choice, allcmds
703
703
704 def findcmd(cmd, table, strict=True):
704 def findcmd(cmd, table, strict=True):
705 """Return (aliases, command table entry) for command string."""
705 """Return (aliases, command table entry) for command string."""
706 choice, allcmds = findpossible(cmd, table, strict)
706 choice, allcmds = findpossible(cmd, table, strict)
707
707
708 if cmd in choice:
708 if cmd in choice:
709 return choice[cmd]
709 return choice[cmd]
710
710
711 if len(choice) > 1:
711 if len(choice) > 1:
712 clist = sorted(choice)
712 clist = sorted(choice)
713 raise error.AmbiguousCommand(cmd, clist)
713 raise error.AmbiguousCommand(cmd, clist)
714
714
715 if choice:
715 if choice:
716 return list(choice.values())[0]
716 return list(choice.values())[0]
717
717
718 raise error.UnknownCommand(cmd, allcmds)
718 raise error.UnknownCommand(cmd, allcmds)
719
719
720 def changebranch(ui, repo, revs, label):
720 def changebranch(ui, repo, revs, label):
721 """ Change the branch name of given revs to label """
721 """ Change the branch name of given revs to label """
722
722
723 with repo.wlock(), repo.lock(), repo.transaction('branches'):
723 with repo.wlock(), repo.lock(), repo.transaction('branches'):
724 # abort in case of uncommitted merge or dirty wdir
724 # abort in case of uncommitted merge or dirty wdir
725 bailifchanged(repo)
725 bailifchanged(repo)
726 revs = scmutil.revrange(repo, revs)
726 revs = scmutil.revrange(repo, revs)
727 if not revs:
727 if not revs:
728 raise error.Abort("empty revision set")
728 raise error.Abort("empty revision set")
729 roots = repo.revs('roots(%ld)', revs)
729 roots = repo.revs('roots(%ld)', revs)
730 if len(roots) > 1:
730 if len(roots) > 1:
731 raise error.Abort(_("cannot change branch of non-linear revisions"))
731 raise error.Abort(_("cannot change branch of non-linear revisions"))
732 rewriteutil.precheck(repo, revs, 'change branch of')
732 rewriteutil.precheck(repo, revs, 'change branch of')
733
733
734 root = repo[roots.first()]
734 root = repo[roots.first()]
735 rpb = {parent.branch() for parent in root.parents()}
735 rpb = {parent.branch() for parent in root.parents()}
736 if label not in rpb and label in repo.branchmap():
736 if label not in rpb and label in repo.branchmap():
737 raise error.Abort(_("a branch of the same name already exists"))
737 raise error.Abort(_("a branch of the same name already exists"))
738
738
739 if repo.revs('obsolete() and %ld', revs):
739 if repo.revs('obsolete() and %ld', revs):
740 raise error.Abort(_("cannot change branch of a obsolete changeset"))
740 raise error.Abort(_("cannot change branch of a obsolete changeset"))
741
741
742 # make sure only topological heads
742 # make sure only topological heads
743 if repo.revs('heads(%ld) - head()', revs):
743 if repo.revs('heads(%ld) - head()', revs):
744 raise error.Abort(_("cannot change branch in middle of a stack"))
744 raise error.Abort(_("cannot change branch in middle of a stack"))
745
745
746 replacements = {}
746 replacements = {}
747 # avoid import cycle mercurial.cmdutil -> mercurial.context ->
747 # avoid import cycle mercurial.cmdutil -> mercurial.context ->
748 # mercurial.subrepo -> mercurial.cmdutil
748 # mercurial.subrepo -> mercurial.cmdutil
749 from . import context
749 from . import context
750 for rev in revs:
750 for rev in revs:
751 ctx = repo[rev]
751 ctx = repo[rev]
752 oldbranch = ctx.branch()
752 oldbranch = ctx.branch()
753 # check if ctx has same branch
753 # check if ctx has same branch
754 if oldbranch == label:
754 if oldbranch == label:
755 continue
755 continue
756
756
757 def filectxfn(repo, newctx, path):
757 def filectxfn(repo, newctx, path):
758 try:
758 try:
759 return ctx[path]
759 return ctx[path]
760 except error.ManifestLookupError:
760 except error.ManifestLookupError:
761 return None
761 return None
762
762
763 ui.debug("changing branch of '%s' from '%s' to '%s'\n"
763 ui.debug("changing branch of '%s' from '%s' to '%s'\n"
764 % (hex(ctx.node()), oldbranch, label))
764 % (hex(ctx.node()), oldbranch, label))
765 extra = ctx.extra()
765 extra = ctx.extra()
766 extra['branch_change'] = hex(ctx.node())
766 extra['branch_change'] = hex(ctx.node())
767 # While changing branch of set of linear commits, make sure that
767 # While changing branch of set of linear commits, make sure that
768 # we base our commits on new parent rather than old parent which
768 # we base our commits on new parent rather than old parent which
769 # was obsoleted while changing the branch
769 # was obsoleted while changing the branch
770 p1 = ctx.p1().node()
770 p1 = ctx.p1().node()
771 p2 = ctx.p2().node()
771 p2 = ctx.p2().node()
772 if p1 in replacements:
772 if p1 in replacements:
773 p1 = replacements[p1][0]
773 p1 = replacements[p1][0]
774 if p2 in replacements:
774 if p2 in replacements:
775 p2 = replacements[p2][0]
775 p2 = replacements[p2][0]
776
776
777 mc = context.memctx(repo, (p1, p2),
777 mc = context.memctx(repo, (p1, p2),
778 ctx.description(),
778 ctx.description(),
779 ctx.files(),
779 ctx.files(),
780 filectxfn,
780 filectxfn,
781 user=ctx.user(),
781 user=ctx.user(),
782 date=ctx.date(),
782 date=ctx.date(),
783 extra=extra,
783 extra=extra,
784 branch=label)
784 branch=label)
785
785
786 newnode = repo.commitctx(mc)
786 newnode = repo.commitctx(mc)
787 replacements[ctx.node()] = (newnode,)
787 replacements[ctx.node()] = (newnode,)
788 ui.debug('new node id is %s\n' % hex(newnode))
788 ui.debug('new node id is %s\n' % hex(newnode))
789
789
790 # create obsmarkers and move bookmarks
790 # create obsmarkers and move bookmarks
791 scmutil.cleanupnodes(repo, replacements, 'branch-change', fixphase=True)
791 scmutil.cleanupnodes(repo, replacements, 'branch-change', fixphase=True)
792
792
793 # move the working copy too
793 # move the working copy too
794 wctx = repo[None]
794 wctx = repo[None]
795 # in-progress merge is a bit too complex for now.
795 # in-progress merge is a bit too complex for now.
796 if len(wctx.parents()) == 1:
796 if len(wctx.parents()) == 1:
797 newid = replacements.get(wctx.p1().node())
797 newid = replacements.get(wctx.p1().node())
798 if newid is not None:
798 if newid is not None:
799 # avoid import cycle mercurial.cmdutil -> mercurial.hg ->
799 # avoid import cycle mercurial.cmdutil -> mercurial.hg ->
800 # mercurial.cmdutil
800 # mercurial.cmdutil
801 from . import hg
801 from . import hg
802 hg.update(repo, newid[0], quietempty=True)
802 hg.update(repo, newid[0], quietempty=True)
803
803
804 ui.status(_("changed branch on %d changesets\n") % len(replacements))
804 ui.status(_("changed branch on %d changesets\n") % len(replacements))
805
805
806 def findrepo(p):
806 def findrepo(p):
807 while not os.path.isdir(os.path.join(p, ".hg")):
807 while not os.path.isdir(os.path.join(p, ".hg")):
808 oldp, p = p, os.path.dirname(p)
808 oldp, p = p, os.path.dirname(p)
809 if p == oldp:
809 if p == oldp:
810 return None
810 return None
811
811
812 return p
812 return p
813
813
814 def bailifchanged(repo, merge=True, hint=None):
814 def bailifchanged(repo, merge=True, hint=None):
815 """ enforce the precondition that working directory must be clean.
815 """ enforce the precondition that working directory must be clean.
816
816
817 'merge' can be set to false if a pending uncommitted merge should be
817 'merge' can be set to false if a pending uncommitted merge should be
818 ignored (such as when 'update --check' runs).
818 ignored (such as when 'update --check' runs).
819
819
820 'hint' is the usual hint given to Abort exception.
820 'hint' is the usual hint given to Abort exception.
821 """
821 """
822
822
823 if merge and repo.dirstate.p2() != nullid:
823 if merge and repo.dirstate.p2() != nullid:
824 raise error.Abort(_('outstanding uncommitted merge'), hint=hint)
824 raise error.Abort(_('outstanding uncommitted merge'), hint=hint)
825 modified, added, removed, deleted = repo.status()[:4]
825 modified, added, removed, deleted = repo.status()[:4]
826 if modified or added or removed or deleted:
826 if modified or added or removed or deleted:
827 raise error.Abort(_('uncommitted changes'), hint=hint)
827 raise error.Abort(_('uncommitted changes'), hint=hint)
828 ctx = repo[None]
828 ctx = repo[None]
829 for s in sorted(ctx.substate):
829 for s in sorted(ctx.substate):
830 ctx.sub(s).bailifchanged(hint=hint)
830 ctx.sub(s).bailifchanged(hint=hint)
831
831
832 def logmessage(ui, opts):
832 def logmessage(ui, opts):
833 """ get the log message according to -m and -l option """
833 """ get the log message according to -m and -l option """
834 message = opts.get('message')
834 message = opts.get('message')
835 logfile = opts.get('logfile')
835 logfile = opts.get('logfile')
836
836
837 if message and logfile:
837 if message and logfile:
838 raise error.Abort(_('options --message and --logfile are mutually '
838 raise error.Abort(_('options --message and --logfile are mutually '
839 'exclusive'))
839 'exclusive'))
840 if not message and logfile:
840 if not message and logfile:
841 try:
841 try:
842 if isstdiofilename(logfile):
842 if isstdiofilename(logfile):
843 message = ui.fin.read()
843 message = ui.fin.read()
844 else:
844 else:
845 message = '\n'.join(util.readfile(logfile).splitlines())
845 message = '\n'.join(util.readfile(logfile).splitlines())
846 except IOError as inst:
846 except IOError as inst:
847 raise error.Abort(_("can't read commit message '%s': %s") %
847 raise error.Abort(_("can't read commit message '%s': %s") %
848 (logfile, encoding.strtolocal(inst.strerror)))
848 (logfile, encoding.strtolocal(inst.strerror)))
849 return message
849 return message
850
850
851 def mergeeditform(ctxorbool, baseformname):
851 def mergeeditform(ctxorbool, baseformname):
852 """return appropriate editform name (referencing a committemplate)
852 """return appropriate editform name (referencing a committemplate)
853
853
854 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
854 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
855 merging is committed.
855 merging is committed.
856
856
857 This returns baseformname with '.merge' appended if it is a merge,
857 This returns baseformname with '.merge' appended if it is a merge,
858 otherwise '.normal' is appended.
858 otherwise '.normal' is appended.
859 """
859 """
860 if isinstance(ctxorbool, bool):
860 if isinstance(ctxorbool, bool):
861 if ctxorbool:
861 if ctxorbool:
862 return baseformname + ".merge"
862 return baseformname + ".merge"
863 elif len(ctxorbool.parents()) > 1:
863 elif len(ctxorbool.parents()) > 1:
864 return baseformname + ".merge"
864 return baseformname + ".merge"
865
865
866 return baseformname + ".normal"
866 return baseformname + ".normal"
867
867
868 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
868 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
869 editform='', **opts):
869 editform='', **opts):
870 """get appropriate commit message editor according to '--edit' option
870 """get appropriate commit message editor according to '--edit' option
871
871
872 'finishdesc' is a function to be called with edited commit message
872 'finishdesc' is a function to be called with edited commit message
873 (= 'description' of the new changeset) just after editing, but
873 (= 'description' of the new changeset) just after editing, but
874 before checking empty-ness. It should return actual text to be
874 before checking empty-ness. It should return actual text to be
875 stored into history. This allows to change description before
875 stored into history. This allows to change description before
876 storing.
876 storing.
877
877
878 'extramsg' is a extra message to be shown in the editor instead of
878 'extramsg' is a extra message to be shown in the editor instead of
879 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
879 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
880 is automatically added.
880 is automatically added.
881
881
882 'editform' is a dot-separated list of names, to distinguish
882 'editform' is a dot-separated list of names, to distinguish
883 the purpose of commit text editing.
883 the purpose of commit text editing.
884
884
885 'getcommiteditor' returns 'commitforceeditor' regardless of
885 'getcommiteditor' returns 'commitforceeditor' regardless of
886 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
886 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
887 they are specific for usage in MQ.
887 they are specific for usage in MQ.
888 """
888 """
889 if edit or finishdesc or extramsg:
889 if edit or finishdesc or extramsg:
890 return lambda r, c, s: commitforceeditor(r, c, s,
890 return lambda r, c, s: commitforceeditor(r, c, s,
891 finishdesc=finishdesc,
891 finishdesc=finishdesc,
892 extramsg=extramsg,
892 extramsg=extramsg,
893 editform=editform)
893 editform=editform)
894 elif editform:
894 elif editform:
895 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
895 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
896 else:
896 else:
897 return commiteditor
897 return commiteditor
898
898
899 def _escapecommandtemplate(tmpl):
899 def _escapecommandtemplate(tmpl):
900 parts = []
900 parts = []
901 for typ, start, end in templater.scantemplate(tmpl, raw=True):
901 for typ, start, end in templater.scantemplate(tmpl, raw=True):
902 if typ == b'string':
902 if typ == b'string':
903 parts.append(stringutil.escapestr(tmpl[start:end]))
903 parts.append(stringutil.escapestr(tmpl[start:end]))
904 else:
904 else:
905 parts.append(tmpl[start:end])
905 parts.append(tmpl[start:end])
906 return b''.join(parts)
906 return b''.join(parts)
907
907
908 def rendercommandtemplate(ui, tmpl, props):
908 def rendercommandtemplate(ui, tmpl, props):
909 r"""Expand a literal template 'tmpl' in a way suitable for command line
909 r"""Expand a literal template 'tmpl' in a way suitable for command line
910
910
911 '\' in outermost string is not taken as an escape character because it
911 '\' in outermost string is not taken as an escape character because it
912 is a directory separator on Windows.
912 is a directory separator on Windows.
913
913
914 >>> from . import ui as uimod
914 >>> from . import ui as uimod
915 >>> ui = uimod.ui()
915 >>> ui = uimod.ui()
916 >>> rendercommandtemplate(ui, b'c:\\{path}', {b'path': b'foo'})
916 >>> rendercommandtemplate(ui, b'c:\\{path}', {b'path': b'foo'})
917 'c:\\foo'
917 'c:\\foo'
918 >>> rendercommandtemplate(ui, b'{"c:\\{path}"}', {'path': b'foo'})
918 >>> rendercommandtemplate(ui, b'{"c:\\{path}"}', {'path': b'foo'})
919 'c:{path}'
919 'c:{path}'
920 """
920 """
921 if not tmpl:
921 if not tmpl:
922 return tmpl
922 return tmpl
923 t = formatter.maketemplater(ui, _escapecommandtemplate(tmpl))
923 t = formatter.maketemplater(ui, _escapecommandtemplate(tmpl))
924 return t.renderdefault(props)
924 return t.renderdefault(props)
925
925
926 def rendertemplate(ctx, tmpl, props=None):
926 def rendertemplate(ctx, tmpl, props=None):
927 """Expand a literal template 'tmpl' byte-string against one changeset
927 """Expand a literal template 'tmpl' byte-string against one changeset
928
928
929 Each props item must be a stringify-able value or a callable returning
929 Each props item must be a stringify-able value or a callable returning
930 such value, i.e. no bare list nor dict should be passed.
930 such value, i.e. no bare list nor dict should be passed.
931 """
931 """
932 repo = ctx.repo()
932 repo = ctx.repo()
933 tres = formatter.templateresources(repo.ui, repo)
933 tres = formatter.templateresources(repo.ui, repo)
934 t = formatter.maketemplater(repo.ui, tmpl, defaults=templatekw.keywords,
934 t = formatter.maketemplater(repo.ui, tmpl, defaults=templatekw.keywords,
935 resources=tres)
935 resources=tres)
936 mapping = {'ctx': ctx}
936 mapping = {'ctx': ctx}
937 if props:
937 if props:
938 mapping.update(props)
938 mapping.update(props)
939 return t.renderdefault(mapping)
939 return t.renderdefault(mapping)
940
940
941 def _buildfntemplate(pat, total=None, seqno=None, revwidth=None, pathname=None):
941 def _buildfntemplate(pat, total=None, seqno=None, revwidth=None, pathname=None):
942 r"""Convert old-style filename format string to template string
942 r"""Convert old-style filename format string to template string
943
943
944 >>> _buildfntemplate(b'foo-%b-%n.patch', seqno=0)
944 >>> _buildfntemplate(b'foo-%b-%n.patch', seqno=0)
945 'foo-{reporoot|basename}-{seqno}.patch'
945 'foo-{reporoot|basename}-{seqno}.patch'
946 >>> _buildfntemplate(b'%R{tags % "{tag}"}%H')
946 >>> _buildfntemplate(b'%R{tags % "{tag}"}%H')
947 '{rev}{tags % "{tag}"}{node}'
947 '{rev}{tags % "{tag}"}{node}'
948
948
949 '\' in outermost strings has to be escaped because it is a directory
949 '\' in outermost strings has to be escaped because it is a directory
950 separator on Windows:
950 separator on Windows:
951
951
952 >>> _buildfntemplate(b'c:\\tmp\\%R\\%n.patch', seqno=0)
952 >>> _buildfntemplate(b'c:\\tmp\\%R\\%n.patch', seqno=0)
953 'c:\\\\tmp\\\\{rev}\\\\{seqno}.patch'
953 'c:\\\\tmp\\\\{rev}\\\\{seqno}.patch'
954 >>> _buildfntemplate(b'\\\\foo\\bar.patch')
954 >>> _buildfntemplate(b'\\\\foo\\bar.patch')
955 '\\\\\\\\foo\\\\bar.patch'
955 '\\\\\\\\foo\\\\bar.patch'
956 >>> _buildfntemplate(b'\\{tags % "{tag}"}')
956 >>> _buildfntemplate(b'\\{tags % "{tag}"}')
957 '\\\\{tags % "{tag}"}'
957 '\\\\{tags % "{tag}"}'
958
958
959 but inner strings follow the template rules (i.e. '\' is taken as an
959 but inner strings follow the template rules (i.e. '\' is taken as an
960 escape character):
960 escape character):
961
961
962 >>> _buildfntemplate(br'{"c:\tmp"}', seqno=0)
962 >>> _buildfntemplate(br'{"c:\tmp"}', seqno=0)
963 '{"c:\\tmp"}'
963 '{"c:\\tmp"}'
964 """
964 """
965 expander = {
965 expander = {
966 b'H': b'{node}',
966 b'H': b'{node}',
967 b'R': b'{rev}',
967 b'R': b'{rev}',
968 b'h': b'{node|short}',
968 b'h': b'{node|short}',
969 b'm': br'{sub(r"[^\w]", "_", desc|firstline)}',
969 b'm': br'{sub(r"[^\w]", "_", desc|firstline)}',
970 b'r': b'{if(revwidth, pad(rev, revwidth, "0", left=True), rev)}',
970 b'r': b'{if(revwidth, pad(rev, revwidth, "0", left=True), rev)}',
971 b'%': b'%',
971 b'%': b'%',
972 b'b': b'{reporoot|basename}',
972 b'b': b'{reporoot|basename}',
973 }
973 }
974 if total is not None:
974 if total is not None:
975 expander[b'N'] = b'{total}'
975 expander[b'N'] = b'{total}'
976 if seqno is not None:
976 if seqno is not None:
977 expander[b'n'] = b'{seqno}'
977 expander[b'n'] = b'{seqno}'
978 if total is not None and seqno is not None:
978 if total is not None and seqno is not None:
979 expander[b'n'] = b'{pad(seqno, total|stringify|count, "0", left=True)}'
979 expander[b'n'] = b'{pad(seqno, total|stringify|count, "0", left=True)}'
980 if pathname is not None:
980 if pathname is not None:
981 expander[b's'] = b'{pathname|basename}'
981 expander[b's'] = b'{pathname|basename}'
982 expander[b'd'] = b'{if(pathname|dirname, pathname|dirname, ".")}'
982 expander[b'd'] = b'{if(pathname|dirname, pathname|dirname, ".")}'
983 expander[b'p'] = b'{pathname}'
983 expander[b'p'] = b'{pathname}'
984
984
985 newname = []
985 newname = []
986 for typ, start, end in templater.scantemplate(pat, raw=True):
986 for typ, start, end in templater.scantemplate(pat, raw=True):
987 if typ != b'string':
987 if typ != b'string':
988 newname.append(pat[start:end])
988 newname.append(pat[start:end])
989 continue
989 continue
990 i = start
990 i = start
991 while i < end:
991 while i < end:
992 n = pat.find(b'%', i, end)
992 n = pat.find(b'%', i, end)
993 if n < 0:
993 if n < 0:
994 newname.append(stringutil.escapestr(pat[i:end]))
994 newname.append(stringutil.escapestr(pat[i:end]))
995 break
995 break
996 newname.append(stringutil.escapestr(pat[i:n]))
996 newname.append(stringutil.escapestr(pat[i:n]))
997 if n + 2 > end:
997 if n + 2 > end:
998 raise error.Abort(_("incomplete format spec in output "
998 raise error.Abort(_("incomplete format spec in output "
999 "filename"))
999 "filename"))
1000 c = pat[n + 1:n + 2]
1000 c = pat[n + 1:n + 2]
1001 i = n + 2
1001 i = n + 2
1002 try:
1002 try:
1003 newname.append(expander[c])
1003 newname.append(expander[c])
1004 except KeyError:
1004 except KeyError:
1005 raise error.Abort(_("invalid format spec '%%%s' in output "
1005 raise error.Abort(_("invalid format spec '%%%s' in output "
1006 "filename") % c)
1006 "filename") % c)
1007 return ''.join(newname)
1007 return ''.join(newname)
1008
1008
1009 def makefilename(ctx, pat, **props):
1009 def makefilename(ctx, pat, **props):
1010 if not pat:
1010 if not pat:
1011 return pat
1011 return pat
1012 tmpl = _buildfntemplate(pat, **props)
1012 tmpl = _buildfntemplate(pat, **props)
1013 # BUG: alias expansion shouldn't be made against template fragments
1013 # BUG: alias expansion shouldn't be made against template fragments
1014 # rewritten from %-format strings, but we have no easy way to partially
1014 # rewritten from %-format strings, but we have no easy way to partially
1015 # disable the expansion.
1015 # disable the expansion.
1016 return rendertemplate(ctx, tmpl, pycompat.byteskwargs(props))
1016 return rendertemplate(ctx, tmpl, pycompat.byteskwargs(props))
1017
1017
1018 def isstdiofilename(pat):
1018 def isstdiofilename(pat):
1019 """True if the given pat looks like a filename denoting stdin/stdout"""
1019 """True if the given pat looks like a filename denoting stdin/stdout"""
1020 return not pat or pat == '-'
1020 return not pat or pat == '-'
1021
1021
1022 class _unclosablefile(object):
1022 class _unclosablefile(object):
1023 def __init__(self, fp):
1023 def __init__(self, fp):
1024 self._fp = fp
1024 self._fp = fp
1025
1025
1026 def close(self):
1026 def close(self):
1027 pass
1027 pass
1028
1028
1029 def __iter__(self):
1029 def __iter__(self):
1030 return iter(self._fp)
1030 return iter(self._fp)
1031
1031
1032 def __getattr__(self, attr):
1032 def __getattr__(self, attr):
1033 return getattr(self._fp, attr)
1033 return getattr(self._fp, attr)
1034
1034
1035 def __enter__(self):
1035 def __enter__(self):
1036 return self
1036 return self
1037
1037
1038 def __exit__(self, exc_type, exc_value, exc_tb):
1038 def __exit__(self, exc_type, exc_value, exc_tb):
1039 pass
1039 pass
1040
1040
1041 def makefileobj(ctx, pat, mode='wb', **props):
1041 def makefileobj(ctx, pat, mode='wb', **props):
1042 writable = mode not in ('r', 'rb')
1042 writable = mode not in ('r', 'rb')
1043
1043
1044 if isstdiofilename(pat):
1044 if isstdiofilename(pat):
1045 repo = ctx.repo()
1045 repo = ctx.repo()
1046 if writable:
1046 if writable:
1047 fp = repo.ui.fout
1047 fp = repo.ui.fout
1048 else:
1048 else:
1049 fp = repo.ui.fin
1049 fp = repo.ui.fin
1050 return _unclosablefile(fp)
1050 return _unclosablefile(fp)
1051 fn = makefilename(ctx, pat, **props)
1051 fn = makefilename(ctx, pat, **props)
1052 return open(fn, mode)
1052 return open(fn, mode)
1053
1053
1054 def openstorage(repo, cmd, file_, opts, returnrevlog=False):
1054 def openstorage(repo, cmd, file_, opts, returnrevlog=False):
1055 """opens the changelog, manifest, a filelog or a given revlog"""
1055 """opens the changelog, manifest, a filelog or a given revlog"""
1056 cl = opts['changelog']
1056 cl = opts['changelog']
1057 mf = opts['manifest']
1057 mf = opts['manifest']
1058 dir = opts['dir']
1058 dir = opts['dir']
1059 msg = None
1059 msg = None
1060 if cl and mf:
1060 if cl and mf:
1061 msg = _('cannot specify --changelog and --manifest at the same time')
1061 msg = _('cannot specify --changelog and --manifest at the same time')
1062 elif cl and dir:
1062 elif cl and dir:
1063 msg = _('cannot specify --changelog and --dir at the same time')
1063 msg = _('cannot specify --changelog and --dir at the same time')
1064 elif cl or mf or dir:
1064 elif cl or mf or dir:
1065 if file_:
1065 if file_:
1066 msg = _('cannot specify filename with --changelog or --manifest')
1066 msg = _('cannot specify filename with --changelog or --manifest')
1067 elif not repo:
1067 elif not repo:
1068 msg = _('cannot specify --changelog or --manifest or --dir '
1068 msg = _('cannot specify --changelog or --manifest or --dir '
1069 'without a repository')
1069 'without a repository')
1070 if msg:
1070 if msg:
1071 raise error.Abort(msg)
1071 raise error.Abort(msg)
1072
1072
1073 r = None
1073 r = None
1074 if repo:
1074 if repo:
1075 if cl:
1075 if cl:
1076 r = repo.unfiltered().changelog
1076 r = repo.unfiltered().changelog
1077 elif dir:
1077 elif dir:
1078 if 'treemanifest' not in repo.requirements:
1078 if 'treemanifest' not in repo.requirements:
1079 raise error.Abort(_("--dir can only be used on repos with "
1079 raise error.Abort(_("--dir can only be used on repos with "
1080 "treemanifest enabled"))
1080 "treemanifest enabled"))
1081 if not dir.endswith('/'):
1081 if not dir.endswith('/'):
1082 dir = dir + '/'
1082 dir = dir + '/'
1083 dirlog = repo.manifestlog.getstorage(dir)
1083 dirlog = repo.manifestlog.getstorage(dir)
1084 if len(dirlog):
1084 if len(dirlog):
1085 r = dirlog
1085 r = dirlog
1086 elif mf:
1086 elif mf:
1087 r = repo.manifestlog.getstorage(b'')
1087 r = repo.manifestlog.getstorage(b'')
1088 elif file_:
1088 elif file_:
1089 filelog = repo.file(file_)
1089 filelog = repo.file(file_)
1090 if len(filelog):
1090 if len(filelog):
1091 r = filelog
1091 r = filelog
1092
1092
1093 # Not all storage may be revlogs. If requested, try to return an actual
1093 # Not all storage may be revlogs. If requested, try to return an actual
1094 # revlog instance.
1094 # revlog instance.
1095 if returnrevlog:
1095 if returnrevlog:
1096 if isinstance(r, revlog.revlog):
1096 if isinstance(r, revlog.revlog):
1097 pass
1097 pass
1098 elif util.safehasattr(r, '_revlog'):
1098 elif util.safehasattr(r, '_revlog'):
1099 r = r._revlog
1099 r = r._revlog
1100 elif r is not None:
1100 elif r is not None:
1101 raise error.Abort(_('%r does not appear to be a revlog') % r)
1101 raise error.Abort(_('%r does not appear to be a revlog') % r)
1102
1102
1103 if not r:
1103 if not r:
1104 if not returnrevlog:
1104 if not returnrevlog:
1105 raise error.Abort(_('cannot give path to non-revlog'))
1105 raise error.Abort(_('cannot give path to non-revlog'))
1106
1106
1107 if not file_:
1107 if not file_:
1108 raise error.CommandError(cmd, _('invalid arguments'))
1108 raise error.CommandError(cmd, _('invalid arguments'))
1109 if not os.path.isfile(file_):
1109 if not os.path.isfile(file_):
1110 raise error.Abort(_("revlog '%s' not found") % file_)
1110 raise error.Abort(_("revlog '%s' not found") % file_)
1111 r = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False),
1111 r = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False),
1112 file_[:-2] + ".i")
1112 file_[:-2] + ".i")
1113 return r
1113 return r
1114
1114
1115 def openrevlog(repo, cmd, file_, opts):
1115 def openrevlog(repo, cmd, file_, opts):
1116 """Obtain a revlog backing storage of an item.
1116 """Obtain a revlog backing storage of an item.
1117
1117
1118 This is similar to ``openstorage()`` except it always returns a revlog.
1118 This is similar to ``openstorage()`` except it always returns a revlog.
1119
1119
1120 In most cases, a caller cares about the main storage object - not the
1120 In most cases, a caller cares about the main storage object - not the
1121 revlog backing it. Therefore, this function should only be used by code
1121 revlog backing it. Therefore, this function should only be used by code
1122 that needs to examine low-level revlog implementation details. e.g. debug
1122 that needs to examine low-level revlog implementation details. e.g. debug
1123 commands.
1123 commands.
1124 """
1124 """
1125 return openstorage(repo, cmd, file_, opts, returnrevlog=True)
1125 return openstorage(repo, cmd, file_, opts, returnrevlog=True)
1126
1126
1127 def copy(ui, repo, pats, opts, rename=False):
1127 def copy(ui, repo, pats, opts, rename=False):
1128 # called with the repo lock held
1128 # called with the repo lock held
1129 #
1129 #
1130 # hgsep => pathname that uses "/" to separate directories
1130 # hgsep => pathname that uses "/" to separate directories
1131 # ossep => pathname that uses os.sep to separate directories
1131 # ossep => pathname that uses os.sep to separate directories
1132 cwd = repo.getcwd()
1132 cwd = repo.getcwd()
1133 targets = {}
1133 targets = {}
1134 after = opts.get("after")
1134 after = opts.get("after")
1135 dryrun = opts.get("dry_run")
1135 dryrun = opts.get("dry_run")
1136 wctx = repo[None]
1136 wctx = repo[None]
1137
1137
1138 def walkpat(pat):
1138 def walkpat(pat):
1139 srcs = []
1139 srcs = []
1140 if after:
1140 if after:
1141 badstates = '?'
1141 badstates = '?'
1142 else:
1142 else:
1143 badstates = '?r'
1143 badstates = '?r'
1144 m = scmutil.match(wctx, [pat], opts, globbed=True)
1144 m = scmutil.match(wctx, [pat], opts, globbed=True)
1145 for abs in wctx.walk(m):
1145 for abs in wctx.walk(m):
1146 state = repo.dirstate[abs]
1146 state = repo.dirstate[abs]
1147 rel = m.rel(abs)
1147 rel = m.rel(abs)
1148 exact = m.exact(abs)
1148 exact = m.exact(abs)
1149 if state in badstates:
1149 if state in badstates:
1150 if exact and state == '?':
1150 if exact and state == '?':
1151 ui.warn(_('%s: not copying - file is not managed\n') % rel)
1151 ui.warn(_('%s: not copying - file is not managed\n') % rel)
1152 if exact and state == 'r':
1152 if exact and state == 'r':
1153 ui.warn(_('%s: not copying - file has been marked for'
1153 ui.warn(_('%s: not copying - file has been marked for'
1154 ' remove\n') % rel)
1154 ' remove\n') % rel)
1155 continue
1155 continue
1156 # abs: hgsep
1156 # abs: hgsep
1157 # rel: ossep
1157 # rel: ossep
1158 srcs.append((abs, rel, exact))
1158 srcs.append((abs, rel, exact))
1159 return srcs
1159 return srcs
1160
1160
1161 # abssrc: hgsep
1161 # abssrc: hgsep
1162 # relsrc: ossep
1162 # relsrc: ossep
1163 # otarget: ossep
1163 # otarget: ossep
1164 def copyfile(abssrc, relsrc, otarget, exact):
1164 def copyfile(abssrc, relsrc, otarget, exact):
1165 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
1165 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
1166 if '/' in abstarget:
1166 if '/' in abstarget:
1167 # We cannot normalize abstarget itself, this would prevent
1167 # We cannot normalize abstarget itself, this would prevent
1168 # case only renames, like a => A.
1168 # case only renames, like a => A.
1169 abspath, absname = abstarget.rsplit('/', 1)
1169 abspath, absname = abstarget.rsplit('/', 1)
1170 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
1170 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
1171 reltarget = repo.pathto(abstarget, cwd)
1171 reltarget = repo.pathto(abstarget, cwd)
1172 target = repo.wjoin(abstarget)
1172 target = repo.wjoin(abstarget)
1173 src = repo.wjoin(abssrc)
1173 src = repo.wjoin(abssrc)
1174 state = repo.dirstate[abstarget]
1174 state = repo.dirstate[abstarget]
1175
1175
1176 scmutil.checkportable(ui, abstarget)
1176 scmutil.checkportable(ui, abstarget)
1177
1177
1178 # check for collisions
1178 # check for collisions
1179 prevsrc = targets.get(abstarget)
1179 prevsrc = targets.get(abstarget)
1180 if prevsrc is not None:
1180 if prevsrc is not None:
1181 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
1181 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
1182 (reltarget, repo.pathto(abssrc, cwd),
1182 (reltarget, repo.pathto(abssrc, cwd),
1183 repo.pathto(prevsrc, cwd)))
1183 repo.pathto(prevsrc, cwd)))
1184 return True # report a failure
1184 return True # report a failure
1185
1185
1186 # check for overwrites
1186 # check for overwrites
1187 exists = os.path.lexists(target)
1187 exists = os.path.lexists(target)
1188 samefile = False
1188 samefile = False
1189 if exists and abssrc != abstarget:
1189 if exists and abssrc != abstarget:
1190 if (repo.dirstate.normalize(abssrc) ==
1190 if (repo.dirstate.normalize(abssrc) ==
1191 repo.dirstate.normalize(abstarget)):
1191 repo.dirstate.normalize(abstarget)):
1192 if not rename:
1192 if not rename:
1193 ui.warn(_("%s: can't copy - same file\n") % reltarget)
1193 ui.warn(_("%s: can't copy - same file\n") % reltarget)
1194 return True # report a failure
1194 return True # report a failure
1195 exists = False
1195 exists = False
1196 samefile = True
1196 samefile = True
1197
1197
1198 if not after and exists or after and state in 'mn':
1198 if not after and exists or after and state in 'mn':
1199 if not opts['force']:
1199 if not opts['force']:
1200 if state in 'mn':
1200 if state in 'mn':
1201 msg = _('%s: not overwriting - file already committed\n')
1201 msg = _('%s: not overwriting - file already committed\n')
1202 if after:
1202 if after:
1203 flags = '--after --force'
1203 flags = '--after --force'
1204 else:
1204 else:
1205 flags = '--force'
1205 flags = '--force'
1206 if rename:
1206 if rename:
1207 hint = _("('hg rename %s' to replace the file by "
1207 hint = _("('hg rename %s' to replace the file by "
1208 'recording a rename)\n') % flags
1208 'recording a rename)\n') % flags
1209 else:
1209 else:
1210 hint = _("('hg copy %s' to replace the file by "
1210 hint = _("('hg copy %s' to replace the file by "
1211 'recording a copy)\n') % flags
1211 'recording a copy)\n') % flags
1212 else:
1212 else:
1213 msg = _('%s: not overwriting - file exists\n')
1213 msg = _('%s: not overwriting - file exists\n')
1214 if rename:
1214 if rename:
1215 hint = _("('hg rename --after' to record the rename)\n")
1215 hint = _("('hg rename --after' to record the rename)\n")
1216 else:
1216 else:
1217 hint = _("('hg copy --after' to record the copy)\n")
1217 hint = _("('hg copy --after' to record the copy)\n")
1218 ui.warn(msg % reltarget)
1218 ui.warn(msg % reltarget)
1219 ui.warn(hint)
1219 ui.warn(hint)
1220 return True # report a failure
1220 return True # report a failure
1221
1221
1222 if after:
1222 if after:
1223 if not exists:
1223 if not exists:
1224 if rename:
1224 if rename:
1225 ui.warn(_('%s: not recording move - %s does not exist\n') %
1225 ui.warn(_('%s: not recording move - %s does not exist\n') %
1226 (relsrc, reltarget))
1226 (relsrc, reltarget))
1227 else:
1227 else:
1228 ui.warn(_('%s: not recording copy - %s does not exist\n') %
1228 ui.warn(_('%s: not recording copy - %s does not exist\n') %
1229 (relsrc, reltarget))
1229 (relsrc, reltarget))
1230 return True # report a failure
1230 return True # report a failure
1231 elif not dryrun:
1231 elif not dryrun:
1232 try:
1232 try:
1233 if exists:
1233 if exists:
1234 os.unlink(target)
1234 os.unlink(target)
1235 targetdir = os.path.dirname(target) or '.'
1235 targetdir = os.path.dirname(target) or '.'
1236 if not os.path.isdir(targetdir):
1236 if not os.path.isdir(targetdir):
1237 os.makedirs(targetdir)
1237 os.makedirs(targetdir)
1238 if samefile:
1238 if samefile:
1239 tmp = target + "~hgrename"
1239 tmp = target + "~hgrename"
1240 os.rename(src, tmp)
1240 os.rename(src, tmp)
1241 os.rename(tmp, target)
1241 os.rename(tmp, target)
1242 else:
1242 else:
1243 # Preserve stat info on renames, not on copies; this matches
1243 # Preserve stat info on renames, not on copies; this matches
1244 # Linux CLI behavior.
1244 # Linux CLI behavior.
1245 util.copyfile(src, target, copystat=rename)
1245 util.copyfile(src, target, copystat=rename)
1246 srcexists = True
1246 srcexists = True
1247 except IOError as inst:
1247 except IOError as inst:
1248 if inst.errno == errno.ENOENT:
1248 if inst.errno == errno.ENOENT:
1249 ui.warn(_('%s: deleted in working directory\n') % relsrc)
1249 ui.warn(_('%s: deleted in working directory\n') % relsrc)
1250 srcexists = False
1250 srcexists = False
1251 else:
1251 else:
1252 ui.warn(_('%s: cannot copy - %s\n') %
1252 ui.warn(_('%s: cannot copy - %s\n') %
1253 (relsrc, encoding.strtolocal(inst.strerror)))
1253 (relsrc, encoding.strtolocal(inst.strerror)))
1254 return True # report a failure
1254 return True # report a failure
1255
1255
1256 if ui.verbose or not exact:
1256 if ui.verbose or not exact:
1257 if rename:
1257 if rename:
1258 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
1258 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
1259 else:
1259 else:
1260 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
1260 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
1261
1261
1262 targets[abstarget] = abssrc
1262 targets[abstarget] = abssrc
1263
1263
1264 # fix up dirstate
1264 # fix up dirstate
1265 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
1265 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
1266 dryrun=dryrun, cwd=cwd)
1266 dryrun=dryrun, cwd=cwd)
1267 if rename and not dryrun:
1267 if rename and not dryrun:
1268 if not after and srcexists and not samefile:
1268 if not after and srcexists and not samefile:
1269 rmdir = repo.ui.configbool('experimental', 'removeemptydirs')
1269 rmdir = repo.ui.configbool('experimental', 'removeemptydirs')
1270 repo.wvfs.unlinkpath(abssrc, rmdir=rmdir)
1270 repo.wvfs.unlinkpath(abssrc, rmdir=rmdir)
1271 wctx.forget([abssrc])
1271 wctx.forget([abssrc])
1272
1272
1273 # pat: ossep
1273 # pat: ossep
1274 # dest ossep
1274 # dest ossep
1275 # srcs: list of (hgsep, hgsep, ossep, bool)
1275 # srcs: list of (hgsep, hgsep, ossep, bool)
1276 # return: function that takes hgsep and returns ossep
1276 # return: function that takes hgsep and returns ossep
1277 def targetpathfn(pat, dest, srcs):
1277 def targetpathfn(pat, dest, srcs):
1278 if os.path.isdir(pat):
1278 if os.path.isdir(pat):
1279 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1279 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1280 abspfx = util.localpath(abspfx)
1280 abspfx = util.localpath(abspfx)
1281 if destdirexists:
1281 if destdirexists:
1282 striplen = len(os.path.split(abspfx)[0])
1282 striplen = len(os.path.split(abspfx)[0])
1283 else:
1283 else:
1284 striplen = len(abspfx)
1284 striplen = len(abspfx)
1285 if striplen:
1285 if striplen:
1286 striplen += len(pycompat.ossep)
1286 striplen += len(pycompat.ossep)
1287 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1287 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1288 elif destdirexists:
1288 elif destdirexists:
1289 res = lambda p: os.path.join(dest,
1289 res = lambda p: os.path.join(dest,
1290 os.path.basename(util.localpath(p)))
1290 os.path.basename(util.localpath(p)))
1291 else:
1291 else:
1292 res = lambda p: dest
1292 res = lambda p: dest
1293 return res
1293 return res
1294
1294
1295 # pat: ossep
1295 # pat: ossep
1296 # dest ossep
1296 # dest ossep
1297 # srcs: list of (hgsep, hgsep, ossep, bool)
1297 # srcs: list of (hgsep, hgsep, ossep, bool)
1298 # return: function that takes hgsep and returns ossep
1298 # return: function that takes hgsep and returns ossep
1299 def targetpathafterfn(pat, dest, srcs):
1299 def targetpathafterfn(pat, dest, srcs):
1300 if matchmod.patkind(pat):
1300 if matchmod.patkind(pat):
1301 # a mercurial pattern
1301 # a mercurial pattern
1302 res = lambda p: os.path.join(dest,
1302 res = lambda p: os.path.join(dest,
1303 os.path.basename(util.localpath(p)))
1303 os.path.basename(util.localpath(p)))
1304 else:
1304 else:
1305 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1305 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1306 if len(abspfx) < len(srcs[0][0]):
1306 if len(abspfx) < len(srcs[0][0]):
1307 # A directory. Either the target path contains the last
1307 # A directory. Either the target path contains the last
1308 # component of the source path or it does not.
1308 # component of the source path or it does not.
1309 def evalpath(striplen):
1309 def evalpath(striplen):
1310 score = 0
1310 score = 0
1311 for s in srcs:
1311 for s in srcs:
1312 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1312 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1313 if os.path.lexists(t):
1313 if os.path.lexists(t):
1314 score += 1
1314 score += 1
1315 return score
1315 return score
1316
1316
1317 abspfx = util.localpath(abspfx)
1317 abspfx = util.localpath(abspfx)
1318 striplen = len(abspfx)
1318 striplen = len(abspfx)
1319 if striplen:
1319 if striplen:
1320 striplen += len(pycompat.ossep)
1320 striplen += len(pycompat.ossep)
1321 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1321 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1322 score = evalpath(striplen)
1322 score = evalpath(striplen)
1323 striplen1 = len(os.path.split(abspfx)[0])
1323 striplen1 = len(os.path.split(abspfx)[0])
1324 if striplen1:
1324 if striplen1:
1325 striplen1 += len(pycompat.ossep)
1325 striplen1 += len(pycompat.ossep)
1326 if evalpath(striplen1) > score:
1326 if evalpath(striplen1) > score:
1327 striplen = striplen1
1327 striplen = striplen1
1328 res = lambda p: os.path.join(dest,
1328 res = lambda p: os.path.join(dest,
1329 util.localpath(p)[striplen:])
1329 util.localpath(p)[striplen:])
1330 else:
1330 else:
1331 # a file
1331 # a file
1332 if destdirexists:
1332 if destdirexists:
1333 res = lambda p: os.path.join(dest,
1333 res = lambda p: os.path.join(dest,
1334 os.path.basename(util.localpath(p)))
1334 os.path.basename(util.localpath(p)))
1335 else:
1335 else:
1336 res = lambda p: dest
1336 res = lambda p: dest
1337 return res
1337 return res
1338
1338
1339 pats = scmutil.expandpats(pats)
1339 pats = scmutil.expandpats(pats)
1340 if not pats:
1340 if not pats:
1341 raise error.Abort(_('no source or destination specified'))
1341 raise error.Abort(_('no source or destination specified'))
1342 if len(pats) == 1:
1342 if len(pats) == 1:
1343 raise error.Abort(_('no destination specified'))
1343 raise error.Abort(_('no destination specified'))
1344 dest = pats.pop()
1344 dest = pats.pop()
1345 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1345 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1346 if not destdirexists:
1346 if not destdirexists:
1347 if len(pats) > 1 or matchmod.patkind(pats[0]):
1347 if len(pats) > 1 or matchmod.patkind(pats[0]):
1348 raise error.Abort(_('with multiple sources, destination must be an '
1348 raise error.Abort(_('with multiple sources, destination must be an '
1349 'existing directory'))
1349 'existing directory'))
1350 if util.endswithsep(dest):
1350 if util.endswithsep(dest):
1351 raise error.Abort(_('destination %s is not a directory') % dest)
1351 raise error.Abort(_('destination %s is not a directory') % dest)
1352
1352
1353 tfn = targetpathfn
1353 tfn = targetpathfn
1354 if after:
1354 if after:
1355 tfn = targetpathafterfn
1355 tfn = targetpathafterfn
1356 copylist = []
1356 copylist = []
1357 for pat in pats:
1357 for pat in pats:
1358 srcs = walkpat(pat)
1358 srcs = walkpat(pat)
1359 if not srcs:
1359 if not srcs:
1360 continue
1360 continue
1361 copylist.append((tfn(pat, dest, srcs), srcs))
1361 copylist.append((tfn(pat, dest, srcs), srcs))
1362 if not copylist:
1362 if not copylist:
1363 raise error.Abort(_('no files to copy'))
1363 raise error.Abort(_('no files to copy'))
1364
1364
1365 errors = 0
1365 errors = 0
1366 for targetpath, srcs in copylist:
1366 for targetpath, srcs in copylist:
1367 for abssrc, relsrc, exact in srcs:
1367 for abssrc, relsrc, exact in srcs:
1368 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1368 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1369 errors += 1
1369 errors += 1
1370
1370
1371 return errors != 0
1371 return errors != 0
1372
1372
1373 ## facility to let extension process additional data into an import patch
1373 ## facility to let extension process additional data into an import patch
1374 # list of identifier to be executed in order
1374 # list of identifier to be executed in order
1375 extrapreimport = [] # run before commit
1375 extrapreimport = [] # run before commit
1376 extrapostimport = [] # run after commit
1376 extrapostimport = [] # run after commit
1377 # mapping from identifier to actual import function
1377 # mapping from identifier to actual import function
1378 #
1378 #
1379 # 'preimport' are run before the commit is made and are provided the following
1379 # 'preimport' are run before the commit is made and are provided the following
1380 # arguments:
1380 # arguments:
1381 # - repo: the localrepository instance,
1381 # - repo: the localrepository instance,
1382 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1382 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1383 # - extra: the future extra dictionary of the changeset, please mutate it,
1383 # - extra: the future extra dictionary of the changeset, please mutate it,
1384 # - opts: the import options.
1384 # - opts: the import options.
1385 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1385 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1386 # mutation of in memory commit and more. Feel free to rework the code to get
1386 # mutation of in memory commit and more. Feel free to rework the code to get
1387 # there.
1387 # there.
1388 extrapreimportmap = {}
1388 extrapreimportmap = {}
1389 # 'postimport' are run after the commit is made and are provided the following
1389 # 'postimport' are run after the commit is made and are provided the following
1390 # argument:
1390 # argument:
1391 # - ctx: the changectx created by import.
1391 # - ctx: the changectx created by import.
1392 extrapostimportmap = {}
1392 extrapostimportmap = {}
1393
1393
1394 def tryimportone(ui, repo, patchdata, parents, opts, msgs, updatefunc):
1394 def tryimportone(ui, repo, patchdata, parents, opts, msgs, updatefunc):
1395 """Utility function used by commands.import to import a single patch
1395 """Utility function used by commands.import to import a single patch
1396
1396
1397 This function is explicitly defined here to help the evolve extension to
1397 This function is explicitly defined here to help the evolve extension to
1398 wrap this part of the import logic.
1398 wrap this part of the import logic.
1399
1399
1400 The API is currently a bit ugly because it a simple code translation from
1400 The API is currently a bit ugly because it a simple code translation from
1401 the import command. Feel free to make it better.
1401 the import command. Feel free to make it better.
1402
1402
1403 :patchdata: a dictionary containing parsed patch data (such as from
1403 :patchdata: a dictionary containing parsed patch data (such as from
1404 ``patch.extract()``)
1404 ``patch.extract()``)
1405 :parents: nodes that will be parent of the created commit
1405 :parents: nodes that will be parent of the created commit
1406 :opts: the full dict of option passed to the import command
1406 :opts: the full dict of option passed to the import command
1407 :msgs: list to save commit message to.
1407 :msgs: list to save commit message to.
1408 (used in case we need to save it when failing)
1408 (used in case we need to save it when failing)
1409 :updatefunc: a function that update a repo to a given node
1409 :updatefunc: a function that update a repo to a given node
1410 updatefunc(<repo>, <node>)
1410 updatefunc(<repo>, <node>)
1411 """
1411 """
1412 # avoid cycle context -> subrepo -> cmdutil
1412 # avoid cycle context -> subrepo -> cmdutil
1413 from . import context
1413 from . import context
1414
1414
1415 tmpname = patchdata.get('filename')
1415 tmpname = patchdata.get('filename')
1416 message = patchdata.get('message')
1416 message = patchdata.get('message')
1417 user = opts.get('user') or patchdata.get('user')
1417 user = opts.get('user') or patchdata.get('user')
1418 date = opts.get('date') or patchdata.get('date')
1418 date = opts.get('date') or patchdata.get('date')
1419 branch = patchdata.get('branch')
1419 branch = patchdata.get('branch')
1420 nodeid = patchdata.get('nodeid')
1420 nodeid = patchdata.get('nodeid')
1421 p1 = patchdata.get('p1')
1421 p1 = patchdata.get('p1')
1422 p2 = patchdata.get('p2')
1422 p2 = patchdata.get('p2')
1423
1423
1424 nocommit = opts.get('no_commit')
1424 nocommit = opts.get('no_commit')
1425 importbranch = opts.get('import_branch')
1425 importbranch = opts.get('import_branch')
1426 update = not opts.get('bypass')
1426 update = not opts.get('bypass')
1427 strip = opts["strip"]
1427 strip = opts["strip"]
1428 prefix = opts["prefix"]
1428 prefix = opts["prefix"]
1429 sim = float(opts.get('similarity') or 0)
1429 sim = float(opts.get('similarity') or 0)
1430
1430
1431 if not tmpname:
1431 if not tmpname:
1432 return None, None, False
1432 return None, None, False
1433
1433
1434 rejects = False
1434 rejects = False
1435
1435
1436 cmdline_message = logmessage(ui, opts)
1436 cmdline_message = logmessage(ui, opts)
1437 if cmdline_message:
1437 if cmdline_message:
1438 # pickup the cmdline msg
1438 # pickup the cmdline msg
1439 message = cmdline_message
1439 message = cmdline_message
1440 elif message:
1440 elif message:
1441 # pickup the patch msg
1441 # pickup the patch msg
1442 message = message.strip()
1442 message = message.strip()
1443 else:
1443 else:
1444 # launch the editor
1444 # launch the editor
1445 message = None
1445 message = None
1446 ui.debug('message:\n%s\n' % (message or ''))
1446 ui.debug('message:\n%s\n' % (message or ''))
1447
1447
1448 if len(parents) == 1:
1448 if len(parents) == 1:
1449 parents.append(repo[nullid])
1449 parents.append(repo[nullid])
1450 if opts.get('exact'):
1450 if opts.get('exact'):
1451 if not nodeid or not p1:
1451 if not nodeid or not p1:
1452 raise error.Abort(_('not a Mercurial patch'))
1452 raise error.Abort(_('not a Mercurial patch'))
1453 p1 = repo[p1]
1453 p1 = repo[p1]
1454 p2 = repo[p2 or nullid]
1454 p2 = repo[p2 or nullid]
1455 elif p2:
1455 elif p2:
1456 try:
1456 try:
1457 p1 = repo[p1]
1457 p1 = repo[p1]
1458 p2 = repo[p2]
1458 p2 = repo[p2]
1459 # Without any options, consider p2 only if the
1459 # Without any options, consider p2 only if the
1460 # patch is being applied on top of the recorded
1460 # patch is being applied on top of the recorded
1461 # first parent.
1461 # first parent.
1462 if p1 != parents[0]:
1462 if p1 != parents[0]:
1463 p1 = parents[0]
1463 p1 = parents[0]
1464 p2 = repo[nullid]
1464 p2 = repo[nullid]
1465 except error.RepoError:
1465 except error.RepoError:
1466 p1, p2 = parents
1466 p1, p2 = parents
1467 if p2.node() == nullid:
1467 if p2.node() == nullid:
1468 ui.warn(_("warning: import the patch as a normal revision\n"
1468 ui.warn(_("warning: import the patch as a normal revision\n"
1469 "(use --exact to import the patch as a merge)\n"))
1469 "(use --exact to import the patch as a merge)\n"))
1470 else:
1470 else:
1471 p1, p2 = parents
1471 p1, p2 = parents
1472
1472
1473 n = None
1473 n = None
1474 if update:
1474 if update:
1475 if p1 != parents[0]:
1475 if p1 != parents[0]:
1476 updatefunc(repo, p1.node())
1476 updatefunc(repo, p1.node())
1477 if p2 != parents[1]:
1477 if p2 != parents[1]:
1478 repo.setparents(p1.node(), p2.node())
1478 repo.setparents(p1.node(), p2.node())
1479
1479
1480 if opts.get('exact') or importbranch:
1480 if opts.get('exact') or importbranch:
1481 repo.dirstate.setbranch(branch or 'default')
1481 repo.dirstate.setbranch(branch or 'default')
1482
1482
1483 partial = opts.get('partial', False)
1483 partial = opts.get('partial', False)
1484 files = set()
1484 files = set()
1485 try:
1485 try:
1486 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
1486 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
1487 files=files, eolmode=None, similarity=sim / 100.0)
1487 files=files, eolmode=None, similarity=sim / 100.0)
1488 except error.PatchError as e:
1488 except error.PatchError as e:
1489 if not partial:
1489 if not partial:
1490 raise error.Abort(pycompat.bytestr(e))
1490 raise error.Abort(pycompat.bytestr(e))
1491 if partial:
1491 if partial:
1492 rejects = True
1492 rejects = True
1493
1493
1494 files = list(files)
1494 files = list(files)
1495 if nocommit:
1495 if nocommit:
1496 if message:
1496 if message:
1497 msgs.append(message)
1497 msgs.append(message)
1498 else:
1498 else:
1499 if opts.get('exact') or p2:
1499 if opts.get('exact') or p2:
1500 # If you got here, you either use --force and know what
1500 # If you got here, you either use --force and know what
1501 # you are doing or used --exact or a merge patch while
1501 # you are doing or used --exact or a merge patch while
1502 # being updated to its first parent.
1502 # being updated to its first parent.
1503 m = None
1503 m = None
1504 else:
1504 else:
1505 m = scmutil.matchfiles(repo, files or [])
1505 m = scmutil.matchfiles(repo, files or [])
1506 editform = mergeeditform(repo[None], 'import.normal')
1506 editform = mergeeditform(repo[None], 'import.normal')
1507 if opts.get('exact'):
1507 if opts.get('exact'):
1508 editor = None
1508 editor = None
1509 else:
1509 else:
1510 editor = getcommiteditor(editform=editform,
1510 editor = getcommiteditor(editform=editform,
1511 **pycompat.strkwargs(opts))
1511 **pycompat.strkwargs(opts))
1512 extra = {}
1512 extra = {}
1513 for idfunc in extrapreimport:
1513 for idfunc in extrapreimport:
1514 extrapreimportmap[idfunc](repo, patchdata, extra, opts)
1514 extrapreimportmap[idfunc](repo, patchdata, extra, opts)
1515 overrides = {}
1515 overrides = {}
1516 if partial:
1516 if partial:
1517 overrides[('ui', 'allowemptycommit')] = True
1517 overrides[('ui', 'allowemptycommit')] = True
1518 with repo.ui.configoverride(overrides, 'import'):
1518 with repo.ui.configoverride(overrides, 'import'):
1519 n = repo.commit(message, user,
1519 n = repo.commit(message, user,
1520 date, match=m,
1520 date, match=m,
1521 editor=editor, extra=extra)
1521 editor=editor, extra=extra)
1522 for idfunc in extrapostimport:
1522 for idfunc in extrapostimport:
1523 extrapostimportmap[idfunc](repo[n])
1523 extrapostimportmap[idfunc](repo[n])
1524 else:
1524 else:
1525 if opts.get('exact') or importbranch:
1525 if opts.get('exact') or importbranch:
1526 branch = branch or 'default'
1526 branch = branch or 'default'
1527 else:
1527 else:
1528 branch = p1.branch()
1528 branch = p1.branch()
1529 store = patch.filestore()
1529 store = patch.filestore()
1530 try:
1530 try:
1531 files = set()
1531 files = set()
1532 try:
1532 try:
1533 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
1533 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
1534 files, eolmode=None)
1534 files, eolmode=None)
1535 except error.PatchError as e:
1535 except error.PatchError as e:
1536 raise error.Abort(stringutil.forcebytestr(e))
1536 raise error.Abort(stringutil.forcebytestr(e))
1537 if opts.get('exact'):
1537 if opts.get('exact'):
1538 editor = None
1538 editor = None
1539 else:
1539 else:
1540 editor = getcommiteditor(editform='import.bypass')
1540 editor = getcommiteditor(editform='import.bypass')
1541 memctx = context.memctx(repo, (p1.node(), p2.node()),
1541 memctx = context.memctx(repo, (p1.node(), p2.node()),
1542 message,
1542 message,
1543 files=files,
1543 files=files,
1544 filectxfn=store,
1544 filectxfn=store,
1545 user=user,
1545 user=user,
1546 date=date,
1546 date=date,
1547 branch=branch,
1547 branch=branch,
1548 editor=editor)
1548 editor=editor)
1549 n = memctx.commit()
1549 n = memctx.commit()
1550 finally:
1550 finally:
1551 store.close()
1551 store.close()
1552 if opts.get('exact') and nocommit:
1552 if opts.get('exact') and nocommit:
1553 # --exact with --no-commit is still useful in that it does merge
1553 # --exact with --no-commit is still useful in that it does merge
1554 # and branch bits
1554 # and branch bits
1555 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1555 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1556 elif opts.get('exact') and (not n or hex(n) != nodeid):
1556 elif opts.get('exact') and (not n or hex(n) != nodeid):
1557 raise error.Abort(_('patch is damaged or loses information'))
1557 raise error.Abort(_('patch is damaged or loses information'))
1558 msg = _('applied to working directory')
1558 msg = _('applied to working directory')
1559 if n:
1559 if n:
1560 # i18n: refers to a short changeset id
1560 # i18n: refers to a short changeset id
1561 msg = _('created %s') % short(n)
1561 msg = _('created %s') % short(n)
1562 return msg, n, rejects
1562 return msg, n, rejects
1563
1563
1564 # facility to let extensions include additional data in an exported patch
1564 # facility to let extensions include additional data in an exported patch
1565 # list of identifiers to be executed in order
1565 # list of identifiers to be executed in order
1566 extraexport = []
1566 extraexport = []
1567 # mapping from identifier to actual export function
1567 # mapping from identifier to actual export function
1568 # function as to return a string to be added to the header or None
1568 # function as to return a string to be added to the header or None
1569 # it is given two arguments (sequencenumber, changectx)
1569 # it is given two arguments (sequencenumber, changectx)
1570 extraexportmap = {}
1570 extraexportmap = {}
1571
1571
1572 def _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts):
1572 def _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts):
1573 node = scmutil.binnode(ctx)
1573 node = scmutil.binnode(ctx)
1574 parents = [p.node() for p in ctx.parents() if p]
1574 parents = [p.node() for p in ctx.parents() if p]
1575 branch = ctx.branch()
1575 branch = ctx.branch()
1576 if switch_parent:
1576 if switch_parent:
1577 parents.reverse()
1577 parents.reverse()
1578
1578
1579 if parents:
1579 if parents:
1580 prev = parents[0]
1580 prev = parents[0]
1581 else:
1581 else:
1582 prev = nullid
1582 prev = nullid
1583
1583
1584 fm.context(ctx=ctx)
1584 fm.context(ctx=ctx)
1585 fm.plain('# HG changeset patch\n')
1585 fm.plain('# HG changeset patch\n')
1586 fm.write('user', '# User %s\n', ctx.user())
1586 fm.write('user', '# User %s\n', ctx.user())
1587 fm.plain('# Date %d %d\n' % ctx.date())
1587 fm.plain('# Date %d %d\n' % ctx.date())
1588 fm.write('date', '# %s\n', fm.formatdate(ctx.date()))
1588 fm.write('date', '# %s\n', fm.formatdate(ctx.date()))
1589 fm.condwrite(branch and branch != 'default',
1589 fm.condwrite(branch and branch != 'default',
1590 'branch', '# Branch %s\n', branch)
1590 'branch', '# Branch %s\n', branch)
1591 fm.write('node', '# Node ID %s\n', hex(node))
1591 fm.write('node', '# Node ID %s\n', hex(node))
1592 fm.plain('# Parent %s\n' % hex(prev))
1592 fm.plain('# Parent %s\n' % hex(prev))
1593 if len(parents) > 1:
1593 if len(parents) > 1:
1594 fm.plain('# Parent %s\n' % hex(parents[1]))
1594 fm.plain('# Parent %s\n' % hex(parents[1]))
1595 fm.data(parents=fm.formatlist(pycompat.maplist(hex, parents), name='node'))
1595 fm.data(parents=fm.formatlist(pycompat.maplist(hex, parents), name='node'))
1596
1596
1597 # TODO: redesign extraexportmap function to support formatter
1597 # TODO: redesign extraexportmap function to support formatter
1598 for headerid in extraexport:
1598 for headerid in extraexport:
1599 header = extraexportmap[headerid](seqno, ctx)
1599 header = extraexportmap[headerid](seqno, ctx)
1600 if header is not None:
1600 if header is not None:
1601 fm.plain('# %s\n' % header)
1601 fm.plain('# %s\n' % header)
1602
1602
1603 fm.write('desc', '%s\n', ctx.description().rstrip())
1603 fm.write('desc', '%s\n', ctx.description().rstrip())
1604 fm.plain('\n')
1604 fm.plain('\n')
1605
1605
1606 if fm.isplain():
1606 if fm.isplain():
1607 chunkiter = patch.diffui(repo, prev, node, match, opts=diffopts)
1607 chunkiter = patch.diffui(repo, prev, node, match, opts=diffopts)
1608 for chunk, label in chunkiter:
1608 for chunk, label in chunkiter:
1609 fm.plain(chunk, label=label)
1609 fm.plain(chunk, label=label)
1610 else:
1610 else:
1611 chunkiter = patch.diff(repo, prev, node, match, opts=diffopts)
1611 chunkiter = patch.diff(repo, prev, node, match, opts=diffopts)
1612 # TODO: make it structured?
1612 # TODO: make it structured?
1613 fm.data(diff=b''.join(chunkiter))
1613 fm.data(diff=b''.join(chunkiter))
1614
1614
1615 def _exportfile(repo, revs, fm, dest, switch_parent, diffopts, match):
1615 def _exportfile(repo, revs, fm, dest, switch_parent, diffopts, match):
1616 """Export changesets to stdout or a single file"""
1616 """Export changesets to stdout or a single file"""
1617 for seqno, rev in enumerate(revs, 1):
1617 for seqno, rev in enumerate(revs, 1):
1618 ctx = repo[rev]
1618 ctx = repo[rev]
1619 if not dest.startswith('<'):
1619 if not dest.startswith('<'):
1620 repo.ui.note("%s\n" % dest)
1620 repo.ui.note("%s\n" % dest)
1621 fm.startitem()
1621 fm.startitem()
1622 _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts)
1622 _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts)
1623
1623
1624 def _exportfntemplate(repo, revs, basefm, fntemplate, switch_parent, diffopts,
1624 def _exportfntemplate(repo, revs, basefm, fntemplate, switch_parent, diffopts,
1625 match):
1625 match):
1626 """Export changesets to possibly multiple files"""
1626 """Export changesets to possibly multiple files"""
1627 total = len(revs)
1627 total = len(revs)
1628 revwidth = max(len(str(rev)) for rev in revs)
1628 revwidth = max(len(str(rev)) for rev in revs)
1629 filemap = util.sortdict() # filename: [(seqno, rev), ...]
1629 filemap = util.sortdict() # filename: [(seqno, rev), ...]
1630
1630
1631 for seqno, rev in enumerate(revs, 1):
1631 for seqno, rev in enumerate(revs, 1):
1632 ctx = repo[rev]
1632 ctx = repo[rev]
1633 dest = makefilename(ctx, fntemplate,
1633 dest = makefilename(ctx, fntemplate,
1634 total=total, seqno=seqno, revwidth=revwidth)
1634 total=total, seqno=seqno, revwidth=revwidth)
1635 filemap.setdefault(dest, []).append((seqno, rev))
1635 filemap.setdefault(dest, []).append((seqno, rev))
1636
1636
1637 for dest in filemap:
1637 for dest in filemap:
1638 with formatter.maybereopen(basefm, dest) as fm:
1638 with formatter.maybereopen(basefm, dest) as fm:
1639 repo.ui.note("%s\n" % dest)
1639 repo.ui.note("%s\n" % dest)
1640 for seqno, rev in filemap[dest]:
1640 for seqno, rev in filemap[dest]:
1641 fm.startitem()
1641 fm.startitem()
1642 ctx = repo[rev]
1642 ctx = repo[rev]
1643 _exportsingle(repo, ctx, fm, match, switch_parent, seqno,
1643 _exportsingle(repo, ctx, fm, match, switch_parent, seqno,
1644 diffopts)
1644 diffopts)
1645
1645
1646 def export(repo, revs, basefm, fntemplate='hg-%h.patch', switch_parent=False,
1646 def export(repo, revs, basefm, fntemplate='hg-%h.patch', switch_parent=False,
1647 opts=None, match=None):
1647 opts=None, match=None):
1648 '''export changesets as hg patches
1648 '''export changesets as hg patches
1649
1649
1650 Args:
1650 Args:
1651 repo: The repository from which we're exporting revisions.
1651 repo: The repository from which we're exporting revisions.
1652 revs: A list of revisions to export as revision numbers.
1652 revs: A list of revisions to export as revision numbers.
1653 basefm: A formatter to which patches should be written.
1653 basefm: A formatter to which patches should be written.
1654 fntemplate: An optional string to use for generating patch file names.
1654 fntemplate: An optional string to use for generating patch file names.
1655 switch_parent: If True, show diffs against second parent when not nullid.
1655 switch_parent: If True, show diffs against second parent when not nullid.
1656 Default is false, which always shows diff against p1.
1656 Default is false, which always shows diff against p1.
1657 opts: diff options to use for generating the patch.
1657 opts: diff options to use for generating the patch.
1658 match: If specified, only export changes to files matching this matcher.
1658 match: If specified, only export changes to files matching this matcher.
1659
1659
1660 Returns:
1660 Returns:
1661 Nothing.
1661 Nothing.
1662
1662
1663 Side Effect:
1663 Side Effect:
1664 "HG Changeset Patch" data is emitted to one of the following
1664 "HG Changeset Patch" data is emitted to one of the following
1665 destinations:
1665 destinations:
1666 fntemplate specified: Each rev is written to a unique file named using
1666 fntemplate specified: Each rev is written to a unique file named using
1667 the given template.
1667 the given template.
1668 Otherwise: All revs will be written to basefm.
1668 Otherwise: All revs will be written to basefm.
1669 '''
1669 '''
1670 scmutil.prefetchfiles(repo, revs, match)
1670 scmutil.prefetchfiles(repo, revs, match)
1671
1671
1672 if not fntemplate:
1672 if not fntemplate:
1673 _exportfile(repo, revs, basefm, '<unnamed>', switch_parent, opts, match)
1673 _exportfile(repo, revs, basefm, '<unnamed>', switch_parent, opts, match)
1674 else:
1674 else:
1675 _exportfntemplate(repo, revs, basefm, fntemplate, switch_parent, opts,
1675 _exportfntemplate(repo, revs, basefm, fntemplate, switch_parent, opts,
1676 match)
1676 match)
1677
1677
1678 def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None):
1678 def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None):
1679 """Export changesets to the given file stream"""
1679 """Export changesets to the given file stream"""
1680 scmutil.prefetchfiles(repo, revs, match)
1680 scmutil.prefetchfiles(repo, revs, match)
1681
1681
1682 dest = getattr(fp, 'name', '<unnamed>')
1682 dest = getattr(fp, 'name', '<unnamed>')
1683 with formatter.formatter(repo.ui, fp, 'export', {}) as fm:
1683 with formatter.formatter(repo.ui, fp, 'export', {}) as fm:
1684 _exportfile(repo, revs, fm, dest, switch_parent, opts, match)
1684 _exportfile(repo, revs, fm, dest, switch_parent, opts, match)
1685
1685
1686 def showmarker(fm, marker, index=None):
1686 def showmarker(fm, marker, index=None):
1687 """utility function to display obsolescence marker in a readable way
1687 """utility function to display obsolescence marker in a readable way
1688
1688
1689 To be used by debug function."""
1689 To be used by debug function."""
1690 if index is not None:
1690 if index is not None:
1691 fm.write('index', '%i ', index)
1691 fm.write('index', '%i ', index)
1692 fm.write('prednode', '%s ', hex(marker.prednode()))
1692 fm.write('prednode', '%s ', hex(marker.prednode()))
1693 succs = marker.succnodes()
1693 succs = marker.succnodes()
1694 fm.condwrite(succs, 'succnodes', '%s ',
1694 fm.condwrite(succs, 'succnodes', '%s ',
1695 fm.formatlist(map(hex, succs), name='node'))
1695 fm.formatlist(map(hex, succs), name='node'))
1696 fm.write('flag', '%X ', marker.flags())
1696 fm.write('flag', '%X ', marker.flags())
1697 parents = marker.parentnodes()
1697 parents = marker.parentnodes()
1698 if parents is not None:
1698 if parents is not None:
1699 fm.write('parentnodes', '{%s} ',
1699 fm.write('parentnodes', '{%s} ',
1700 fm.formatlist(map(hex, parents), name='node', sep=', '))
1700 fm.formatlist(map(hex, parents), name='node', sep=', '))
1701 fm.write('date', '(%s) ', fm.formatdate(marker.date()))
1701 fm.write('date', '(%s) ', fm.formatdate(marker.date()))
1702 meta = marker.metadata().copy()
1702 meta = marker.metadata().copy()
1703 meta.pop('date', None)
1703 meta.pop('date', None)
1704 smeta = pycompat.rapply(pycompat.maybebytestr, meta)
1704 smeta = pycompat.rapply(pycompat.maybebytestr, meta)
1705 fm.write('metadata', '{%s}', fm.formatdict(smeta, fmt='%r: %r', sep=', '))
1705 fm.write('metadata', '{%s}', fm.formatdict(smeta, fmt='%r: %r', sep=', '))
1706 fm.plain('\n')
1706 fm.plain('\n')
1707
1707
1708 def finddate(ui, repo, date):
1708 def finddate(ui, repo, date):
1709 """Find the tipmost changeset that matches the given date spec"""
1709 """Find the tipmost changeset that matches the given date spec"""
1710
1710
1711 df = dateutil.matchdate(date)
1711 df = dateutil.matchdate(date)
1712 m = scmutil.matchall(repo)
1712 m = scmutil.matchall(repo)
1713 results = {}
1713 results = {}
1714
1714
1715 def prep(ctx, fns):
1715 def prep(ctx, fns):
1716 d = ctx.date()
1716 d = ctx.date()
1717 if df(d[0]):
1717 if df(d[0]):
1718 results[ctx.rev()] = d
1718 results[ctx.rev()] = d
1719
1719
1720 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1720 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1721 rev = ctx.rev()
1721 rev = ctx.rev()
1722 if rev in results:
1722 if rev in results:
1723 ui.status(_("found revision %s from %s\n") %
1723 ui.status(_("found revision %s from %s\n") %
1724 (rev, dateutil.datestr(results[rev])))
1724 (rev, dateutil.datestr(results[rev])))
1725 return '%d' % rev
1725 return '%d' % rev
1726
1726
1727 raise error.Abort(_("revision matching date not found"))
1727 raise error.Abort(_("revision matching date not found"))
1728
1728
1729 def increasingwindows(windowsize=8, sizelimit=512):
1729 def increasingwindows(windowsize=8, sizelimit=512):
1730 while True:
1730 while True:
1731 yield windowsize
1731 yield windowsize
1732 if windowsize < sizelimit:
1732 if windowsize < sizelimit:
1733 windowsize *= 2
1733 windowsize *= 2
1734
1734
1735 def _walkrevs(repo, opts):
1735 def _walkrevs(repo, opts):
1736 # Default --rev value depends on --follow but --follow behavior
1736 # Default --rev value depends on --follow but --follow behavior
1737 # depends on revisions resolved from --rev...
1737 # depends on revisions resolved from --rev...
1738 follow = opts.get('follow') or opts.get('follow_first')
1738 follow = opts.get('follow') or opts.get('follow_first')
1739 if opts.get('rev'):
1739 if opts.get('rev'):
1740 revs = scmutil.revrange(repo, opts['rev'])
1740 revs = scmutil.revrange(repo, opts['rev'])
1741 elif follow and repo.dirstate.p1() == nullid:
1741 elif follow and repo.dirstate.p1() == nullid:
1742 revs = smartset.baseset()
1742 revs = smartset.baseset()
1743 elif follow:
1743 elif follow:
1744 revs = repo.revs('reverse(:.)')
1744 revs = repo.revs('reverse(:.)')
1745 else:
1745 else:
1746 revs = smartset.spanset(repo)
1746 revs = smartset.spanset(repo)
1747 revs.reverse()
1747 revs.reverse()
1748 return revs
1748 return revs
1749
1749
1750 class FileWalkError(Exception):
1750 class FileWalkError(Exception):
1751 pass
1751 pass
1752
1752
1753 def walkfilerevs(repo, match, follow, revs, fncache):
1753 def walkfilerevs(repo, match, follow, revs, fncache):
1754 '''Walks the file history for the matched files.
1754 '''Walks the file history for the matched files.
1755
1755
1756 Returns the changeset revs that are involved in the file history.
1756 Returns the changeset revs that are involved in the file history.
1757
1757
1758 Throws FileWalkError if the file history can't be walked using
1758 Throws FileWalkError if the file history can't be walked using
1759 filelogs alone.
1759 filelogs alone.
1760 '''
1760 '''
1761 wanted = set()
1761 wanted = set()
1762 copies = []
1762 copies = []
1763 minrev, maxrev = min(revs), max(revs)
1763 minrev, maxrev = min(revs), max(revs)
1764 def filerevgen(filelog, last):
1764 def filerevgen(filelog, last):
1765 """
1765 """
1766 Only files, no patterns. Check the history of each file.
1766 Only files, no patterns. Check the history of each file.
1767
1767
1768 Examines filelog entries within minrev, maxrev linkrev range
1768 Examines filelog entries within minrev, maxrev linkrev range
1769 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1769 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1770 tuples in backwards order
1770 tuples in backwards order
1771 """
1771 """
1772 cl_count = len(repo)
1772 cl_count = len(repo)
1773 revs = []
1773 revs = []
1774 for j in pycompat.xrange(0, last + 1):
1774 for j in pycompat.xrange(0, last + 1):
1775 linkrev = filelog.linkrev(j)
1775 linkrev = filelog.linkrev(j)
1776 if linkrev < minrev:
1776 if linkrev < minrev:
1777 continue
1777 continue
1778 # only yield rev for which we have the changelog, it can
1778 # only yield rev for which we have the changelog, it can
1779 # happen while doing "hg log" during a pull or commit
1779 # happen while doing "hg log" during a pull or commit
1780 if linkrev >= cl_count:
1780 if linkrev >= cl_count:
1781 break
1781 break
1782
1782
1783 parentlinkrevs = []
1783 parentlinkrevs = []
1784 for p in filelog.parentrevs(j):
1784 for p in filelog.parentrevs(j):
1785 if p != nullrev:
1785 if p != nullrev:
1786 parentlinkrevs.append(filelog.linkrev(p))
1786 parentlinkrevs.append(filelog.linkrev(p))
1787 n = filelog.node(j)
1787 n = filelog.node(j)
1788 revs.append((linkrev, parentlinkrevs,
1788 revs.append((linkrev, parentlinkrevs,
1789 follow and filelog.renamed(n)))
1789 follow and filelog.renamed(n)))
1790
1790
1791 return reversed(revs)
1791 return reversed(revs)
1792 def iterfiles():
1792 def iterfiles():
1793 pctx = repo['.']
1793 pctx = repo['.']
1794 for filename in match.files():
1794 for filename in match.files():
1795 if follow:
1795 if follow:
1796 if filename not in pctx:
1796 if filename not in pctx:
1797 raise error.Abort(_('cannot follow file not in parent '
1797 raise error.Abort(_('cannot follow file not in parent '
1798 'revision: "%s"') % filename)
1798 'revision: "%s"') % filename)
1799 yield filename, pctx[filename].filenode()
1799 yield filename, pctx[filename].filenode()
1800 else:
1800 else:
1801 yield filename, None
1801 yield filename, None
1802 for filename_node in copies:
1802 for filename_node in copies:
1803 yield filename_node
1803 yield filename_node
1804
1804
1805 for file_, node in iterfiles():
1805 for file_, node in iterfiles():
1806 filelog = repo.file(file_)
1806 filelog = repo.file(file_)
1807 if not len(filelog):
1807 if not len(filelog):
1808 if node is None:
1808 if node is None:
1809 # A zero count may be a directory or deleted file, so
1809 # A zero count may be a directory or deleted file, so
1810 # try to find matching entries on the slow path.
1810 # try to find matching entries on the slow path.
1811 if follow:
1811 if follow:
1812 raise error.Abort(
1812 raise error.Abort(
1813 _('cannot follow nonexistent file: "%s"') % file_)
1813 _('cannot follow nonexistent file: "%s"') % file_)
1814 raise FileWalkError("Cannot walk via filelog")
1814 raise FileWalkError("Cannot walk via filelog")
1815 else:
1815 else:
1816 continue
1816 continue
1817
1817
1818 if node is None:
1818 if node is None:
1819 last = len(filelog) - 1
1819 last = len(filelog) - 1
1820 else:
1820 else:
1821 last = filelog.rev(node)
1821 last = filelog.rev(node)
1822
1822
1823 # keep track of all ancestors of the file
1823 # keep track of all ancestors of the file
1824 ancestors = {filelog.linkrev(last)}
1824 ancestors = {filelog.linkrev(last)}
1825
1825
1826 # iterate from latest to oldest revision
1826 # iterate from latest to oldest revision
1827 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1827 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1828 if not follow:
1828 if not follow:
1829 if rev > maxrev:
1829 if rev > maxrev:
1830 continue
1830 continue
1831 else:
1831 else:
1832 # Note that last might not be the first interesting
1832 # Note that last might not be the first interesting
1833 # rev to us:
1833 # rev to us:
1834 # if the file has been changed after maxrev, we'll
1834 # if the file has been changed after maxrev, we'll
1835 # have linkrev(last) > maxrev, and we still need
1835 # have linkrev(last) > maxrev, and we still need
1836 # to explore the file graph
1836 # to explore the file graph
1837 if rev not in ancestors:
1837 if rev not in ancestors:
1838 continue
1838 continue
1839 # XXX insert 1327 fix here
1839 # XXX insert 1327 fix here
1840 if flparentlinkrevs:
1840 if flparentlinkrevs:
1841 ancestors.update(flparentlinkrevs)
1841 ancestors.update(flparentlinkrevs)
1842
1842
1843 fncache.setdefault(rev, []).append(file_)
1843 fncache.setdefault(rev, []).append(file_)
1844 wanted.add(rev)
1844 wanted.add(rev)
1845 if copied:
1845 if copied:
1846 copies.append(copied)
1846 copies.append(copied)
1847
1847
1848 return wanted
1848 return wanted
1849
1849
1850 class _followfilter(object):
1850 class _followfilter(object):
1851 def __init__(self, repo, onlyfirst=False):
1851 def __init__(self, repo, onlyfirst=False):
1852 self.repo = repo
1852 self.repo = repo
1853 self.startrev = nullrev
1853 self.startrev = nullrev
1854 self.roots = set()
1854 self.roots = set()
1855 self.onlyfirst = onlyfirst
1855 self.onlyfirst = onlyfirst
1856
1856
1857 def match(self, rev):
1857 def match(self, rev):
1858 def realparents(rev):
1858 def realparents(rev):
1859 if self.onlyfirst:
1859 if self.onlyfirst:
1860 return self.repo.changelog.parentrevs(rev)[0:1]
1860 return self.repo.changelog.parentrevs(rev)[0:1]
1861 else:
1861 else:
1862 return filter(lambda x: x != nullrev,
1862 return filter(lambda x: x != nullrev,
1863 self.repo.changelog.parentrevs(rev))
1863 self.repo.changelog.parentrevs(rev))
1864
1864
1865 if self.startrev == nullrev:
1865 if self.startrev == nullrev:
1866 self.startrev = rev
1866 self.startrev = rev
1867 return True
1867 return True
1868
1868
1869 if rev > self.startrev:
1869 if rev > self.startrev:
1870 # forward: all descendants
1870 # forward: all descendants
1871 if not self.roots:
1871 if not self.roots:
1872 self.roots.add(self.startrev)
1872 self.roots.add(self.startrev)
1873 for parent in realparents(rev):
1873 for parent in realparents(rev):
1874 if parent in self.roots:
1874 if parent in self.roots:
1875 self.roots.add(rev)
1875 self.roots.add(rev)
1876 return True
1876 return True
1877 else:
1877 else:
1878 # backwards: all parents
1878 # backwards: all parents
1879 if not self.roots:
1879 if not self.roots:
1880 self.roots.update(realparents(self.startrev))
1880 self.roots.update(realparents(self.startrev))
1881 if rev in self.roots:
1881 if rev in self.roots:
1882 self.roots.remove(rev)
1882 self.roots.remove(rev)
1883 self.roots.update(realparents(rev))
1883 self.roots.update(realparents(rev))
1884 return True
1884 return True
1885
1885
1886 return False
1886 return False
1887
1887
1888 def walkchangerevs(repo, match, opts, prepare):
1888 def walkchangerevs(repo, match, opts, prepare):
1889 '''Iterate over files and the revs in which they changed.
1889 '''Iterate over files and the revs in which they changed.
1890
1890
1891 Callers most commonly need to iterate backwards over the history
1891 Callers most commonly need to iterate backwards over the history
1892 in which they are interested. Doing so has awful (quadratic-looking)
1892 in which they are interested. Doing so has awful (quadratic-looking)
1893 performance, so we use iterators in a "windowed" way.
1893 performance, so we use iterators in a "windowed" way.
1894
1894
1895 We walk a window of revisions in the desired order. Within the
1895 We walk a window of revisions in the desired order. Within the
1896 window, we first walk forwards to gather data, then in the desired
1896 window, we first walk forwards to gather data, then in the desired
1897 order (usually backwards) to display it.
1897 order (usually backwards) to display it.
1898
1898
1899 This function returns an iterator yielding contexts. Before
1899 This function returns an iterator yielding contexts. Before
1900 yielding each context, the iterator will first call the prepare
1900 yielding each context, the iterator will first call the prepare
1901 function on each context in the window in forward order.'''
1901 function on each context in the window in forward order.'''
1902
1902
1903 allfiles = opts.get('all_files')
1903 allfiles = opts.get('all_files')
1904 follow = opts.get('follow') or opts.get('follow_first')
1904 follow = opts.get('follow') or opts.get('follow_first')
1905 revs = _walkrevs(repo, opts)
1905 revs = _walkrevs(repo, opts)
1906 if not revs:
1906 if not revs:
1907 return []
1907 return []
1908 wanted = set()
1908 wanted = set()
1909 slowpath = match.anypats() or (not match.always() and opts.get('removed'))
1909 slowpath = match.anypats() or (not match.always() and opts.get('removed'))
1910 fncache = {}
1910 fncache = {}
1911 change = repo.__getitem__
1911 change = repo.__getitem__
1912
1912
1913 # First step is to fill wanted, the set of revisions that we want to yield.
1913 # First step is to fill wanted, the set of revisions that we want to yield.
1914 # When it does not induce extra cost, we also fill fncache for revisions in
1914 # When it does not induce extra cost, we also fill fncache for revisions in
1915 # wanted: a cache of filenames that were changed (ctx.files()) and that
1915 # wanted: a cache of filenames that were changed (ctx.files()) and that
1916 # match the file filtering conditions.
1916 # match the file filtering conditions.
1917
1917
1918 if match.always() or allfiles:
1918 if match.always() or allfiles:
1919 # No files, no patterns. Display all revs.
1919 # No files, no patterns. Display all revs.
1920 wanted = revs
1920 wanted = revs
1921 elif not slowpath:
1921 elif not slowpath:
1922 # We only have to read through the filelog to find wanted revisions
1922 # We only have to read through the filelog to find wanted revisions
1923
1923
1924 try:
1924 try:
1925 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1925 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1926 except FileWalkError:
1926 except FileWalkError:
1927 slowpath = True
1927 slowpath = True
1928
1928
1929 # We decided to fall back to the slowpath because at least one
1929 # We decided to fall back to the slowpath because at least one
1930 # of the paths was not a file. Check to see if at least one of them
1930 # of the paths was not a file. Check to see if at least one of them
1931 # existed in history, otherwise simply return
1931 # existed in history, otherwise simply return
1932 for path in match.files():
1932 for path in match.files():
1933 if path == '.' or path in repo.store:
1933 if path == '.' or path in repo.store:
1934 break
1934 break
1935 else:
1935 else:
1936 return []
1936 return []
1937
1937
1938 if slowpath:
1938 if slowpath:
1939 # We have to read the changelog to match filenames against
1939 # We have to read the changelog to match filenames against
1940 # changed files
1940 # changed files
1941
1941
1942 if follow:
1942 if follow:
1943 raise error.Abort(_('can only follow copies/renames for explicit '
1943 raise error.Abort(_('can only follow copies/renames for explicit '
1944 'filenames'))
1944 'filenames'))
1945
1945
1946 # The slow path checks files modified in every changeset.
1946 # The slow path checks files modified in every changeset.
1947 # This is really slow on large repos, so compute the set lazily.
1947 # This is really slow on large repos, so compute the set lazily.
1948 class lazywantedset(object):
1948 class lazywantedset(object):
1949 def __init__(self):
1949 def __init__(self):
1950 self.set = set()
1950 self.set = set()
1951 self.revs = set(revs)
1951 self.revs = set(revs)
1952
1952
1953 # No need to worry about locality here because it will be accessed
1953 # No need to worry about locality here because it will be accessed
1954 # in the same order as the increasing window below.
1954 # in the same order as the increasing window below.
1955 def __contains__(self, value):
1955 def __contains__(self, value):
1956 if value in self.set:
1956 if value in self.set:
1957 return True
1957 return True
1958 elif not value in self.revs:
1958 elif not value in self.revs:
1959 return False
1959 return False
1960 else:
1960 else:
1961 self.revs.discard(value)
1961 self.revs.discard(value)
1962 ctx = change(value)
1962 ctx = change(value)
1963 matches = [f for f in ctx.files() if match(f)]
1963 matches = [f for f in ctx.files() if match(f)]
1964 if matches:
1964 if matches:
1965 fncache[value] = matches
1965 fncache[value] = matches
1966 self.set.add(value)
1966 self.set.add(value)
1967 return True
1967 return True
1968 return False
1968 return False
1969
1969
1970 def discard(self, value):
1970 def discard(self, value):
1971 self.revs.discard(value)
1971 self.revs.discard(value)
1972 self.set.discard(value)
1972 self.set.discard(value)
1973
1973
1974 wanted = lazywantedset()
1974 wanted = lazywantedset()
1975
1975
1976 # it might be worthwhile to do this in the iterator if the rev range
1976 # it might be worthwhile to do this in the iterator if the rev range
1977 # is descending and the prune args are all within that range
1977 # is descending and the prune args are all within that range
1978 for rev in opts.get('prune', ()):
1978 for rev in opts.get('prune', ()):
1979 rev = repo[rev].rev()
1979 rev = repo[rev].rev()
1980 ff = _followfilter(repo)
1980 ff = _followfilter(repo)
1981 stop = min(revs[0], revs[-1])
1981 stop = min(revs[0], revs[-1])
1982 for x in pycompat.xrange(rev, stop - 1, -1):
1982 for x in pycompat.xrange(rev, stop - 1, -1):
1983 if ff.match(x):
1983 if ff.match(x):
1984 wanted = wanted - [x]
1984 wanted = wanted - [x]
1985
1985
1986 # Now that wanted is correctly initialized, we can iterate over the
1986 # Now that wanted is correctly initialized, we can iterate over the
1987 # revision range, yielding only revisions in wanted.
1987 # revision range, yielding only revisions in wanted.
1988 def iterate():
1988 def iterate():
1989 if follow and match.always():
1989 if follow and match.always():
1990 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
1990 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
1991 def want(rev):
1991 def want(rev):
1992 return ff.match(rev) and rev in wanted
1992 return ff.match(rev) and rev in wanted
1993 else:
1993 else:
1994 def want(rev):
1994 def want(rev):
1995 return rev in wanted
1995 return rev in wanted
1996
1996
1997 it = iter(revs)
1997 it = iter(revs)
1998 stopiteration = False
1998 stopiteration = False
1999 for windowsize in increasingwindows():
1999 for windowsize in increasingwindows():
2000 nrevs = []
2000 nrevs = []
2001 for i in pycompat.xrange(windowsize):
2001 for i in pycompat.xrange(windowsize):
2002 rev = next(it, None)
2002 rev = next(it, None)
2003 if rev is None:
2003 if rev is None:
2004 stopiteration = True
2004 stopiteration = True
2005 break
2005 break
2006 elif want(rev):
2006 elif want(rev):
2007 nrevs.append(rev)
2007 nrevs.append(rev)
2008 for rev in sorted(nrevs):
2008 for rev in sorted(nrevs):
2009 fns = fncache.get(rev)
2009 fns = fncache.get(rev)
2010 ctx = change(rev)
2010 ctx = change(rev)
2011 if not fns:
2011 if not fns:
2012 def fns_generator():
2012 def fns_generator():
2013 if allfiles:
2013 if allfiles:
2014 fiter = iter(ctx)
2014 fiter = iter(ctx)
2015 else:
2015 else:
2016 fiter = ctx.files()
2016 fiter = ctx.files()
2017 for f in fiter:
2017 for f in fiter:
2018 if match(f):
2018 if match(f):
2019 yield f
2019 yield f
2020 fns = fns_generator()
2020 fns = fns_generator()
2021 prepare(ctx, fns)
2021 prepare(ctx, fns)
2022 for rev in nrevs:
2022 for rev in nrevs:
2023 yield change(rev)
2023 yield change(rev)
2024
2024
2025 if stopiteration:
2025 if stopiteration:
2026 break
2026 break
2027
2027
2028 return iterate()
2028 return iterate()
2029
2029
2030 def add(ui, repo, match, prefix, uipathfn, explicitonly, **opts):
2030 def add(ui, repo, match, prefix, uipathfn, explicitonly, **opts):
2031 bad = []
2031 bad = []
2032
2032
2033 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2033 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2034 names = []
2034 names = []
2035 wctx = repo[None]
2035 wctx = repo[None]
2036 cca = None
2036 cca = None
2037 abort, warn = scmutil.checkportabilityalert(ui)
2037 abort, warn = scmutil.checkportabilityalert(ui)
2038 if abort or warn:
2038 if abort or warn:
2039 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2039 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2040
2040
2041 match = repo.narrowmatch(match, includeexact=True)
2041 match = repo.narrowmatch(match, includeexact=True)
2042 badmatch = matchmod.badmatch(match, badfn)
2042 badmatch = matchmod.badmatch(match, badfn)
2043 dirstate = repo.dirstate
2043 dirstate = repo.dirstate
2044 # We don't want to just call wctx.walk here, since it would return a lot of
2044 # We don't want to just call wctx.walk here, since it would return a lot of
2045 # clean files, which we aren't interested in and takes time.
2045 # clean files, which we aren't interested in and takes time.
2046 for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate),
2046 for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate),
2047 unknown=True, ignored=False, full=False)):
2047 unknown=True, ignored=False, full=False)):
2048 exact = match.exact(f)
2048 exact = match.exact(f)
2049 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2049 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2050 if cca:
2050 if cca:
2051 cca(f)
2051 cca(f)
2052 names.append(f)
2052 names.append(f)
2053 if ui.verbose or not exact:
2053 if ui.verbose or not exact:
2054 ui.status(_('adding %s\n') % uipathfn(f),
2054 ui.status(_('adding %s\n') % uipathfn(f),
2055 label='ui.addremove.added')
2055 label='ui.addremove.added')
2056
2056
2057 for subpath in sorted(wctx.substate):
2057 for subpath in sorted(wctx.substate):
2058 sub = wctx.sub(subpath)
2058 sub = wctx.sub(subpath)
2059 try:
2059 try:
2060 submatch = matchmod.subdirmatcher(subpath, match)
2060 submatch = matchmod.subdirmatcher(subpath, match)
2061 subprefix = repo.wvfs.reljoin(prefix, subpath)
2061 subprefix = repo.wvfs.reljoin(prefix, subpath)
2062 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2062 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2063 if opts.get(r'subrepos'):
2063 if opts.get(r'subrepos'):
2064 bad.extend(sub.add(ui, submatch, subprefix, subuipathfn, False,
2064 bad.extend(sub.add(ui, submatch, subprefix, subuipathfn, False,
2065 **opts))
2065 **opts))
2066 else:
2066 else:
2067 bad.extend(sub.add(ui, submatch, subprefix, subuipathfn, True,
2067 bad.extend(sub.add(ui, submatch, subprefix, subuipathfn, True,
2068 **opts))
2068 **opts))
2069 except error.LookupError:
2069 except error.LookupError:
2070 ui.status(_("skipping missing subrepository: %s\n")
2070 ui.status(_("skipping missing subrepository: %s\n")
2071 % uipathfn(subpath))
2071 % uipathfn(subpath))
2072
2072
2073 if not opts.get(r'dry_run'):
2073 if not opts.get(r'dry_run'):
2074 rejected = wctx.add(names, prefix)
2074 rejected = wctx.add(names, prefix)
2075 bad.extend(f for f in rejected if f in match.files())
2075 bad.extend(f for f in rejected if f in match.files())
2076 return bad
2076 return bad
2077
2077
2078 def addwebdirpath(repo, serverpath, webconf):
2078 def addwebdirpath(repo, serverpath, webconf):
2079 webconf[serverpath] = repo.root
2079 webconf[serverpath] = repo.root
2080 repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root))
2080 repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root))
2081
2081
2082 for r in repo.revs('filelog("path:.hgsub")'):
2082 for r in repo.revs('filelog("path:.hgsub")'):
2083 ctx = repo[r]
2083 ctx = repo[r]
2084 for subpath in ctx.substate:
2084 for subpath in ctx.substate:
2085 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2085 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2086
2086
2087 def forget(ui, repo, match, prefix, explicitonly, dryrun, interactive):
2087 def forget(ui, repo, match, prefix, uipathfn, explicitonly, dryrun,
2088 interactive):
2088 if dryrun and interactive:
2089 if dryrun and interactive:
2089 raise error.Abort(_("cannot specify both --dry-run and --interactive"))
2090 raise error.Abort(_("cannot specify both --dry-run and --interactive"))
2090 bad = []
2091 bad = []
2091 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2092 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2092 wctx = repo[None]
2093 wctx = repo[None]
2093 forgot = []
2094 forgot = []
2094
2095
2095 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2096 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2096 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2097 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2097 if explicitonly:
2098 if explicitonly:
2098 forget = [f for f in forget if match.exact(f)]
2099 forget = [f for f in forget if match.exact(f)]
2099
2100
2100 for subpath in sorted(wctx.substate):
2101 for subpath in sorted(wctx.substate):
2101 sub = wctx.sub(subpath)
2102 sub = wctx.sub(subpath)
2102 submatch = matchmod.subdirmatcher(subpath, match)
2103 submatch = matchmod.subdirmatcher(subpath, match)
2103 subprefix = repo.wvfs.reljoin(prefix, subpath)
2104 subprefix = repo.wvfs.reljoin(prefix, subpath)
2105 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2104 try:
2106 try:
2105 subbad, subforgot = sub.forget(submatch, subprefix, dryrun=dryrun,
2107 subbad, subforgot = sub.forget(submatch, subprefix, subuipathfn,
2108 dryrun=dryrun,
2106 interactive=interactive)
2109 interactive=interactive)
2107 bad.extend([subpath + '/' + f for f in subbad])
2110 bad.extend([subpath + '/' + f for f in subbad])
2108 forgot.extend([subpath + '/' + f for f in subforgot])
2111 forgot.extend([subpath + '/' + f for f in subforgot])
2109 except error.LookupError:
2112 except error.LookupError:
2110 ui.status(_("skipping missing subrepository: %s\n")
2113 ui.status(_("skipping missing subrepository: %s\n")
2111 % match.rel(subpath))
2114 % uipathfn(subpath))
2112
2115
2113 if not explicitonly:
2116 if not explicitonly:
2114 for f in match.files():
2117 for f in match.files():
2115 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2118 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2116 if f not in forgot:
2119 if f not in forgot:
2117 if repo.wvfs.exists(f):
2120 if repo.wvfs.exists(f):
2118 # Don't complain if the exact case match wasn't given.
2121 # Don't complain if the exact case match wasn't given.
2119 # But don't do this until after checking 'forgot', so
2122 # But don't do this until after checking 'forgot', so
2120 # that subrepo files aren't normalized, and this op is
2123 # that subrepo files aren't normalized, and this op is
2121 # purely from data cached by the status walk above.
2124 # purely from data cached by the status walk above.
2122 if repo.dirstate.normalize(f) in repo.dirstate:
2125 if repo.dirstate.normalize(f) in repo.dirstate:
2123 continue
2126 continue
2124 ui.warn(_('not removing %s: '
2127 ui.warn(_('not removing %s: '
2125 'file is already untracked\n')
2128 'file is already untracked\n')
2126 % match.rel(f))
2129 % uipathfn(f))
2127 bad.append(f)
2130 bad.append(f)
2128
2131
2129 if interactive:
2132 if interactive:
2130 responses = _('[Ynsa?]'
2133 responses = _('[Ynsa?]'
2131 '$$ &Yes, forget this file'
2134 '$$ &Yes, forget this file'
2132 '$$ &No, skip this file'
2135 '$$ &No, skip this file'
2133 '$$ &Skip remaining files'
2136 '$$ &Skip remaining files'
2134 '$$ Include &all remaining files'
2137 '$$ Include &all remaining files'
2135 '$$ &? (display help)')
2138 '$$ &? (display help)')
2136 for filename in forget[:]:
2139 for filename in forget[:]:
2137 r = ui.promptchoice(_('forget %s %s') % (filename, responses))
2140 r = ui.promptchoice(_('forget %s %s') % (filename, responses))
2138 if r == 4: # ?
2141 if r == 4: # ?
2139 while r == 4:
2142 while r == 4:
2140 for c, t in ui.extractchoices(responses)[1]:
2143 for c, t in ui.extractchoices(responses)[1]:
2141 ui.write('%s - %s\n' % (c, encoding.lower(t)))
2144 ui.write('%s - %s\n' % (c, encoding.lower(t)))
2142 r = ui.promptchoice(_('forget %s %s') % (filename,
2145 r = ui.promptchoice(_('forget %s %s') % (filename,
2143 responses))
2146 responses))
2144 if r == 0: # yes
2147 if r == 0: # yes
2145 continue
2148 continue
2146 elif r == 1: # no
2149 elif r == 1: # no
2147 forget.remove(filename)
2150 forget.remove(filename)
2148 elif r == 2: # Skip
2151 elif r == 2: # Skip
2149 fnindex = forget.index(filename)
2152 fnindex = forget.index(filename)
2150 del forget[fnindex:]
2153 del forget[fnindex:]
2151 break
2154 break
2152 elif r == 3: # All
2155 elif r == 3: # All
2153 break
2156 break
2154
2157
2155 for f in forget:
2158 for f in forget:
2156 if ui.verbose or not match.exact(f) or interactive:
2159 if ui.verbose or not match.exact(f) or interactive:
2157 ui.status(_('removing %s\n') % match.rel(f),
2160 ui.status(_('removing %s\n') % uipathfn(f),
2158 label='ui.addremove.removed')
2161 label='ui.addremove.removed')
2159
2162
2160 if not dryrun:
2163 if not dryrun:
2161 rejected = wctx.forget(forget, prefix)
2164 rejected = wctx.forget(forget, prefix)
2162 bad.extend(f for f in rejected if f in match.files())
2165 bad.extend(f for f in rejected if f in match.files())
2163 forgot.extend(f for f in forget if f not in rejected)
2166 forgot.extend(f for f in forget if f not in rejected)
2164 return bad, forgot
2167 return bad, forgot
2165
2168
2166 def files(ui, ctx, m, fm, fmt, subrepos):
2169 def files(ui, ctx, m, fm, fmt, subrepos):
2167 ret = 1
2170 ret = 1
2168
2171
2169 needsfctx = ui.verbose or {'size', 'flags'} & fm.datahint()
2172 needsfctx = ui.verbose or {'size', 'flags'} & fm.datahint()
2170 uipathfn = scmutil.getuipathfn(ctx.repo(), legacyrelativevalue=True)
2173 uipathfn = scmutil.getuipathfn(ctx.repo(), legacyrelativevalue=True)
2171 for f in ctx.matches(m):
2174 for f in ctx.matches(m):
2172 fm.startitem()
2175 fm.startitem()
2173 fm.context(ctx=ctx)
2176 fm.context(ctx=ctx)
2174 if needsfctx:
2177 if needsfctx:
2175 fc = ctx[f]
2178 fc = ctx[f]
2176 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2179 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2177 fm.data(path=f)
2180 fm.data(path=f)
2178 fm.plain(fmt % uipathfn(f))
2181 fm.plain(fmt % uipathfn(f))
2179 ret = 0
2182 ret = 0
2180
2183
2181 for subpath in sorted(ctx.substate):
2184 for subpath in sorted(ctx.substate):
2182 submatch = matchmod.subdirmatcher(subpath, m)
2185 submatch = matchmod.subdirmatcher(subpath, m)
2183 if (subrepos or m.exact(subpath) or any(submatch.files())):
2186 if (subrepos or m.exact(subpath) or any(submatch.files())):
2184 sub = ctx.sub(subpath)
2187 sub = ctx.sub(subpath)
2185 try:
2188 try:
2186 recurse = m.exact(subpath) or subrepos
2189 recurse = m.exact(subpath) or subrepos
2187 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2190 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2188 ret = 0
2191 ret = 0
2189 except error.LookupError:
2192 except error.LookupError:
2190 ui.status(_("skipping missing subrepository: %s\n")
2193 ui.status(_("skipping missing subrepository: %s\n")
2191 % m.rel(subpath))
2194 % m.rel(subpath))
2192
2195
2193 return ret
2196 return ret
2194
2197
2195 def remove(ui, repo, m, prefix, uipathfn, after, force, subrepos, dryrun,
2198 def remove(ui, repo, m, prefix, uipathfn, after, force, subrepos, dryrun,
2196 warnings=None):
2199 warnings=None):
2197 ret = 0
2200 ret = 0
2198 s = repo.status(match=m, clean=True)
2201 s = repo.status(match=m, clean=True)
2199 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2202 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2200
2203
2201 wctx = repo[None]
2204 wctx = repo[None]
2202
2205
2203 if warnings is None:
2206 if warnings is None:
2204 warnings = []
2207 warnings = []
2205 warn = True
2208 warn = True
2206 else:
2209 else:
2207 warn = False
2210 warn = False
2208
2211
2209 subs = sorted(wctx.substate)
2212 subs = sorted(wctx.substate)
2210 progress = ui.makeprogress(_('searching'), total=len(subs),
2213 progress = ui.makeprogress(_('searching'), total=len(subs),
2211 unit=_('subrepos'))
2214 unit=_('subrepos'))
2212 for subpath in subs:
2215 for subpath in subs:
2213 submatch = matchmod.subdirmatcher(subpath, m)
2216 submatch = matchmod.subdirmatcher(subpath, m)
2214 subprefix = repo.wvfs.reljoin(prefix, subpath)
2217 subprefix = repo.wvfs.reljoin(prefix, subpath)
2215 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2218 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2216 if subrepos or m.exact(subpath) or any(submatch.files()):
2219 if subrepos or m.exact(subpath) or any(submatch.files()):
2217 progress.increment()
2220 progress.increment()
2218 sub = wctx.sub(subpath)
2221 sub = wctx.sub(subpath)
2219 try:
2222 try:
2220 if sub.removefiles(submatch, subprefix, subuipathfn, after,
2223 if sub.removefiles(submatch, subprefix, subuipathfn, after,
2221 force, subrepos, dryrun, warnings):
2224 force, subrepos, dryrun, warnings):
2222 ret = 1
2225 ret = 1
2223 except error.LookupError:
2226 except error.LookupError:
2224 warnings.append(_("skipping missing subrepository: %s\n")
2227 warnings.append(_("skipping missing subrepository: %s\n")
2225 % uipathfn(subpath))
2228 % uipathfn(subpath))
2226 progress.complete()
2229 progress.complete()
2227
2230
2228 # warn about failure to delete explicit files/dirs
2231 # warn about failure to delete explicit files/dirs
2229 deleteddirs = util.dirs(deleted)
2232 deleteddirs = util.dirs(deleted)
2230 files = m.files()
2233 files = m.files()
2231 progress = ui.makeprogress(_('deleting'), total=len(files),
2234 progress = ui.makeprogress(_('deleting'), total=len(files),
2232 unit=_('files'))
2235 unit=_('files'))
2233 for f in files:
2236 for f in files:
2234 def insubrepo():
2237 def insubrepo():
2235 for subpath in wctx.substate:
2238 for subpath in wctx.substate:
2236 if f.startswith(subpath + '/'):
2239 if f.startswith(subpath + '/'):
2237 return True
2240 return True
2238 return False
2241 return False
2239
2242
2240 progress.increment()
2243 progress.increment()
2241 isdir = f in deleteddirs or wctx.hasdir(f)
2244 isdir = f in deleteddirs or wctx.hasdir(f)
2242 if (f in repo.dirstate or isdir or f == '.'
2245 if (f in repo.dirstate or isdir or f == '.'
2243 or insubrepo() or f in subs):
2246 or insubrepo() or f in subs):
2244 continue
2247 continue
2245
2248
2246 if repo.wvfs.exists(f):
2249 if repo.wvfs.exists(f):
2247 if repo.wvfs.isdir(f):
2250 if repo.wvfs.isdir(f):
2248 warnings.append(_('not removing %s: no tracked files\n')
2251 warnings.append(_('not removing %s: no tracked files\n')
2249 % uipathfn(f))
2252 % uipathfn(f))
2250 else:
2253 else:
2251 warnings.append(_('not removing %s: file is untracked\n')
2254 warnings.append(_('not removing %s: file is untracked\n')
2252 % uipathfn(f))
2255 % uipathfn(f))
2253 # missing files will generate a warning elsewhere
2256 # missing files will generate a warning elsewhere
2254 ret = 1
2257 ret = 1
2255 progress.complete()
2258 progress.complete()
2256
2259
2257 if force:
2260 if force:
2258 list = modified + deleted + clean + added
2261 list = modified + deleted + clean + added
2259 elif after:
2262 elif after:
2260 list = deleted
2263 list = deleted
2261 remaining = modified + added + clean
2264 remaining = modified + added + clean
2262 progress = ui.makeprogress(_('skipping'), total=len(remaining),
2265 progress = ui.makeprogress(_('skipping'), total=len(remaining),
2263 unit=_('files'))
2266 unit=_('files'))
2264 for f in remaining:
2267 for f in remaining:
2265 progress.increment()
2268 progress.increment()
2266 if ui.verbose or (f in files):
2269 if ui.verbose or (f in files):
2267 warnings.append(_('not removing %s: file still exists\n')
2270 warnings.append(_('not removing %s: file still exists\n')
2268 % uipathfn(f))
2271 % uipathfn(f))
2269 ret = 1
2272 ret = 1
2270 progress.complete()
2273 progress.complete()
2271 else:
2274 else:
2272 list = deleted + clean
2275 list = deleted + clean
2273 progress = ui.makeprogress(_('skipping'),
2276 progress = ui.makeprogress(_('skipping'),
2274 total=(len(modified) + len(added)),
2277 total=(len(modified) + len(added)),
2275 unit=_('files'))
2278 unit=_('files'))
2276 for f in modified:
2279 for f in modified:
2277 progress.increment()
2280 progress.increment()
2278 warnings.append(_('not removing %s: file is modified (use -f'
2281 warnings.append(_('not removing %s: file is modified (use -f'
2279 ' to force removal)\n') % uipathfn(f))
2282 ' to force removal)\n') % uipathfn(f))
2280 ret = 1
2283 ret = 1
2281 for f in added:
2284 for f in added:
2282 progress.increment()
2285 progress.increment()
2283 warnings.append(_("not removing %s: file has been marked for add"
2286 warnings.append(_("not removing %s: file has been marked for add"
2284 " (use 'hg forget' to undo add)\n") % uipathfn(f))
2287 " (use 'hg forget' to undo add)\n") % uipathfn(f))
2285 ret = 1
2288 ret = 1
2286 progress.complete()
2289 progress.complete()
2287
2290
2288 list = sorted(list)
2291 list = sorted(list)
2289 progress = ui.makeprogress(_('deleting'), total=len(list),
2292 progress = ui.makeprogress(_('deleting'), total=len(list),
2290 unit=_('files'))
2293 unit=_('files'))
2291 for f in list:
2294 for f in list:
2292 if ui.verbose or not m.exact(f):
2295 if ui.verbose or not m.exact(f):
2293 progress.increment()
2296 progress.increment()
2294 ui.status(_('removing %s\n') % uipathfn(f),
2297 ui.status(_('removing %s\n') % uipathfn(f),
2295 label='ui.addremove.removed')
2298 label='ui.addremove.removed')
2296 progress.complete()
2299 progress.complete()
2297
2300
2298 if not dryrun:
2301 if not dryrun:
2299 with repo.wlock():
2302 with repo.wlock():
2300 if not after:
2303 if not after:
2301 for f in list:
2304 for f in list:
2302 if f in added:
2305 if f in added:
2303 continue # we never unlink added files on remove
2306 continue # we never unlink added files on remove
2304 rmdir = repo.ui.configbool('experimental',
2307 rmdir = repo.ui.configbool('experimental',
2305 'removeemptydirs')
2308 'removeemptydirs')
2306 repo.wvfs.unlinkpath(f, ignoremissing=True, rmdir=rmdir)
2309 repo.wvfs.unlinkpath(f, ignoremissing=True, rmdir=rmdir)
2307 repo[None].forget(list)
2310 repo[None].forget(list)
2308
2311
2309 if warn:
2312 if warn:
2310 for warning in warnings:
2313 for warning in warnings:
2311 ui.warn(warning)
2314 ui.warn(warning)
2312
2315
2313 return ret
2316 return ret
2314
2317
2315 def _updatecatformatter(fm, ctx, matcher, path, decode):
2318 def _updatecatformatter(fm, ctx, matcher, path, decode):
2316 """Hook for adding data to the formatter used by ``hg cat``.
2319 """Hook for adding data to the formatter used by ``hg cat``.
2317
2320
2318 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2321 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2319 this method first."""
2322 this method first."""
2320 data = ctx[path].data()
2323 data = ctx[path].data()
2321 if decode:
2324 if decode:
2322 data = ctx.repo().wwritedata(path, data)
2325 data = ctx.repo().wwritedata(path, data)
2323 fm.startitem()
2326 fm.startitem()
2324 fm.context(ctx=ctx)
2327 fm.context(ctx=ctx)
2325 fm.write('data', '%s', data)
2328 fm.write('data', '%s', data)
2326 fm.data(path=path)
2329 fm.data(path=path)
2327
2330
2328 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2331 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2329 err = 1
2332 err = 1
2330 opts = pycompat.byteskwargs(opts)
2333 opts = pycompat.byteskwargs(opts)
2331
2334
2332 def write(path):
2335 def write(path):
2333 filename = None
2336 filename = None
2334 if fntemplate:
2337 if fntemplate:
2335 filename = makefilename(ctx, fntemplate,
2338 filename = makefilename(ctx, fntemplate,
2336 pathname=os.path.join(prefix, path))
2339 pathname=os.path.join(prefix, path))
2337 # attempt to create the directory if it does not already exist
2340 # attempt to create the directory if it does not already exist
2338 try:
2341 try:
2339 os.makedirs(os.path.dirname(filename))
2342 os.makedirs(os.path.dirname(filename))
2340 except OSError:
2343 except OSError:
2341 pass
2344 pass
2342 with formatter.maybereopen(basefm, filename) as fm:
2345 with formatter.maybereopen(basefm, filename) as fm:
2343 _updatecatformatter(fm, ctx, matcher, path, opts.get('decode'))
2346 _updatecatformatter(fm, ctx, matcher, path, opts.get('decode'))
2344
2347
2345 # Automation often uses hg cat on single files, so special case it
2348 # Automation often uses hg cat on single files, so special case it
2346 # for performance to avoid the cost of parsing the manifest.
2349 # for performance to avoid the cost of parsing the manifest.
2347 if len(matcher.files()) == 1 and not matcher.anypats():
2350 if len(matcher.files()) == 1 and not matcher.anypats():
2348 file = matcher.files()[0]
2351 file = matcher.files()[0]
2349 mfl = repo.manifestlog
2352 mfl = repo.manifestlog
2350 mfnode = ctx.manifestnode()
2353 mfnode = ctx.manifestnode()
2351 try:
2354 try:
2352 if mfnode and mfl[mfnode].find(file)[0]:
2355 if mfnode and mfl[mfnode].find(file)[0]:
2353 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2356 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2354 write(file)
2357 write(file)
2355 return 0
2358 return 0
2356 except KeyError:
2359 except KeyError:
2357 pass
2360 pass
2358
2361
2359 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2362 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2360
2363
2361 for abs in ctx.walk(matcher):
2364 for abs in ctx.walk(matcher):
2362 write(abs)
2365 write(abs)
2363 err = 0
2366 err = 0
2364
2367
2365 for subpath in sorted(ctx.substate):
2368 for subpath in sorted(ctx.substate):
2366 sub = ctx.sub(subpath)
2369 sub = ctx.sub(subpath)
2367 try:
2370 try:
2368 submatch = matchmod.subdirmatcher(subpath, matcher)
2371 submatch = matchmod.subdirmatcher(subpath, matcher)
2369 subprefix = os.path.join(prefix, subpath)
2372 subprefix = os.path.join(prefix, subpath)
2370 if not sub.cat(submatch, basefm, fntemplate, subprefix,
2373 if not sub.cat(submatch, basefm, fntemplate, subprefix,
2371 **pycompat.strkwargs(opts)):
2374 **pycompat.strkwargs(opts)):
2372 err = 0
2375 err = 0
2373 except error.RepoLookupError:
2376 except error.RepoLookupError:
2374 ui.status(_("skipping missing subrepository: %s\n") %
2377 ui.status(_("skipping missing subrepository: %s\n") %
2375 matcher.rel(subpath))
2378 matcher.rel(subpath))
2376
2379
2377 return err
2380 return err
2378
2381
2379 def commit(ui, repo, commitfunc, pats, opts):
2382 def commit(ui, repo, commitfunc, pats, opts):
2380 '''commit the specified files or all outstanding changes'''
2383 '''commit the specified files or all outstanding changes'''
2381 date = opts.get('date')
2384 date = opts.get('date')
2382 if date:
2385 if date:
2383 opts['date'] = dateutil.parsedate(date)
2386 opts['date'] = dateutil.parsedate(date)
2384 message = logmessage(ui, opts)
2387 message = logmessage(ui, opts)
2385 matcher = scmutil.match(repo[None], pats, opts)
2388 matcher = scmutil.match(repo[None], pats, opts)
2386
2389
2387 dsguard = None
2390 dsguard = None
2388 # extract addremove carefully -- this function can be called from a command
2391 # extract addremove carefully -- this function can be called from a command
2389 # that doesn't support addremove
2392 # that doesn't support addremove
2390 if opts.get('addremove'):
2393 if opts.get('addremove'):
2391 dsguard = dirstateguard.dirstateguard(repo, 'commit')
2394 dsguard = dirstateguard.dirstateguard(repo, 'commit')
2392 with dsguard or util.nullcontextmanager():
2395 with dsguard or util.nullcontextmanager():
2393 if dsguard:
2396 if dsguard:
2394 relative = scmutil.anypats(pats, opts)
2397 relative = scmutil.anypats(pats, opts)
2395 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=relative)
2398 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=relative)
2396 if scmutil.addremove(repo, matcher, "", uipathfn, opts) != 0:
2399 if scmutil.addremove(repo, matcher, "", uipathfn, opts) != 0:
2397 raise error.Abort(
2400 raise error.Abort(
2398 _("failed to mark all new/missing files as added/removed"))
2401 _("failed to mark all new/missing files as added/removed"))
2399
2402
2400 return commitfunc(ui, repo, message, matcher, opts)
2403 return commitfunc(ui, repo, message, matcher, opts)
2401
2404
2402 def samefile(f, ctx1, ctx2):
2405 def samefile(f, ctx1, ctx2):
2403 if f in ctx1.manifest():
2406 if f in ctx1.manifest():
2404 a = ctx1.filectx(f)
2407 a = ctx1.filectx(f)
2405 if f in ctx2.manifest():
2408 if f in ctx2.manifest():
2406 b = ctx2.filectx(f)
2409 b = ctx2.filectx(f)
2407 return (not a.cmp(b)
2410 return (not a.cmp(b)
2408 and a.flags() == b.flags())
2411 and a.flags() == b.flags())
2409 else:
2412 else:
2410 return False
2413 return False
2411 else:
2414 else:
2412 return f not in ctx2.manifest()
2415 return f not in ctx2.manifest()
2413
2416
2414 def amend(ui, repo, old, extra, pats, opts):
2417 def amend(ui, repo, old, extra, pats, opts):
2415 # avoid cycle context -> subrepo -> cmdutil
2418 # avoid cycle context -> subrepo -> cmdutil
2416 from . import context
2419 from . import context
2417
2420
2418 # amend will reuse the existing user if not specified, but the obsolete
2421 # amend will reuse the existing user if not specified, but the obsolete
2419 # marker creation requires that the current user's name is specified.
2422 # marker creation requires that the current user's name is specified.
2420 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2423 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2421 ui.username() # raise exception if username not set
2424 ui.username() # raise exception if username not set
2422
2425
2423 ui.note(_('amending changeset %s\n') % old)
2426 ui.note(_('amending changeset %s\n') % old)
2424 base = old.p1()
2427 base = old.p1()
2425
2428
2426 with repo.wlock(), repo.lock(), repo.transaction('amend'):
2429 with repo.wlock(), repo.lock(), repo.transaction('amend'):
2427 # Participating changesets:
2430 # Participating changesets:
2428 #
2431 #
2429 # wctx o - workingctx that contains changes from working copy
2432 # wctx o - workingctx that contains changes from working copy
2430 # | to go into amending commit
2433 # | to go into amending commit
2431 # |
2434 # |
2432 # old o - changeset to amend
2435 # old o - changeset to amend
2433 # |
2436 # |
2434 # base o - first parent of the changeset to amend
2437 # base o - first parent of the changeset to amend
2435 wctx = repo[None]
2438 wctx = repo[None]
2436
2439
2437 # Copy to avoid mutating input
2440 # Copy to avoid mutating input
2438 extra = extra.copy()
2441 extra = extra.copy()
2439 # Update extra dict from amended commit (e.g. to preserve graft
2442 # Update extra dict from amended commit (e.g. to preserve graft
2440 # source)
2443 # source)
2441 extra.update(old.extra())
2444 extra.update(old.extra())
2442
2445
2443 # Also update it from the from the wctx
2446 # Also update it from the from the wctx
2444 extra.update(wctx.extra())
2447 extra.update(wctx.extra())
2445
2448
2446 user = opts.get('user') or old.user()
2449 user = opts.get('user') or old.user()
2447
2450
2448 datemaydiffer = False # date-only change should be ignored?
2451 datemaydiffer = False # date-only change should be ignored?
2449 if opts.get('date') and opts.get('currentdate'):
2452 if opts.get('date') and opts.get('currentdate'):
2450 raise error.Abort(_('--date and --currentdate are mutually '
2453 raise error.Abort(_('--date and --currentdate are mutually '
2451 'exclusive'))
2454 'exclusive'))
2452 if opts.get('date'):
2455 if opts.get('date'):
2453 date = dateutil.parsedate(opts.get('date'))
2456 date = dateutil.parsedate(opts.get('date'))
2454 elif opts.get('currentdate'):
2457 elif opts.get('currentdate'):
2455 date = dateutil.makedate()
2458 date = dateutil.makedate()
2456 elif (ui.configbool('rewrite', 'update-timestamp')
2459 elif (ui.configbool('rewrite', 'update-timestamp')
2457 and opts.get('currentdate') is None):
2460 and opts.get('currentdate') is None):
2458 date = dateutil.makedate()
2461 date = dateutil.makedate()
2459 datemaydiffer = True
2462 datemaydiffer = True
2460 else:
2463 else:
2461 date = old.date()
2464 date = old.date()
2462
2465
2463 if len(old.parents()) > 1:
2466 if len(old.parents()) > 1:
2464 # ctx.files() isn't reliable for merges, so fall back to the
2467 # ctx.files() isn't reliable for merges, so fall back to the
2465 # slower repo.status() method
2468 # slower repo.status() method
2466 files = set([fn for st in base.status(old)[:3]
2469 files = set([fn for st in base.status(old)[:3]
2467 for fn in st])
2470 for fn in st])
2468 else:
2471 else:
2469 files = set(old.files())
2472 files = set(old.files())
2470
2473
2471 # add/remove the files to the working copy if the "addremove" option
2474 # add/remove the files to the working copy if the "addremove" option
2472 # was specified.
2475 # was specified.
2473 matcher = scmutil.match(wctx, pats, opts)
2476 matcher = scmutil.match(wctx, pats, opts)
2474 relative = scmutil.anypats(pats, opts)
2477 relative = scmutil.anypats(pats, opts)
2475 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=relative)
2478 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=relative)
2476 if (opts.get('addremove')
2479 if (opts.get('addremove')
2477 and scmutil.addremove(repo, matcher, "", uipathfn, opts)):
2480 and scmutil.addremove(repo, matcher, "", uipathfn, opts)):
2478 raise error.Abort(
2481 raise error.Abort(
2479 _("failed to mark all new/missing files as added/removed"))
2482 _("failed to mark all new/missing files as added/removed"))
2480
2483
2481 # Check subrepos. This depends on in-place wctx._status update in
2484 # Check subrepos. This depends on in-place wctx._status update in
2482 # subrepo.precommit(). To minimize the risk of this hack, we do
2485 # subrepo.precommit(). To minimize the risk of this hack, we do
2483 # nothing if .hgsub does not exist.
2486 # nothing if .hgsub does not exist.
2484 if '.hgsub' in wctx or '.hgsub' in old:
2487 if '.hgsub' in wctx or '.hgsub' in old:
2485 subs, commitsubs, newsubstate = subrepoutil.precommit(
2488 subs, commitsubs, newsubstate = subrepoutil.precommit(
2486 ui, wctx, wctx._status, matcher)
2489 ui, wctx, wctx._status, matcher)
2487 # amend should abort if commitsubrepos is enabled
2490 # amend should abort if commitsubrepos is enabled
2488 assert not commitsubs
2491 assert not commitsubs
2489 if subs:
2492 if subs:
2490 subrepoutil.writestate(repo, newsubstate)
2493 subrepoutil.writestate(repo, newsubstate)
2491
2494
2492 ms = mergemod.mergestate.read(repo)
2495 ms = mergemod.mergestate.read(repo)
2493 mergeutil.checkunresolved(ms)
2496 mergeutil.checkunresolved(ms)
2494
2497
2495 filestoamend = set(f for f in wctx.files() if matcher(f))
2498 filestoamend = set(f for f in wctx.files() if matcher(f))
2496
2499
2497 changes = (len(filestoamend) > 0)
2500 changes = (len(filestoamend) > 0)
2498 if changes:
2501 if changes:
2499 # Recompute copies (avoid recording a -> b -> a)
2502 # Recompute copies (avoid recording a -> b -> a)
2500 copied = copies.pathcopies(base, wctx, matcher)
2503 copied = copies.pathcopies(base, wctx, matcher)
2501 if old.p2:
2504 if old.p2:
2502 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
2505 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
2503
2506
2504 # Prune files which were reverted by the updates: if old
2507 # Prune files which were reverted by the updates: if old
2505 # introduced file X and the file was renamed in the working
2508 # introduced file X and the file was renamed in the working
2506 # copy, then those two files are the same and
2509 # copy, then those two files are the same and
2507 # we can discard X from our list of files. Likewise if X
2510 # we can discard X from our list of files. Likewise if X
2508 # was removed, it's no longer relevant. If X is missing (aka
2511 # was removed, it's no longer relevant. If X is missing (aka
2509 # deleted), old X must be preserved.
2512 # deleted), old X must be preserved.
2510 files.update(filestoamend)
2513 files.update(filestoamend)
2511 files = [f for f in files if (not samefile(f, wctx, base)
2514 files = [f for f in files if (not samefile(f, wctx, base)
2512 or f in wctx.deleted())]
2515 or f in wctx.deleted())]
2513
2516
2514 def filectxfn(repo, ctx_, path):
2517 def filectxfn(repo, ctx_, path):
2515 try:
2518 try:
2516 # If the file being considered is not amongst the files
2519 # If the file being considered is not amongst the files
2517 # to be amended, we should return the file context from the
2520 # to be amended, we should return the file context from the
2518 # old changeset. This avoids issues when only some files in
2521 # old changeset. This avoids issues when only some files in
2519 # the working copy are being amended but there are also
2522 # the working copy are being amended but there are also
2520 # changes to other files from the old changeset.
2523 # changes to other files from the old changeset.
2521 if path not in filestoamend:
2524 if path not in filestoamend:
2522 return old.filectx(path)
2525 return old.filectx(path)
2523
2526
2524 # Return None for removed files.
2527 # Return None for removed files.
2525 if path in wctx.removed():
2528 if path in wctx.removed():
2526 return None
2529 return None
2527
2530
2528 fctx = wctx[path]
2531 fctx = wctx[path]
2529 flags = fctx.flags()
2532 flags = fctx.flags()
2530 mctx = context.memfilectx(repo, ctx_,
2533 mctx = context.memfilectx(repo, ctx_,
2531 fctx.path(), fctx.data(),
2534 fctx.path(), fctx.data(),
2532 islink='l' in flags,
2535 islink='l' in flags,
2533 isexec='x' in flags,
2536 isexec='x' in flags,
2534 copied=copied.get(path))
2537 copied=copied.get(path))
2535 return mctx
2538 return mctx
2536 except KeyError:
2539 except KeyError:
2537 return None
2540 return None
2538 else:
2541 else:
2539 ui.note(_('copying changeset %s to %s\n') % (old, base))
2542 ui.note(_('copying changeset %s to %s\n') % (old, base))
2540
2543
2541 # Use version of files as in the old cset
2544 # Use version of files as in the old cset
2542 def filectxfn(repo, ctx_, path):
2545 def filectxfn(repo, ctx_, path):
2543 try:
2546 try:
2544 return old.filectx(path)
2547 return old.filectx(path)
2545 except KeyError:
2548 except KeyError:
2546 return None
2549 return None
2547
2550
2548 # See if we got a message from -m or -l, if not, open the editor with
2551 # See if we got a message from -m or -l, if not, open the editor with
2549 # the message of the changeset to amend.
2552 # the message of the changeset to amend.
2550 message = logmessage(ui, opts)
2553 message = logmessage(ui, opts)
2551
2554
2552 editform = mergeeditform(old, 'commit.amend')
2555 editform = mergeeditform(old, 'commit.amend')
2553 editor = getcommiteditor(editform=editform,
2556 editor = getcommiteditor(editform=editform,
2554 **pycompat.strkwargs(opts))
2557 **pycompat.strkwargs(opts))
2555
2558
2556 if not message:
2559 if not message:
2557 editor = getcommiteditor(edit=True, editform=editform)
2560 editor = getcommiteditor(edit=True, editform=editform)
2558 message = old.description()
2561 message = old.description()
2559
2562
2560 pureextra = extra.copy()
2563 pureextra = extra.copy()
2561 extra['amend_source'] = old.hex()
2564 extra['amend_source'] = old.hex()
2562
2565
2563 new = context.memctx(repo,
2566 new = context.memctx(repo,
2564 parents=[base.node(), old.p2().node()],
2567 parents=[base.node(), old.p2().node()],
2565 text=message,
2568 text=message,
2566 files=files,
2569 files=files,
2567 filectxfn=filectxfn,
2570 filectxfn=filectxfn,
2568 user=user,
2571 user=user,
2569 date=date,
2572 date=date,
2570 extra=extra,
2573 extra=extra,
2571 editor=editor)
2574 editor=editor)
2572
2575
2573 newdesc = changelog.stripdesc(new.description())
2576 newdesc = changelog.stripdesc(new.description())
2574 if ((not changes)
2577 if ((not changes)
2575 and newdesc == old.description()
2578 and newdesc == old.description()
2576 and user == old.user()
2579 and user == old.user()
2577 and (date == old.date() or datemaydiffer)
2580 and (date == old.date() or datemaydiffer)
2578 and pureextra == old.extra()):
2581 and pureextra == old.extra()):
2579 # nothing changed. continuing here would create a new node
2582 # nothing changed. continuing here would create a new node
2580 # anyway because of the amend_source noise.
2583 # anyway because of the amend_source noise.
2581 #
2584 #
2582 # This not what we expect from amend.
2585 # This not what we expect from amend.
2583 return old.node()
2586 return old.node()
2584
2587
2585 commitphase = None
2588 commitphase = None
2586 if opts.get('secret'):
2589 if opts.get('secret'):
2587 commitphase = phases.secret
2590 commitphase = phases.secret
2588 newid = repo.commitctx(new)
2591 newid = repo.commitctx(new)
2589
2592
2590 # Reroute the working copy parent to the new changeset
2593 # Reroute the working copy parent to the new changeset
2591 repo.setparents(newid, nullid)
2594 repo.setparents(newid, nullid)
2592 mapping = {old.node(): (newid,)}
2595 mapping = {old.node(): (newid,)}
2593 obsmetadata = None
2596 obsmetadata = None
2594 if opts.get('note'):
2597 if opts.get('note'):
2595 obsmetadata = {'note': encoding.fromlocal(opts['note'])}
2598 obsmetadata = {'note': encoding.fromlocal(opts['note'])}
2596 backup = ui.configbool('rewrite', 'backup-bundle')
2599 backup = ui.configbool('rewrite', 'backup-bundle')
2597 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata,
2600 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata,
2598 fixphase=True, targetphase=commitphase,
2601 fixphase=True, targetphase=commitphase,
2599 backup=backup)
2602 backup=backup)
2600
2603
2601 # Fixing the dirstate because localrepo.commitctx does not update
2604 # Fixing the dirstate because localrepo.commitctx does not update
2602 # it. This is rather convenient because we did not need to update
2605 # it. This is rather convenient because we did not need to update
2603 # the dirstate for all the files in the new commit which commitctx
2606 # the dirstate for all the files in the new commit which commitctx
2604 # could have done if it updated the dirstate. Now, we can
2607 # could have done if it updated the dirstate. Now, we can
2605 # selectively update the dirstate only for the amended files.
2608 # selectively update the dirstate only for the amended files.
2606 dirstate = repo.dirstate
2609 dirstate = repo.dirstate
2607
2610
2608 # Update the state of the files which were added and
2611 # Update the state of the files which were added and
2609 # and modified in the amend to "normal" in the dirstate.
2612 # and modified in the amend to "normal" in the dirstate.
2610 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
2613 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
2611 for f in normalfiles:
2614 for f in normalfiles:
2612 dirstate.normal(f)
2615 dirstate.normal(f)
2613
2616
2614 # Update the state of files which were removed in the amend
2617 # Update the state of files which were removed in the amend
2615 # to "removed" in the dirstate.
2618 # to "removed" in the dirstate.
2616 removedfiles = set(wctx.removed()) & filestoamend
2619 removedfiles = set(wctx.removed()) & filestoamend
2617 for f in removedfiles:
2620 for f in removedfiles:
2618 dirstate.drop(f)
2621 dirstate.drop(f)
2619
2622
2620 return newid
2623 return newid
2621
2624
2622 def commiteditor(repo, ctx, subs, editform=''):
2625 def commiteditor(repo, ctx, subs, editform=''):
2623 if ctx.description():
2626 if ctx.description():
2624 return ctx.description()
2627 return ctx.description()
2625 return commitforceeditor(repo, ctx, subs, editform=editform,
2628 return commitforceeditor(repo, ctx, subs, editform=editform,
2626 unchangedmessagedetection=True)
2629 unchangedmessagedetection=True)
2627
2630
2628 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2631 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2629 editform='', unchangedmessagedetection=False):
2632 editform='', unchangedmessagedetection=False):
2630 if not extramsg:
2633 if not extramsg:
2631 extramsg = _("Leave message empty to abort commit.")
2634 extramsg = _("Leave message empty to abort commit.")
2632
2635
2633 forms = [e for e in editform.split('.') if e]
2636 forms = [e for e in editform.split('.') if e]
2634 forms.insert(0, 'changeset')
2637 forms.insert(0, 'changeset')
2635 templatetext = None
2638 templatetext = None
2636 while forms:
2639 while forms:
2637 ref = '.'.join(forms)
2640 ref = '.'.join(forms)
2638 if repo.ui.config('committemplate', ref):
2641 if repo.ui.config('committemplate', ref):
2639 templatetext = committext = buildcommittemplate(
2642 templatetext = committext = buildcommittemplate(
2640 repo, ctx, subs, extramsg, ref)
2643 repo, ctx, subs, extramsg, ref)
2641 break
2644 break
2642 forms.pop()
2645 forms.pop()
2643 else:
2646 else:
2644 committext = buildcommittext(repo, ctx, subs, extramsg)
2647 committext = buildcommittext(repo, ctx, subs, extramsg)
2645
2648
2646 # run editor in the repository root
2649 # run editor in the repository root
2647 olddir = encoding.getcwd()
2650 olddir = encoding.getcwd()
2648 os.chdir(repo.root)
2651 os.chdir(repo.root)
2649
2652
2650 # make in-memory changes visible to external process
2653 # make in-memory changes visible to external process
2651 tr = repo.currenttransaction()
2654 tr = repo.currenttransaction()
2652 repo.dirstate.write(tr)
2655 repo.dirstate.write(tr)
2653 pending = tr and tr.writepending() and repo.root
2656 pending = tr and tr.writepending() and repo.root
2654
2657
2655 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
2658 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
2656 editform=editform, pending=pending,
2659 editform=editform, pending=pending,
2657 repopath=repo.path, action='commit')
2660 repopath=repo.path, action='commit')
2658 text = editortext
2661 text = editortext
2659
2662
2660 # strip away anything below this special string (used for editors that want
2663 # strip away anything below this special string (used for editors that want
2661 # to display the diff)
2664 # to display the diff)
2662 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
2665 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
2663 if stripbelow:
2666 if stripbelow:
2664 text = text[:stripbelow.start()]
2667 text = text[:stripbelow.start()]
2665
2668
2666 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2669 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2667 os.chdir(olddir)
2670 os.chdir(olddir)
2668
2671
2669 if finishdesc:
2672 if finishdesc:
2670 text = finishdesc(text)
2673 text = finishdesc(text)
2671 if not text.strip():
2674 if not text.strip():
2672 raise error.Abort(_("empty commit message"))
2675 raise error.Abort(_("empty commit message"))
2673 if unchangedmessagedetection and editortext == templatetext:
2676 if unchangedmessagedetection and editortext == templatetext:
2674 raise error.Abort(_("commit message unchanged"))
2677 raise error.Abort(_("commit message unchanged"))
2675
2678
2676 return text
2679 return text
2677
2680
2678 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
2681 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
2679 ui = repo.ui
2682 ui = repo.ui
2680 spec = formatter.templatespec(ref, None, None)
2683 spec = formatter.templatespec(ref, None, None)
2681 t = logcmdutil.changesettemplater(ui, repo, spec)
2684 t = logcmdutil.changesettemplater(ui, repo, spec)
2682 t.t.cache.update((k, templater.unquotestring(v))
2685 t.t.cache.update((k, templater.unquotestring(v))
2683 for k, v in repo.ui.configitems('committemplate'))
2686 for k, v in repo.ui.configitems('committemplate'))
2684
2687
2685 if not extramsg:
2688 if not extramsg:
2686 extramsg = '' # ensure that extramsg is string
2689 extramsg = '' # ensure that extramsg is string
2687
2690
2688 ui.pushbuffer()
2691 ui.pushbuffer()
2689 t.show(ctx, extramsg=extramsg)
2692 t.show(ctx, extramsg=extramsg)
2690 return ui.popbuffer()
2693 return ui.popbuffer()
2691
2694
2692 def hgprefix(msg):
2695 def hgprefix(msg):
2693 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
2696 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
2694
2697
2695 def buildcommittext(repo, ctx, subs, extramsg):
2698 def buildcommittext(repo, ctx, subs, extramsg):
2696 edittext = []
2699 edittext = []
2697 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2700 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2698 if ctx.description():
2701 if ctx.description():
2699 edittext.append(ctx.description())
2702 edittext.append(ctx.description())
2700 edittext.append("")
2703 edittext.append("")
2701 edittext.append("") # Empty line between message and comments.
2704 edittext.append("") # Empty line between message and comments.
2702 edittext.append(hgprefix(_("Enter commit message."
2705 edittext.append(hgprefix(_("Enter commit message."
2703 " Lines beginning with 'HG:' are removed.")))
2706 " Lines beginning with 'HG:' are removed.")))
2704 edittext.append(hgprefix(extramsg))
2707 edittext.append(hgprefix(extramsg))
2705 edittext.append("HG: --")
2708 edittext.append("HG: --")
2706 edittext.append(hgprefix(_("user: %s") % ctx.user()))
2709 edittext.append(hgprefix(_("user: %s") % ctx.user()))
2707 if ctx.p2():
2710 if ctx.p2():
2708 edittext.append(hgprefix(_("branch merge")))
2711 edittext.append(hgprefix(_("branch merge")))
2709 if ctx.branch():
2712 if ctx.branch():
2710 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
2713 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
2711 if bookmarks.isactivewdirparent(repo):
2714 if bookmarks.isactivewdirparent(repo):
2712 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
2715 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
2713 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
2716 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
2714 edittext.extend([hgprefix(_("added %s") % f) for f in added])
2717 edittext.extend([hgprefix(_("added %s") % f) for f in added])
2715 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
2718 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
2716 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
2719 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
2717 if not added and not modified and not removed:
2720 if not added and not modified and not removed:
2718 edittext.append(hgprefix(_("no files changed")))
2721 edittext.append(hgprefix(_("no files changed")))
2719 edittext.append("")
2722 edittext.append("")
2720
2723
2721 return "\n".join(edittext)
2724 return "\n".join(edittext)
2722
2725
2723 def commitstatus(repo, node, branch, bheads=None, opts=None):
2726 def commitstatus(repo, node, branch, bheads=None, opts=None):
2724 if opts is None:
2727 if opts is None:
2725 opts = {}
2728 opts = {}
2726 ctx = repo[node]
2729 ctx = repo[node]
2727 parents = ctx.parents()
2730 parents = ctx.parents()
2728
2731
2729 if (not opts.get('amend') and bheads and node not in bheads and not
2732 if (not opts.get('amend') and bheads and node not in bheads and not
2730 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2733 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2731 repo.ui.status(_('created new head\n'))
2734 repo.ui.status(_('created new head\n'))
2732 # The message is not printed for initial roots. For the other
2735 # The message is not printed for initial roots. For the other
2733 # changesets, it is printed in the following situations:
2736 # changesets, it is printed in the following situations:
2734 #
2737 #
2735 # Par column: for the 2 parents with ...
2738 # Par column: for the 2 parents with ...
2736 # N: null or no parent
2739 # N: null or no parent
2737 # B: parent is on another named branch
2740 # B: parent is on another named branch
2738 # C: parent is a regular non head changeset
2741 # C: parent is a regular non head changeset
2739 # H: parent was a branch head of the current branch
2742 # H: parent was a branch head of the current branch
2740 # Msg column: whether we print "created new head" message
2743 # Msg column: whether we print "created new head" message
2741 # In the following, it is assumed that there already exists some
2744 # In the following, it is assumed that there already exists some
2742 # initial branch heads of the current branch, otherwise nothing is
2745 # initial branch heads of the current branch, otherwise nothing is
2743 # printed anyway.
2746 # printed anyway.
2744 #
2747 #
2745 # Par Msg Comment
2748 # Par Msg Comment
2746 # N N y additional topo root
2749 # N N y additional topo root
2747 #
2750 #
2748 # B N y additional branch root
2751 # B N y additional branch root
2749 # C N y additional topo head
2752 # C N y additional topo head
2750 # H N n usual case
2753 # H N n usual case
2751 #
2754 #
2752 # B B y weird additional branch root
2755 # B B y weird additional branch root
2753 # C B y branch merge
2756 # C B y branch merge
2754 # H B n merge with named branch
2757 # H B n merge with named branch
2755 #
2758 #
2756 # C C y additional head from merge
2759 # C C y additional head from merge
2757 # C H n merge with a head
2760 # C H n merge with a head
2758 #
2761 #
2759 # H H n head merge: head count decreases
2762 # H H n head merge: head count decreases
2760
2763
2761 if not opts.get('close_branch'):
2764 if not opts.get('close_branch'):
2762 for r in parents:
2765 for r in parents:
2763 if r.closesbranch() and r.branch() == branch:
2766 if r.closesbranch() and r.branch() == branch:
2764 repo.ui.status(_('reopening closed branch head %d\n') % r.rev())
2767 repo.ui.status(_('reopening closed branch head %d\n') % r.rev())
2765
2768
2766 if repo.ui.debugflag:
2769 if repo.ui.debugflag:
2767 repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx.hex()))
2770 repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx.hex()))
2768 elif repo.ui.verbose:
2771 elif repo.ui.verbose:
2769 repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx))
2772 repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx))
2770
2773
2771 def postcommitstatus(repo, pats, opts):
2774 def postcommitstatus(repo, pats, opts):
2772 return repo.status(match=scmutil.match(repo[None], pats, opts))
2775 return repo.status(match=scmutil.match(repo[None], pats, opts))
2773
2776
2774 def revert(ui, repo, ctx, parents, *pats, **opts):
2777 def revert(ui, repo, ctx, parents, *pats, **opts):
2775 opts = pycompat.byteskwargs(opts)
2778 opts = pycompat.byteskwargs(opts)
2776 parent, p2 = parents
2779 parent, p2 = parents
2777 node = ctx.node()
2780 node = ctx.node()
2778
2781
2779 mf = ctx.manifest()
2782 mf = ctx.manifest()
2780 if node == p2:
2783 if node == p2:
2781 parent = p2
2784 parent = p2
2782
2785
2783 # need all matching names in dirstate and manifest of target rev,
2786 # need all matching names in dirstate and manifest of target rev,
2784 # so have to walk both. do not print errors if files exist in one
2787 # so have to walk both. do not print errors if files exist in one
2785 # but not other. in both cases, filesets should be evaluated against
2788 # but not other. in both cases, filesets should be evaluated against
2786 # workingctx to get consistent result (issue4497). this means 'set:**'
2789 # workingctx to get consistent result (issue4497). this means 'set:**'
2787 # cannot be used to select missing files from target rev.
2790 # cannot be used to select missing files from target rev.
2788
2791
2789 # `names` is a mapping for all elements in working copy and target revision
2792 # `names` is a mapping for all elements in working copy and target revision
2790 # The mapping is in the form:
2793 # The mapping is in the form:
2791 # <abs path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2794 # <abs path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2792 names = {}
2795 names = {}
2793 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2796 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2794
2797
2795 with repo.wlock():
2798 with repo.wlock():
2796 ## filling of the `names` mapping
2799 ## filling of the `names` mapping
2797 # walk dirstate to fill `names`
2800 # walk dirstate to fill `names`
2798
2801
2799 interactive = opts.get('interactive', False)
2802 interactive = opts.get('interactive', False)
2800 wctx = repo[None]
2803 wctx = repo[None]
2801 m = scmutil.match(wctx, pats, opts)
2804 m = scmutil.match(wctx, pats, opts)
2802
2805
2803 # we'll need this later
2806 # we'll need this later
2804 targetsubs = sorted(s for s in wctx.substate if m(s))
2807 targetsubs = sorted(s for s in wctx.substate if m(s))
2805
2808
2806 if not m.always():
2809 if not m.always():
2807 matcher = matchmod.badmatch(m, lambda x, y: False)
2810 matcher = matchmod.badmatch(m, lambda x, y: False)
2808 for abs in wctx.walk(matcher):
2811 for abs in wctx.walk(matcher):
2809 names[abs] = m.exact(abs)
2812 names[abs] = m.exact(abs)
2810
2813
2811 # walk target manifest to fill `names`
2814 # walk target manifest to fill `names`
2812
2815
2813 def badfn(path, msg):
2816 def badfn(path, msg):
2814 if path in names:
2817 if path in names:
2815 return
2818 return
2816 if path in ctx.substate:
2819 if path in ctx.substate:
2817 return
2820 return
2818 path_ = path + '/'
2821 path_ = path + '/'
2819 for f in names:
2822 for f in names:
2820 if f.startswith(path_):
2823 if f.startswith(path_):
2821 return
2824 return
2822 ui.warn("%s: %s\n" % (m.rel(path), msg))
2825 ui.warn("%s: %s\n" % (m.rel(path), msg))
2823
2826
2824 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
2827 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
2825 if abs not in names:
2828 if abs not in names:
2826 names[abs] = m.exact(abs)
2829 names[abs] = m.exact(abs)
2827
2830
2828 # Find status of all file in `names`.
2831 # Find status of all file in `names`.
2829 m = scmutil.matchfiles(repo, names)
2832 m = scmutil.matchfiles(repo, names)
2830
2833
2831 changes = repo.status(node1=node, match=m,
2834 changes = repo.status(node1=node, match=m,
2832 unknown=True, ignored=True, clean=True)
2835 unknown=True, ignored=True, clean=True)
2833 else:
2836 else:
2834 changes = repo.status(node1=node, match=m)
2837 changes = repo.status(node1=node, match=m)
2835 for kind in changes:
2838 for kind in changes:
2836 for abs in kind:
2839 for abs in kind:
2837 names[abs] = m.exact(abs)
2840 names[abs] = m.exact(abs)
2838
2841
2839 m = scmutil.matchfiles(repo, names)
2842 m = scmutil.matchfiles(repo, names)
2840
2843
2841 modified = set(changes.modified)
2844 modified = set(changes.modified)
2842 added = set(changes.added)
2845 added = set(changes.added)
2843 removed = set(changes.removed)
2846 removed = set(changes.removed)
2844 _deleted = set(changes.deleted)
2847 _deleted = set(changes.deleted)
2845 unknown = set(changes.unknown)
2848 unknown = set(changes.unknown)
2846 unknown.update(changes.ignored)
2849 unknown.update(changes.ignored)
2847 clean = set(changes.clean)
2850 clean = set(changes.clean)
2848 modadded = set()
2851 modadded = set()
2849
2852
2850 # We need to account for the state of the file in the dirstate,
2853 # We need to account for the state of the file in the dirstate,
2851 # even when we revert against something else than parent. This will
2854 # even when we revert against something else than parent. This will
2852 # slightly alter the behavior of revert (doing back up or not, delete
2855 # slightly alter the behavior of revert (doing back up or not, delete
2853 # or just forget etc).
2856 # or just forget etc).
2854 if parent == node:
2857 if parent == node:
2855 dsmodified = modified
2858 dsmodified = modified
2856 dsadded = added
2859 dsadded = added
2857 dsremoved = removed
2860 dsremoved = removed
2858 # store all local modifications, useful later for rename detection
2861 # store all local modifications, useful later for rename detection
2859 localchanges = dsmodified | dsadded
2862 localchanges = dsmodified | dsadded
2860 modified, added, removed = set(), set(), set()
2863 modified, added, removed = set(), set(), set()
2861 else:
2864 else:
2862 changes = repo.status(node1=parent, match=m)
2865 changes = repo.status(node1=parent, match=m)
2863 dsmodified = set(changes.modified)
2866 dsmodified = set(changes.modified)
2864 dsadded = set(changes.added)
2867 dsadded = set(changes.added)
2865 dsremoved = set(changes.removed)
2868 dsremoved = set(changes.removed)
2866 # store all local modifications, useful later for rename detection
2869 # store all local modifications, useful later for rename detection
2867 localchanges = dsmodified | dsadded
2870 localchanges = dsmodified | dsadded
2868
2871
2869 # only take into account for removes between wc and target
2872 # only take into account for removes between wc and target
2870 clean |= dsremoved - removed
2873 clean |= dsremoved - removed
2871 dsremoved &= removed
2874 dsremoved &= removed
2872 # distinct between dirstate remove and other
2875 # distinct between dirstate remove and other
2873 removed -= dsremoved
2876 removed -= dsremoved
2874
2877
2875 modadded = added & dsmodified
2878 modadded = added & dsmodified
2876 added -= modadded
2879 added -= modadded
2877
2880
2878 # tell newly modified apart.
2881 # tell newly modified apart.
2879 dsmodified &= modified
2882 dsmodified &= modified
2880 dsmodified |= modified & dsadded # dirstate added may need backup
2883 dsmodified |= modified & dsadded # dirstate added may need backup
2881 modified -= dsmodified
2884 modified -= dsmodified
2882
2885
2883 # We need to wait for some post-processing to update this set
2886 # We need to wait for some post-processing to update this set
2884 # before making the distinction. The dirstate will be used for
2887 # before making the distinction. The dirstate will be used for
2885 # that purpose.
2888 # that purpose.
2886 dsadded = added
2889 dsadded = added
2887
2890
2888 # in case of merge, files that are actually added can be reported as
2891 # in case of merge, files that are actually added can be reported as
2889 # modified, we need to post process the result
2892 # modified, we need to post process the result
2890 if p2 != nullid:
2893 if p2 != nullid:
2891 mergeadd = set(dsmodified)
2894 mergeadd = set(dsmodified)
2892 for path in dsmodified:
2895 for path in dsmodified:
2893 if path in mf:
2896 if path in mf:
2894 mergeadd.remove(path)
2897 mergeadd.remove(path)
2895 dsadded |= mergeadd
2898 dsadded |= mergeadd
2896 dsmodified -= mergeadd
2899 dsmodified -= mergeadd
2897
2900
2898 # if f is a rename, update `names` to also revert the source
2901 # if f is a rename, update `names` to also revert the source
2899 for f in localchanges:
2902 for f in localchanges:
2900 src = repo.dirstate.copied(f)
2903 src = repo.dirstate.copied(f)
2901 # XXX should we check for rename down to target node?
2904 # XXX should we check for rename down to target node?
2902 if src and src not in names and repo.dirstate[src] == 'r':
2905 if src and src not in names and repo.dirstate[src] == 'r':
2903 dsremoved.add(src)
2906 dsremoved.add(src)
2904 names[src] = True
2907 names[src] = True
2905
2908
2906 # determine the exact nature of the deleted changesets
2909 # determine the exact nature of the deleted changesets
2907 deladded = set(_deleted)
2910 deladded = set(_deleted)
2908 for path in _deleted:
2911 for path in _deleted:
2909 if path in mf:
2912 if path in mf:
2910 deladded.remove(path)
2913 deladded.remove(path)
2911 deleted = _deleted - deladded
2914 deleted = _deleted - deladded
2912
2915
2913 # distinguish between file to forget and the other
2916 # distinguish between file to forget and the other
2914 added = set()
2917 added = set()
2915 for abs in dsadded:
2918 for abs in dsadded:
2916 if repo.dirstate[abs] != 'a':
2919 if repo.dirstate[abs] != 'a':
2917 added.add(abs)
2920 added.add(abs)
2918 dsadded -= added
2921 dsadded -= added
2919
2922
2920 for abs in deladded:
2923 for abs in deladded:
2921 if repo.dirstate[abs] == 'a':
2924 if repo.dirstate[abs] == 'a':
2922 dsadded.add(abs)
2925 dsadded.add(abs)
2923 deladded -= dsadded
2926 deladded -= dsadded
2924
2927
2925 # For files marked as removed, we check if an unknown file is present at
2928 # For files marked as removed, we check if an unknown file is present at
2926 # the same path. If a such file exists it may need to be backed up.
2929 # the same path. If a such file exists it may need to be backed up.
2927 # Making the distinction at this stage helps have simpler backup
2930 # Making the distinction at this stage helps have simpler backup
2928 # logic.
2931 # logic.
2929 removunk = set()
2932 removunk = set()
2930 for abs in removed:
2933 for abs in removed:
2931 target = repo.wjoin(abs)
2934 target = repo.wjoin(abs)
2932 if os.path.lexists(target):
2935 if os.path.lexists(target):
2933 removunk.add(abs)
2936 removunk.add(abs)
2934 removed -= removunk
2937 removed -= removunk
2935
2938
2936 dsremovunk = set()
2939 dsremovunk = set()
2937 for abs in dsremoved:
2940 for abs in dsremoved:
2938 target = repo.wjoin(abs)
2941 target = repo.wjoin(abs)
2939 if os.path.lexists(target):
2942 if os.path.lexists(target):
2940 dsremovunk.add(abs)
2943 dsremovunk.add(abs)
2941 dsremoved -= dsremovunk
2944 dsremoved -= dsremovunk
2942
2945
2943 # action to be actually performed by revert
2946 # action to be actually performed by revert
2944 # (<list of file>, message>) tuple
2947 # (<list of file>, message>) tuple
2945 actions = {'revert': ([], _('reverting %s\n')),
2948 actions = {'revert': ([], _('reverting %s\n')),
2946 'add': ([], _('adding %s\n')),
2949 'add': ([], _('adding %s\n')),
2947 'remove': ([], _('removing %s\n')),
2950 'remove': ([], _('removing %s\n')),
2948 'drop': ([], _('removing %s\n')),
2951 'drop': ([], _('removing %s\n')),
2949 'forget': ([], _('forgetting %s\n')),
2952 'forget': ([], _('forgetting %s\n')),
2950 'undelete': ([], _('undeleting %s\n')),
2953 'undelete': ([], _('undeleting %s\n')),
2951 'noop': (None, _('no changes needed to %s\n')),
2954 'noop': (None, _('no changes needed to %s\n')),
2952 'unknown': (None, _('file not managed: %s\n')),
2955 'unknown': (None, _('file not managed: %s\n')),
2953 }
2956 }
2954
2957
2955 # "constant" that convey the backup strategy.
2958 # "constant" that convey the backup strategy.
2956 # All set to `discard` if `no-backup` is set do avoid checking
2959 # All set to `discard` if `no-backup` is set do avoid checking
2957 # no_backup lower in the code.
2960 # no_backup lower in the code.
2958 # These values are ordered for comparison purposes
2961 # These values are ordered for comparison purposes
2959 backupinteractive = 3 # do backup if interactively modified
2962 backupinteractive = 3 # do backup if interactively modified
2960 backup = 2 # unconditionally do backup
2963 backup = 2 # unconditionally do backup
2961 check = 1 # check if the existing file differs from target
2964 check = 1 # check if the existing file differs from target
2962 discard = 0 # never do backup
2965 discard = 0 # never do backup
2963 if opts.get('no_backup'):
2966 if opts.get('no_backup'):
2964 backupinteractive = backup = check = discard
2967 backupinteractive = backup = check = discard
2965 if interactive:
2968 if interactive:
2966 dsmodifiedbackup = backupinteractive
2969 dsmodifiedbackup = backupinteractive
2967 else:
2970 else:
2968 dsmodifiedbackup = backup
2971 dsmodifiedbackup = backup
2969 tobackup = set()
2972 tobackup = set()
2970
2973
2971 backupanddel = actions['remove']
2974 backupanddel = actions['remove']
2972 if not opts.get('no_backup'):
2975 if not opts.get('no_backup'):
2973 backupanddel = actions['drop']
2976 backupanddel = actions['drop']
2974
2977
2975 disptable = (
2978 disptable = (
2976 # dispatch table:
2979 # dispatch table:
2977 # file state
2980 # file state
2978 # action
2981 # action
2979 # make backup
2982 # make backup
2980
2983
2981 ## Sets that results that will change file on disk
2984 ## Sets that results that will change file on disk
2982 # Modified compared to target, no local change
2985 # Modified compared to target, no local change
2983 (modified, actions['revert'], discard),
2986 (modified, actions['revert'], discard),
2984 # Modified compared to target, but local file is deleted
2987 # Modified compared to target, but local file is deleted
2985 (deleted, actions['revert'], discard),
2988 (deleted, actions['revert'], discard),
2986 # Modified compared to target, local change
2989 # Modified compared to target, local change
2987 (dsmodified, actions['revert'], dsmodifiedbackup),
2990 (dsmodified, actions['revert'], dsmodifiedbackup),
2988 # Added since target
2991 # Added since target
2989 (added, actions['remove'], discard),
2992 (added, actions['remove'], discard),
2990 # Added in working directory
2993 # Added in working directory
2991 (dsadded, actions['forget'], discard),
2994 (dsadded, actions['forget'], discard),
2992 # Added since target, have local modification
2995 # Added since target, have local modification
2993 (modadded, backupanddel, backup),
2996 (modadded, backupanddel, backup),
2994 # Added since target but file is missing in working directory
2997 # Added since target but file is missing in working directory
2995 (deladded, actions['drop'], discard),
2998 (deladded, actions['drop'], discard),
2996 # Removed since target, before working copy parent
2999 # Removed since target, before working copy parent
2997 (removed, actions['add'], discard),
3000 (removed, actions['add'], discard),
2998 # Same as `removed` but an unknown file exists at the same path
3001 # Same as `removed` but an unknown file exists at the same path
2999 (removunk, actions['add'], check),
3002 (removunk, actions['add'], check),
3000 # Removed since targe, marked as such in working copy parent
3003 # Removed since targe, marked as such in working copy parent
3001 (dsremoved, actions['undelete'], discard),
3004 (dsremoved, actions['undelete'], discard),
3002 # Same as `dsremoved` but an unknown file exists at the same path
3005 # Same as `dsremoved` but an unknown file exists at the same path
3003 (dsremovunk, actions['undelete'], check),
3006 (dsremovunk, actions['undelete'], check),
3004 ## the following sets does not result in any file changes
3007 ## the following sets does not result in any file changes
3005 # File with no modification
3008 # File with no modification
3006 (clean, actions['noop'], discard),
3009 (clean, actions['noop'], discard),
3007 # Existing file, not tracked anywhere
3010 # Existing file, not tracked anywhere
3008 (unknown, actions['unknown'], discard),
3011 (unknown, actions['unknown'], discard),
3009 )
3012 )
3010
3013
3011 for abs, exact in sorted(names.items()):
3014 for abs, exact in sorted(names.items()):
3012 # target file to be touch on disk (relative to cwd)
3015 # target file to be touch on disk (relative to cwd)
3013 target = repo.wjoin(abs)
3016 target = repo.wjoin(abs)
3014 # search the entry in the dispatch table.
3017 # search the entry in the dispatch table.
3015 # if the file is in any of these sets, it was touched in the working
3018 # if the file is in any of these sets, it was touched in the working
3016 # directory parent and we are sure it needs to be reverted.
3019 # directory parent and we are sure it needs to be reverted.
3017 for table, (xlist, msg), dobackup in disptable:
3020 for table, (xlist, msg), dobackup in disptable:
3018 if abs not in table:
3021 if abs not in table:
3019 continue
3022 continue
3020 if xlist is not None:
3023 if xlist is not None:
3021 xlist.append(abs)
3024 xlist.append(abs)
3022 if dobackup:
3025 if dobackup:
3023 # If in interactive mode, don't automatically create
3026 # If in interactive mode, don't automatically create
3024 # .orig files (issue4793)
3027 # .orig files (issue4793)
3025 if dobackup == backupinteractive:
3028 if dobackup == backupinteractive:
3026 tobackup.add(abs)
3029 tobackup.add(abs)
3027 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
3030 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
3028 absbakname = scmutil.backuppath(ui, repo, abs)
3031 absbakname = scmutil.backuppath(ui, repo, abs)
3029 bakname = os.path.relpath(absbakname,
3032 bakname = os.path.relpath(absbakname,
3030 start=repo.root)
3033 start=repo.root)
3031 ui.note(_('saving current version of %s as %s\n') %
3034 ui.note(_('saving current version of %s as %s\n') %
3032 (uipathfn(abs), uipathfn(bakname)))
3035 (uipathfn(abs), uipathfn(bakname)))
3033 if not opts.get('dry_run'):
3036 if not opts.get('dry_run'):
3034 if interactive:
3037 if interactive:
3035 util.copyfile(target, absbakname)
3038 util.copyfile(target, absbakname)
3036 else:
3039 else:
3037 util.rename(target, absbakname)
3040 util.rename(target, absbakname)
3038 if opts.get('dry_run'):
3041 if opts.get('dry_run'):
3039 if ui.verbose or not exact:
3042 if ui.verbose or not exact:
3040 ui.status(msg % uipathfn(abs))
3043 ui.status(msg % uipathfn(abs))
3041 elif exact:
3044 elif exact:
3042 ui.warn(msg % uipathfn(abs))
3045 ui.warn(msg % uipathfn(abs))
3043 break
3046 break
3044
3047
3045 if not opts.get('dry_run'):
3048 if not opts.get('dry_run'):
3046 needdata = ('revert', 'add', 'undelete')
3049 needdata = ('revert', 'add', 'undelete')
3047 oplist = [actions[name][0] for name in needdata]
3050 oplist = [actions[name][0] for name in needdata]
3048 prefetch = scmutil.prefetchfiles
3051 prefetch = scmutil.prefetchfiles
3049 matchfiles = scmutil.matchfiles
3052 matchfiles = scmutil.matchfiles
3050 prefetch(repo, [ctx.rev()],
3053 prefetch(repo, [ctx.rev()],
3051 matchfiles(repo,
3054 matchfiles(repo,
3052 [f for sublist in oplist for f in sublist]))
3055 [f for sublist in oplist for f in sublist]))
3053 _performrevert(repo, parents, ctx, names, uipathfn, actions,
3056 _performrevert(repo, parents, ctx, names, uipathfn, actions,
3054 interactive, tobackup)
3057 interactive, tobackup)
3055
3058
3056 if targetsubs:
3059 if targetsubs:
3057 # Revert the subrepos on the revert list
3060 # Revert the subrepos on the revert list
3058 for sub in targetsubs:
3061 for sub in targetsubs:
3059 try:
3062 try:
3060 wctx.sub(sub).revert(ctx.substate[sub], *pats,
3063 wctx.sub(sub).revert(ctx.substate[sub], *pats,
3061 **pycompat.strkwargs(opts))
3064 **pycompat.strkwargs(opts))
3062 except KeyError:
3065 except KeyError:
3063 raise error.Abort("subrepository '%s' does not exist in %s!"
3066 raise error.Abort("subrepository '%s' does not exist in %s!"
3064 % (sub, short(ctx.node())))
3067 % (sub, short(ctx.node())))
3065
3068
3066 def _performrevert(repo, parents, ctx, names, uipathfn, actions,
3069 def _performrevert(repo, parents, ctx, names, uipathfn, actions,
3067 interactive=False, tobackup=None):
3070 interactive=False, tobackup=None):
3068 """function that actually perform all the actions computed for revert
3071 """function that actually perform all the actions computed for revert
3069
3072
3070 This is an independent function to let extension to plug in and react to
3073 This is an independent function to let extension to plug in and react to
3071 the imminent revert.
3074 the imminent revert.
3072
3075
3073 Make sure you have the working directory locked when calling this function.
3076 Make sure you have the working directory locked when calling this function.
3074 """
3077 """
3075 parent, p2 = parents
3078 parent, p2 = parents
3076 node = ctx.node()
3079 node = ctx.node()
3077 excluded_files = []
3080 excluded_files = []
3078
3081
3079 def checkout(f):
3082 def checkout(f):
3080 fc = ctx[f]
3083 fc = ctx[f]
3081 repo.wwrite(f, fc.data(), fc.flags())
3084 repo.wwrite(f, fc.data(), fc.flags())
3082
3085
3083 def doremove(f):
3086 def doremove(f):
3084 try:
3087 try:
3085 rmdir = repo.ui.configbool('experimental', 'removeemptydirs')
3088 rmdir = repo.ui.configbool('experimental', 'removeemptydirs')
3086 repo.wvfs.unlinkpath(f, rmdir=rmdir)
3089 repo.wvfs.unlinkpath(f, rmdir=rmdir)
3087 except OSError:
3090 except OSError:
3088 pass
3091 pass
3089 repo.dirstate.remove(f)
3092 repo.dirstate.remove(f)
3090
3093
3091 def prntstatusmsg(action, f):
3094 def prntstatusmsg(action, f):
3092 exact = names[f]
3095 exact = names[f]
3093 if repo.ui.verbose or not exact:
3096 if repo.ui.verbose or not exact:
3094 repo.ui.status(actions[action][1] % uipathfn(f))
3097 repo.ui.status(actions[action][1] % uipathfn(f))
3095
3098
3096 audit_path = pathutil.pathauditor(repo.root, cached=True)
3099 audit_path = pathutil.pathauditor(repo.root, cached=True)
3097 for f in actions['forget'][0]:
3100 for f in actions['forget'][0]:
3098 if interactive:
3101 if interactive:
3099 choice = repo.ui.promptchoice(
3102 choice = repo.ui.promptchoice(
3100 _("forget added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f))
3103 _("forget added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f))
3101 if choice == 0:
3104 if choice == 0:
3102 prntstatusmsg('forget', f)
3105 prntstatusmsg('forget', f)
3103 repo.dirstate.drop(f)
3106 repo.dirstate.drop(f)
3104 else:
3107 else:
3105 excluded_files.append(f)
3108 excluded_files.append(f)
3106 else:
3109 else:
3107 prntstatusmsg('forget', f)
3110 prntstatusmsg('forget', f)
3108 repo.dirstate.drop(f)
3111 repo.dirstate.drop(f)
3109 for f in actions['remove'][0]:
3112 for f in actions['remove'][0]:
3110 audit_path(f)
3113 audit_path(f)
3111 if interactive:
3114 if interactive:
3112 choice = repo.ui.promptchoice(
3115 choice = repo.ui.promptchoice(
3113 _("remove added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f))
3116 _("remove added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f))
3114 if choice == 0:
3117 if choice == 0:
3115 prntstatusmsg('remove', f)
3118 prntstatusmsg('remove', f)
3116 doremove(f)
3119 doremove(f)
3117 else:
3120 else:
3118 excluded_files.append(f)
3121 excluded_files.append(f)
3119 else:
3122 else:
3120 prntstatusmsg('remove', f)
3123 prntstatusmsg('remove', f)
3121 doremove(f)
3124 doremove(f)
3122 for f in actions['drop'][0]:
3125 for f in actions['drop'][0]:
3123 audit_path(f)
3126 audit_path(f)
3124 prntstatusmsg('drop', f)
3127 prntstatusmsg('drop', f)
3125 repo.dirstate.remove(f)
3128 repo.dirstate.remove(f)
3126
3129
3127 normal = None
3130 normal = None
3128 if node == parent:
3131 if node == parent:
3129 # We're reverting to our parent. If possible, we'd like status
3132 # We're reverting to our parent. If possible, we'd like status
3130 # to report the file as clean. We have to use normallookup for
3133 # to report the file as clean. We have to use normallookup for
3131 # merges to avoid losing information about merged/dirty files.
3134 # merges to avoid losing information about merged/dirty files.
3132 if p2 != nullid:
3135 if p2 != nullid:
3133 normal = repo.dirstate.normallookup
3136 normal = repo.dirstate.normallookup
3134 else:
3137 else:
3135 normal = repo.dirstate.normal
3138 normal = repo.dirstate.normal
3136
3139
3137 newlyaddedandmodifiedfiles = set()
3140 newlyaddedandmodifiedfiles = set()
3138 if interactive:
3141 if interactive:
3139 # Prompt the user for changes to revert
3142 # Prompt the user for changes to revert
3140 torevert = [f for f in actions['revert'][0] if f not in excluded_files]
3143 torevert = [f for f in actions['revert'][0] if f not in excluded_files]
3141 m = scmutil.matchfiles(repo, torevert)
3144 m = scmutil.matchfiles(repo, torevert)
3142 diffopts = patch.difffeatureopts(repo.ui, whitespace=True,
3145 diffopts = patch.difffeatureopts(repo.ui, whitespace=True,
3143 section='commands',
3146 section='commands',
3144 configprefix='revert.interactive.')
3147 configprefix='revert.interactive.')
3145 diffopts.nodates = True
3148 diffopts.nodates = True
3146 diffopts.git = True
3149 diffopts.git = True
3147 operation = 'discard'
3150 operation = 'discard'
3148 reversehunks = True
3151 reversehunks = True
3149 if node != parent:
3152 if node != parent:
3150 operation = 'apply'
3153 operation = 'apply'
3151 reversehunks = False
3154 reversehunks = False
3152 if reversehunks:
3155 if reversehunks:
3153 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3156 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3154 else:
3157 else:
3155 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3158 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3156 originalchunks = patch.parsepatch(diff)
3159 originalchunks = patch.parsepatch(diff)
3157
3160
3158 try:
3161 try:
3159
3162
3160 chunks, opts = recordfilter(repo.ui, originalchunks,
3163 chunks, opts = recordfilter(repo.ui, originalchunks,
3161 operation=operation)
3164 operation=operation)
3162 if reversehunks:
3165 if reversehunks:
3163 chunks = patch.reversehunks(chunks)
3166 chunks = patch.reversehunks(chunks)
3164
3167
3165 except error.PatchError as err:
3168 except error.PatchError as err:
3166 raise error.Abort(_('error parsing patch: %s') % err)
3169 raise error.Abort(_('error parsing patch: %s') % err)
3167
3170
3168 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3171 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3169 if tobackup is None:
3172 if tobackup is None:
3170 tobackup = set()
3173 tobackup = set()
3171 # Apply changes
3174 # Apply changes
3172 fp = stringio()
3175 fp = stringio()
3173 # chunks are serialized per file, but files aren't sorted
3176 # chunks are serialized per file, but files aren't sorted
3174 for f in sorted(set(c.header.filename() for c in chunks if ishunk(c))):
3177 for f in sorted(set(c.header.filename() for c in chunks if ishunk(c))):
3175 prntstatusmsg('revert', f)
3178 prntstatusmsg('revert', f)
3176 for c in chunks:
3179 for c in chunks:
3177 if ishunk(c):
3180 if ishunk(c):
3178 abs = c.header.filename()
3181 abs = c.header.filename()
3179 # Create a backup file only if this hunk should be backed up
3182 # Create a backup file only if this hunk should be backed up
3180 if c.header.filename() in tobackup:
3183 if c.header.filename() in tobackup:
3181 target = repo.wjoin(abs)
3184 target = repo.wjoin(abs)
3182 bakname = scmutil.backuppath(repo.ui, repo, abs)
3185 bakname = scmutil.backuppath(repo.ui, repo, abs)
3183 util.copyfile(target, bakname)
3186 util.copyfile(target, bakname)
3184 tobackup.remove(abs)
3187 tobackup.remove(abs)
3185 c.write(fp)
3188 c.write(fp)
3186 dopatch = fp.tell()
3189 dopatch = fp.tell()
3187 fp.seek(0)
3190 fp.seek(0)
3188 if dopatch:
3191 if dopatch:
3189 try:
3192 try:
3190 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3193 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3191 except error.PatchError as err:
3194 except error.PatchError as err:
3192 raise error.Abort(pycompat.bytestr(err))
3195 raise error.Abort(pycompat.bytestr(err))
3193 del fp
3196 del fp
3194 else:
3197 else:
3195 for f in actions['revert'][0]:
3198 for f in actions['revert'][0]:
3196 prntstatusmsg('revert', f)
3199 prntstatusmsg('revert', f)
3197 checkout(f)
3200 checkout(f)
3198 if normal:
3201 if normal:
3199 normal(f)
3202 normal(f)
3200
3203
3201 for f in actions['add'][0]:
3204 for f in actions['add'][0]:
3202 # Don't checkout modified files, they are already created by the diff
3205 # Don't checkout modified files, they are already created by the diff
3203 if f not in newlyaddedandmodifiedfiles:
3206 if f not in newlyaddedandmodifiedfiles:
3204 prntstatusmsg('add', f)
3207 prntstatusmsg('add', f)
3205 checkout(f)
3208 checkout(f)
3206 repo.dirstate.add(f)
3209 repo.dirstate.add(f)
3207
3210
3208 normal = repo.dirstate.normallookup
3211 normal = repo.dirstate.normallookup
3209 if node == parent and p2 == nullid:
3212 if node == parent and p2 == nullid:
3210 normal = repo.dirstate.normal
3213 normal = repo.dirstate.normal
3211 for f in actions['undelete'][0]:
3214 for f in actions['undelete'][0]:
3212 if interactive:
3215 if interactive:
3213 choice = repo.ui.promptchoice(
3216 choice = repo.ui.promptchoice(
3214 _("add back removed file %s (Yn)?$$ &Yes $$ &No") % f)
3217 _("add back removed file %s (Yn)?$$ &Yes $$ &No") % f)
3215 if choice == 0:
3218 if choice == 0:
3216 prntstatusmsg('undelete', f)
3219 prntstatusmsg('undelete', f)
3217 checkout(f)
3220 checkout(f)
3218 normal(f)
3221 normal(f)
3219 else:
3222 else:
3220 excluded_files.append(f)
3223 excluded_files.append(f)
3221 else:
3224 else:
3222 prntstatusmsg('undelete', f)
3225 prntstatusmsg('undelete', f)
3223 checkout(f)
3226 checkout(f)
3224 normal(f)
3227 normal(f)
3225
3228
3226 copied = copies.pathcopies(repo[parent], ctx)
3229 copied = copies.pathcopies(repo[parent], ctx)
3227
3230
3228 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3231 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3229 if f in copied:
3232 if f in copied:
3230 repo.dirstate.copy(copied[f], f)
3233 repo.dirstate.copy(copied[f], f)
3231
3234
3232 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3235 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3233 # commands.outgoing. "missing" is "missing" of the result of
3236 # commands.outgoing. "missing" is "missing" of the result of
3234 # "findcommonoutgoing()"
3237 # "findcommonoutgoing()"
3235 outgoinghooks = util.hooks()
3238 outgoinghooks = util.hooks()
3236
3239
3237 # a list of (ui, repo) functions called by commands.summary
3240 # a list of (ui, repo) functions called by commands.summary
3238 summaryhooks = util.hooks()
3241 summaryhooks = util.hooks()
3239
3242
3240 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3243 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3241 #
3244 #
3242 # functions should return tuple of booleans below, if 'changes' is None:
3245 # functions should return tuple of booleans below, if 'changes' is None:
3243 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3246 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3244 #
3247 #
3245 # otherwise, 'changes' is a tuple of tuples below:
3248 # otherwise, 'changes' is a tuple of tuples below:
3246 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3249 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3247 # - (desturl, destbranch, destpeer, outgoing)
3250 # - (desturl, destbranch, destpeer, outgoing)
3248 summaryremotehooks = util.hooks()
3251 summaryremotehooks = util.hooks()
3249
3252
3250 # A list of state files kept by multistep operations like graft.
3253 # A list of state files kept by multistep operations like graft.
3251 # Since graft cannot be aborted, it is considered 'clearable' by update.
3254 # Since graft cannot be aborted, it is considered 'clearable' by update.
3252 # note: bisect is intentionally excluded
3255 # note: bisect is intentionally excluded
3253 # (state file, clearable, allowcommit, error, hint)
3256 # (state file, clearable, allowcommit, error, hint)
3254 unfinishedstates = [
3257 unfinishedstates = [
3255 ('graftstate', True, False, _('graft in progress'),
3258 ('graftstate', True, False, _('graft in progress'),
3256 _("use 'hg graft --continue' or 'hg graft --stop' to stop")),
3259 _("use 'hg graft --continue' or 'hg graft --stop' to stop")),
3257 ('updatestate', True, False, _('last update was interrupted'),
3260 ('updatestate', True, False, _('last update was interrupted'),
3258 _("use 'hg update' to get a consistent checkout"))
3261 _("use 'hg update' to get a consistent checkout"))
3259 ]
3262 ]
3260
3263
3261 def checkunfinished(repo, commit=False):
3264 def checkunfinished(repo, commit=False):
3262 '''Look for an unfinished multistep operation, like graft, and abort
3265 '''Look for an unfinished multistep operation, like graft, and abort
3263 if found. It's probably good to check this right before
3266 if found. It's probably good to check this right before
3264 bailifchanged().
3267 bailifchanged().
3265 '''
3268 '''
3266 # Check for non-clearable states first, so things like rebase will take
3269 # Check for non-clearable states first, so things like rebase will take
3267 # precedence over update.
3270 # precedence over update.
3268 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3271 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3269 if clearable or (commit and allowcommit):
3272 if clearable or (commit and allowcommit):
3270 continue
3273 continue
3271 if repo.vfs.exists(f):
3274 if repo.vfs.exists(f):
3272 raise error.Abort(msg, hint=hint)
3275 raise error.Abort(msg, hint=hint)
3273
3276
3274 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3277 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3275 if not clearable or (commit and allowcommit):
3278 if not clearable or (commit and allowcommit):
3276 continue
3279 continue
3277 if repo.vfs.exists(f):
3280 if repo.vfs.exists(f):
3278 raise error.Abort(msg, hint=hint)
3281 raise error.Abort(msg, hint=hint)
3279
3282
3280 def clearunfinished(repo):
3283 def clearunfinished(repo):
3281 '''Check for unfinished operations (as above), and clear the ones
3284 '''Check for unfinished operations (as above), and clear the ones
3282 that are clearable.
3285 that are clearable.
3283 '''
3286 '''
3284 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3287 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3285 if not clearable and repo.vfs.exists(f):
3288 if not clearable and repo.vfs.exists(f):
3286 raise error.Abort(msg, hint=hint)
3289 raise error.Abort(msg, hint=hint)
3287 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3290 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3288 if clearable and repo.vfs.exists(f):
3291 if clearable and repo.vfs.exists(f):
3289 util.unlink(repo.vfs.join(f))
3292 util.unlink(repo.vfs.join(f))
3290
3293
3291 afterresolvedstates = [
3294 afterresolvedstates = [
3292 ('graftstate',
3295 ('graftstate',
3293 _('hg graft --continue')),
3296 _('hg graft --continue')),
3294 ]
3297 ]
3295
3298
3296 def howtocontinue(repo):
3299 def howtocontinue(repo):
3297 '''Check for an unfinished operation and return the command to finish
3300 '''Check for an unfinished operation and return the command to finish
3298 it.
3301 it.
3299
3302
3300 afterresolvedstates tuples define a .hg/{file} and the corresponding
3303 afterresolvedstates tuples define a .hg/{file} and the corresponding
3301 command needed to finish it.
3304 command needed to finish it.
3302
3305
3303 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3306 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3304 a boolean.
3307 a boolean.
3305 '''
3308 '''
3306 contmsg = _("continue: %s")
3309 contmsg = _("continue: %s")
3307 for f, msg in afterresolvedstates:
3310 for f, msg in afterresolvedstates:
3308 if repo.vfs.exists(f):
3311 if repo.vfs.exists(f):
3309 return contmsg % msg, True
3312 return contmsg % msg, True
3310 if repo[None].dirty(missing=True, merge=False, branch=False):
3313 if repo[None].dirty(missing=True, merge=False, branch=False):
3311 return contmsg % _("hg commit"), False
3314 return contmsg % _("hg commit"), False
3312 return None, None
3315 return None, None
3313
3316
3314 def checkafterresolved(repo):
3317 def checkafterresolved(repo):
3315 '''Inform the user about the next action after completing hg resolve
3318 '''Inform the user about the next action after completing hg resolve
3316
3319
3317 If there's a matching afterresolvedstates, howtocontinue will yield
3320 If there's a matching afterresolvedstates, howtocontinue will yield
3318 repo.ui.warn as the reporter.
3321 repo.ui.warn as the reporter.
3319
3322
3320 Otherwise, it will yield repo.ui.note.
3323 Otherwise, it will yield repo.ui.note.
3321 '''
3324 '''
3322 msg, warning = howtocontinue(repo)
3325 msg, warning = howtocontinue(repo)
3323 if msg is not None:
3326 if msg is not None:
3324 if warning:
3327 if warning:
3325 repo.ui.warn("%s\n" % msg)
3328 repo.ui.warn("%s\n" % msg)
3326 else:
3329 else:
3327 repo.ui.note("%s\n" % msg)
3330 repo.ui.note("%s\n" % msg)
3328
3331
3329 def wrongtooltocontinue(repo, task):
3332 def wrongtooltocontinue(repo, task):
3330 '''Raise an abort suggesting how to properly continue if there is an
3333 '''Raise an abort suggesting how to properly continue if there is an
3331 active task.
3334 active task.
3332
3335
3333 Uses howtocontinue() to find the active task.
3336 Uses howtocontinue() to find the active task.
3334
3337
3335 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3338 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3336 a hint.
3339 a hint.
3337 '''
3340 '''
3338 after = howtocontinue(repo)
3341 after = howtocontinue(repo)
3339 hint = None
3342 hint = None
3340 if after[1]:
3343 if after[1]:
3341 hint = after[0]
3344 hint = after[0]
3342 raise error.Abort(_('no %s in progress') % task, hint=hint)
3345 raise error.Abort(_('no %s in progress') % task, hint=hint)
@@ -1,6232 +1,6233 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import difflib
10 import difflib
11 import errno
11 import errno
12 import os
12 import os
13 import re
13 import re
14 import sys
14 import sys
15
15
16 from .i18n import _
16 from .i18n import _
17 from .node import (
17 from .node import (
18 hex,
18 hex,
19 nullid,
19 nullid,
20 nullrev,
20 nullrev,
21 short,
21 short,
22 wdirhex,
22 wdirhex,
23 wdirrev,
23 wdirrev,
24 )
24 )
25 from . import (
25 from . import (
26 archival,
26 archival,
27 bookmarks,
27 bookmarks,
28 bundle2,
28 bundle2,
29 changegroup,
29 changegroup,
30 cmdutil,
30 cmdutil,
31 copies,
31 copies,
32 debugcommands as debugcommandsmod,
32 debugcommands as debugcommandsmod,
33 destutil,
33 destutil,
34 dirstateguard,
34 dirstateguard,
35 discovery,
35 discovery,
36 encoding,
36 encoding,
37 error,
37 error,
38 exchange,
38 exchange,
39 extensions,
39 extensions,
40 filemerge,
40 filemerge,
41 formatter,
41 formatter,
42 graphmod,
42 graphmod,
43 hbisect,
43 hbisect,
44 help,
44 help,
45 hg,
45 hg,
46 logcmdutil,
46 logcmdutil,
47 merge as mergemod,
47 merge as mergemod,
48 narrowspec,
48 narrowspec,
49 obsolete,
49 obsolete,
50 obsutil,
50 obsutil,
51 patch,
51 patch,
52 phases,
52 phases,
53 pycompat,
53 pycompat,
54 rcutil,
54 rcutil,
55 registrar,
55 registrar,
56 repair,
56 repair,
57 revsetlang,
57 revsetlang,
58 rewriteutil,
58 rewriteutil,
59 scmutil,
59 scmutil,
60 server,
60 server,
61 state as statemod,
61 state as statemod,
62 streamclone,
62 streamclone,
63 tags as tagsmod,
63 tags as tagsmod,
64 templatekw,
64 templatekw,
65 ui as uimod,
65 ui as uimod,
66 util,
66 util,
67 wireprotoserver,
67 wireprotoserver,
68 )
68 )
69 from .utils import (
69 from .utils import (
70 dateutil,
70 dateutil,
71 stringutil,
71 stringutil,
72 )
72 )
73
73
74 table = {}
74 table = {}
75 table.update(debugcommandsmod.command._table)
75 table.update(debugcommandsmod.command._table)
76
76
77 command = registrar.command(table)
77 command = registrar.command(table)
78 INTENT_READONLY = registrar.INTENT_READONLY
78 INTENT_READONLY = registrar.INTENT_READONLY
79
79
80 # common command options
80 # common command options
81
81
82 globalopts = [
82 globalopts = [
83 ('R', 'repository', '',
83 ('R', 'repository', '',
84 _('repository root directory or name of overlay bundle file'),
84 _('repository root directory or name of overlay bundle file'),
85 _('REPO')),
85 _('REPO')),
86 ('', 'cwd', '',
86 ('', 'cwd', '',
87 _('change working directory'), _('DIR')),
87 _('change working directory'), _('DIR')),
88 ('y', 'noninteractive', None,
88 ('y', 'noninteractive', None,
89 _('do not prompt, automatically pick the first choice for all prompts')),
89 _('do not prompt, automatically pick the first choice for all prompts')),
90 ('q', 'quiet', None, _('suppress output')),
90 ('q', 'quiet', None, _('suppress output')),
91 ('v', 'verbose', None, _('enable additional output')),
91 ('v', 'verbose', None, _('enable additional output')),
92 ('', 'color', '',
92 ('', 'color', '',
93 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
93 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
94 # and should not be translated
94 # and should not be translated
95 _("when to colorize (boolean, always, auto, never, or debug)"),
95 _("when to colorize (boolean, always, auto, never, or debug)"),
96 _('TYPE')),
96 _('TYPE')),
97 ('', 'config', [],
97 ('', 'config', [],
98 _('set/override config option (use \'section.name=value\')'),
98 _('set/override config option (use \'section.name=value\')'),
99 _('CONFIG')),
99 _('CONFIG')),
100 ('', 'debug', None, _('enable debugging output')),
100 ('', 'debug', None, _('enable debugging output')),
101 ('', 'debugger', None, _('start debugger')),
101 ('', 'debugger', None, _('start debugger')),
102 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
102 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
103 _('ENCODE')),
103 _('ENCODE')),
104 ('', 'encodingmode', encoding.encodingmode,
104 ('', 'encodingmode', encoding.encodingmode,
105 _('set the charset encoding mode'), _('MODE')),
105 _('set the charset encoding mode'), _('MODE')),
106 ('', 'traceback', None, _('always print a traceback on exception')),
106 ('', 'traceback', None, _('always print a traceback on exception')),
107 ('', 'time', None, _('time how long the command takes')),
107 ('', 'time', None, _('time how long the command takes')),
108 ('', 'profile', None, _('print command execution profile')),
108 ('', 'profile', None, _('print command execution profile')),
109 ('', 'version', None, _('output version information and exit')),
109 ('', 'version', None, _('output version information and exit')),
110 ('h', 'help', None, _('display help and exit')),
110 ('h', 'help', None, _('display help and exit')),
111 ('', 'hidden', False, _('consider hidden changesets')),
111 ('', 'hidden', False, _('consider hidden changesets')),
112 ('', 'pager', 'auto',
112 ('', 'pager', 'auto',
113 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
113 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
114 ]
114 ]
115
115
116 dryrunopts = cmdutil.dryrunopts
116 dryrunopts = cmdutil.dryrunopts
117 remoteopts = cmdutil.remoteopts
117 remoteopts = cmdutil.remoteopts
118 walkopts = cmdutil.walkopts
118 walkopts = cmdutil.walkopts
119 commitopts = cmdutil.commitopts
119 commitopts = cmdutil.commitopts
120 commitopts2 = cmdutil.commitopts2
120 commitopts2 = cmdutil.commitopts2
121 formatteropts = cmdutil.formatteropts
121 formatteropts = cmdutil.formatteropts
122 templateopts = cmdutil.templateopts
122 templateopts = cmdutil.templateopts
123 logopts = cmdutil.logopts
123 logopts = cmdutil.logopts
124 diffopts = cmdutil.diffopts
124 diffopts = cmdutil.diffopts
125 diffwsopts = cmdutil.diffwsopts
125 diffwsopts = cmdutil.diffwsopts
126 diffopts2 = cmdutil.diffopts2
126 diffopts2 = cmdutil.diffopts2
127 mergetoolopts = cmdutil.mergetoolopts
127 mergetoolopts = cmdutil.mergetoolopts
128 similarityopts = cmdutil.similarityopts
128 similarityopts = cmdutil.similarityopts
129 subrepoopts = cmdutil.subrepoopts
129 subrepoopts = cmdutil.subrepoopts
130 debugrevlogopts = cmdutil.debugrevlogopts
130 debugrevlogopts = cmdutil.debugrevlogopts
131
131
132 # Commands start here, listed alphabetically
132 # Commands start here, listed alphabetically
133
133
134 @command('add',
134 @command('add',
135 walkopts + subrepoopts + dryrunopts,
135 walkopts + subrepoopts + dryrunopts,
136 _('[OPTION]... [FILE]...'),
136 _('[OPTION]... [FILE]...'),
137 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
137 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
138 helpbasic=True, inferrepo=True)
138 helpbasic=True, inferrepo=True)
139 def add(ui, repo, *pats, **opts):
139 def add(ui, repo, *pats, **opts):
140 """add the specified files on the next commit
140 """add the specified files on the next commit
141
141
142 Schedule files to be version controlled and added to the
142 Schedule files to be version controlled and added to the
143 repository.
143 repository.
144
144
145 The files will be added to the repository at the next commit. To
145 The files will be added to the repository at the next commit. To
146 undo an add before that, see :hg:`forget`.
146 undo an add before that, see :hg:`forget`.
147
147
148 If no names are given, add all files to the repository (except
148 If no names are given, add all files to the repository (except
149 files matching ``.hgignore``).
149 files matching ``.hgignore``).
150
150
151 .. container:: verbose
151 .. container:: verbose
152
152
153 Examples:
153 Examples:
154
154
155 - New (unknown) files are added
155 - New (unknown) files are added
156 automatically by :hg:`add`::
156 automatically by :hg:`add`::
157
157
158 $ ls
158 $ ls
159 foo.c
159 foo.c
160 $ hg status
160 $ hg status
161 ? foo.c
161 ? foo.c
162 $ hg add
162 $ hg add
163 adding foo.c
163 adding foo.c
164 $ hg status
164 $ hg status
165 A foo.c
165 A foo.c
166
166
167 - Specific files to be added can be specified::
167 - Specific files to be added can be specified::
168
168
169 $ ls
169 $ ls
170 bar.c foo.c
170 bar.c foo.c
171 $ hg status
171 $ hg status
172 ? bar.c
172 ? bar.c
173 ? foo.c
173 ? foo.c
174 $ hg add bar.c
174 $ hg add bar.c
175 $ hg status
175 $ hg status
176 A bar.c
176 A bar.c
177 ? foo.c
177 ? foo.c
178
178
179 Returns 0 if all files are successfully added.
179 Returns 0 if all files are successfully added.
180 """
180 """
181
181
182 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
182 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
183 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=True)
183 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=True)
184 rejected = cmdutil.add(ui, repo, m, "", uipathfn, False, **opts)
184 rejected = cmdutil.add(ui, repo, m, "", uipathfn, False, **opts)
185 return rejected and 1 or 0
185 return rejected and 1 or 0
186
186
187 @command('addremove',
187 @command('addremove',
188 similarityopts + subrepoopts + walkopts + dryrunopts,
188 similarityopts + subrepoopts + walkopts + dryrunopts,
189 _('[OPTION]... [FILE]...'),
189 _('[OPTION]... [FILE]...'),
190 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
190 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
191 inferrepo=True)
191 inferrepo=True)
192 def addremove(ui, repo, *pats, **opts):
192 def addremove(ui, repo, *pats, **opts):
193 """add all new files, delete all missing files
193 """add all new files, delete all missing files
194
194
195 Add all new files and remove all missing files from the
195 Add all new files and remove all missing files from the
196 repository.
196 repository.
197
197
198 Unless names are given, new files are ignored if they match any of
198 Unless names are given, new files are ignored if they match any of
199 the patterns in ``.hgignore``. As with add, these changes take
199 the patterns in ``.hgignore``. As with add, these changes take
200 effect at the next commit.
200 effect at the next commit.
201
201
202 Use the -s/--similarity option to detect renamed files. This
202 Use the -s/--similarity option to detect renamed files. This
203 option takes a percentage between 0 (disabled) and 100 (files must
203 option takes a percentage between 0 (disabled) and 100 (files must
204 be identical) as its parameter. With a parameter greater than 0,
204 be identical) as its parameter. With a parameter greater than 0,
205 this compares every removed file with every added file and records
205 this compares every removed file with every added file and records
206 those similar enough as renames. Detecting renamed files this way
206 those similar enough as renames. Detecting renamed files this way
207 can be expensive. After using this option, :hg:`status -C` can be
207 can be expensive. After using this option, :hg:`status -C` can be
208 used to check which files were identified as moved or renamed. If
208 used to check which files were identified as moved or renamed. If
209 not specified, -s/--similarity defaults to 100 and only renames of
209 not specified, -s/--similarity defaults to 100 and only renames of
210 identical files are detected.
210 identical files are detected.
211
211
212 .. container:: verbose
212 .. container:: verbose
213
213
214 Examples:
214 Examples:
215
215
216 - A number of files (bar.c and foo.c) are new,
216 - A number of files (bar.c and foo.c) are new,
217 while foobar.c has been removed (without using :hg:`remove`)
217 while foobar.c has been removed (without using :hg:`remove`)
218 from the repository::
218 from the repository::
219
219
220 $ ls
220 $ ls
221 bar.c foo.c
221 bar.c foo.c
222 $ hg status
222 $ hg status
223 ! foobar.c
223 ! foobar.c
224 ? bar.c
224 ? bar.c
225 ? foo.c
225 ? foo.c
226 $ hg addremove
226 $ hg addremove
227 adding bar.c
227 adding bar.c
228 adding foo.c
228 adding foo.c
229 removing foobar.c
229 removing foobar.c
230 $ hg status
230 $ hg status
231 A bar.c
231 A bar.c
232 A foo.c
232 A foo.c
233 R foobar.c
233 R foobar.c
234
234
235 - A file foobar.c was moved to foo.c without using :hg:`rename`.
235 - A file foobar.c was moved to foo.c without using :hg:`rename`.
236 Afterwards, it was edited slightly::
236 Afterwards, it was edited slightly::
237
237
238 $ ls
238 $ ls
239 foo.c
239 foo.c
240 $ hg status
240 $ hg status
241 ! foobar.c
241 ! foobar.c
242 ? foo.c
242 ? foo.c
243 $ hg addremove --similarity 90
243 $ hg addremove --similarity 90
244 removing foobar.c
244 removing foobar.c
245 adding foo.c
245 adding foo.c
246 recording removal of foobar.c as rename to foo.c (94% similar)
246 recording removal of foobar.c as rename to foo.c (94% similar)
247 $ hg status -C
247 $ hg status -C
248 A foo.c
248 A foo.c
249 foobar.c
249 foobar.c
250 R foobar.c
250 R foobar.c
251
251
252 Returns 0 if all files are successfully added.
252 Returns 0 if all files are successfully added.
253 """
253 """
254 opts = pycompat.byteskwargs(opts)
254 opts = pycompat.byteskwargs(opts)
255 if not opts.get('similarity'):
255 if not opts.get('similarity'):
256 opts['similarity'] = '100'
256 opts['similarity'] = '100'
257 matcher = scmutil.match(repo[None], pats, opts)
257 matcher = scmutil.match(repo[None], pats, opts)
258 relative = scmutil.anypats(pats, opts)
258 relative = scmutil.anypats(pats, opts)
259 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=relative)
259 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=relative)
260 return scmutil.addremove(repo, matcher, "", uipathfn, opts)
260 return scmutil.addremove(repo, matcher, "", uipathfn, opts)
261
261
262 @command('annotate|blame',
262 @command('annotate|blame',
263 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
263 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
264 ('', 'follow', None,
264 ('', 'follow', None,
265 _('follow copies/renames and list the filename (DEPRECATED)')),
265 _('follow copies/renames and list the filename (DEPRECATED)')),
266 ('', 'no-follow', None, _("don't follow copies and renames")),
266 ('', 'no-follow', None, _("don't follow copies and renames")),
267 ('a', 'text', None, _('treat all files as text')),
267 ('a', 'text', None, _('treat all files as text')),
268 ('u', 'user', None, _('list the author (long with -v)')),
268 ('u', 'user', None, _('list the author (long with -v)')),
269 ('f', 'file', None, _('list the filename')),
269 ('f', 'file', None, _('list the filename')),
270 ('d', 'date', None, _('list the date (short with -q)')),
270 ('d', 'date', None, _('list the date (short with -q)')),
271 ('n', 'number', None, _('list the revision number (default)')),
271 ('n', 'number', None, _('list the revision number (default)')),
272 ('c', 'changeset', None, _('list the changeset')),
272 ('c', 'changeset', None, _('list the changeset')),
273 ('l', 'line-number', None, _('show line number at the first appearance')),
273 ('l', 'line-number', None, _('show line number at the first appearance')),
274 ('', 'skip', [], _('revision to not display (EXPERIMENTAL)'), _('REV')),
274 ('', 'skip', [], _('revision to not display (EXPERIMENTAL)'), _('REV')),
275 ] + diffwsopts + walkopts + formatteropts,
275 ] + diffwsopts + walkopts + formatteropts,
276 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
276 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
277 helpcategory=command.CATEGORY_FILE_CONTENTS,
277 helpcategory=command.CATEGORY_FILE_CONTENTS,
278 helpbasic=True, inferrepo=True)
278 helpbasic=True, inferrepo=True)
279 def annotate(ui, repo, *pats, **opts):
279 def annotate(ui, repo, *pats, **opts):
280 """show changeset information by line for each file
280 """show changeset information by line for each file
281
281
282 List changes in files, showing the revision id responsible for
282 List changes in files, showing the revision id responsible for
283 each line.
283 each line.
284
284
285 This command is useful for discovering when a change was made and
285 This command is useful for discovering when a change was made and
286 by whom.
286 by whom.
287
287
288 If you include --file, --user, or --date, the revision number is
288 If you include --file, --user, or --date, the revision number is
289 suppressed unless you also include --number.
289 suppressed unless you also include --number.
290
290
291 Without the -a/--text option, annotate will avoid processing files
291 Without the -a/--text option, annotate will avoid processing files
292 it detects as binary. With -a, annotate will annotate the file
292 it detects as binary. With -a, annotate will annotate the file
293 anyway, although the results will probably be neither useful
293 anyway, although the results will probably be neither useful
294 nor desirable.
294 nor desirable.
295
295
296 .. container:: verbose
296 .. container:: verbose
297
297
298 Template:
298 Template:
299
299
300 The following keywords are supported in addition to the common template
300 The following keywords are supported in addition to the common template
301 keywords and functions. See also :hg:`help templates`.
301 keywords and functions. See also :hg:`help templates`.
302
302
303 :lines: List of lines with annotation data.
303 :lines: List of lines with annotation data.
304 :path: String. Repository-absolute path of the specified file.
304 :path: String. Repository-absolute path of the specified file.
305
305
306 And each entry of ``{lines}`` provides the following sub-keywords in
306 And each entry of ``{lines}`` provides the following sub-keywords in
307 addition to ``{date}``, ``{node}``, ``{rev}``, ``{user}``, etc.
307 addition to ``{date}``, ``{node}``, ``{rev}``, ``{user}``, etc.
308
308
309 :line: String. Line content.
309 :line: String. Line content.
310 :lineno: Integer. Line number at that revision.
310 :lineno: Integer. Line number at that revision.
311 :path: String. Repository-absolute path of the file at that revision.
311 :path: String. Repository-absolute path of the file at that revision.
312
312
313 See :hg:`help templates.operators` for the list expansion syntax.
313 See :hg:`help templates.operators` for the list expansion syntax.
314
314
315 Returns 0 on success.
315 Returns 0 on success.
316 """
316 """
317 opts = pycompat.byteskwargs(opts)
317 opts = pycompat.byteskwargs(opts)
318 if not pats:
318 if not pats:
319 raise error.Abort(_('at least one filename or pattern is required'))
319 raise error.Abort(_('at least one filename or pattern is required'))
320
320
321 if opts.get('follow'):
321 if opts.get('follow'):
322 # --follow is deprecated and now just an alias for -f/--file
322 # --follow is deprecated and now just an alias for -f/--file
323 # to mimic the behavior of Mercurial before version 1.5
323 # to mimic the behavior of Mercurial before version 1.5
324 opts['file'] = True
324 opts['file'] = True
325
325
326 if (not opts.get('user') and not opts.get('changeset')
326 if (not opts.get('user') and not opts.get('changeset')
327 and not opts.get('date') and not opts.get('file')):
327 and not opts.get('date') and not opts.get('file')):
328 opts['number'] = True
328 opts['number'] = True
329
329
330 linenumber = opts.get('line_number') is not None
330 linenumber = opts.get('line_number') is not None
331 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
331 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
332 raise error.Abort(_('at least one of -n/-c is required for -l'))
332 raise error.Abort(_('at least one of -n/-c is required for -l'))
333
333
334 rev = opts.get('rev')
334 rev = opts.get('rev')
335 if rev:
335 if rev:
336 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
336 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
337 ctx = scmutil.revsingle(repo, rev)
337 ctx = scmutil.revsingle(repo, rev)
338
338
339 ui.pager('annotate')
339 ui.pager('annotate')
340 rootfm = ui.formatter('annotate', opts)
340 rootfm = ui.formatter('annotate', opts)
341 if ui.debugflag:
341 if ui.debugflag:
342 shorthex = pycompat.identity
342 shorthex = pycompat.identity
343 else:
343 else:
344 def shorthex(h):
344 def shorthex(h):
345 return h[:12]
345 return h[:12]
346 if ui.quiet:
346 if ui.quiet:
347 datefunc = dateutil.shortdate
347 datefunc = dateutil.shortdate
348 else:
348 else:
349 datefunc = dateutil.datestr
349 datefunc = dateutil.datestr
350 if ctx.rev() is None:
350 if ctx.rev() is None:
351 if opts.get('changeset'):
351 if opts.get('changeset'):
352 # omit "+" suffix which is appended to node hex
352 # omit "+" suffix which is appended to node hex
353 def formatrev(rev):
353 def formatrev(rev):
354 if rev == wdirrev:
354 if rev == wdirrev:
355 return '%d' % ctx.p1().rev()
355 return '%d' % ctx.p1().rev()
356 else:
356 else:
357 return '%d' % rev
357 return '%d' % rev
358 else:
358 else:
359 def formatrev(rev):
359 def formatrev(rev):
360 if rev == wdirrev:
360 if rev == wdirrev:
361 return '%d+' % ctx.p1().rev()
361 return '%d+' % ctx.p1().rev()
362 else:
362 else:
363 return '%d ' % rev
363 return '%d ' % rev
364 def formathex(h):
364 def formathex(h):
365 if h == wdirhex:
365 if h == wdirhex:
366 return '%s+' % shorthex(hex(ctx.p1().node()))
366 return '%s+' % shorthex(hex(ctx.p1().node()))
367 else:
367 else:
368 return '%s ' % shorthex(h)
368 return '%s ' % shorthex(h)
369 else:
369 else:
370 formatrev = b'%d'.__mod__
370 formatrev = b'%d'.__mod__
371 formathex = shorthex
371 formathex = shorthex
372
372
373 opmap = [
373 opmap = [
374 ('user', ' ', lambda x: x.fctx.user(), ui.shortuser),
374 ('user', ' ', lambda x: x.fctx.user(), ui.shortuser),
375 ('rev', ' ', lambda x: scmutil.intrev(x.fctx), formatrev),
375 ('rev', ' ', lambda x: scmutil.intrev(x.fctx), formatrev),
376 ('node', ' ', lambda x: hex(scmutil.binnode(x.fctx)), formathex),
376 ('node', ' ', lambda x: hex(scmutil.binnode(x.fctx)), formathex),
377 ('date', ' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
377 ('date', ' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
378 ('path', ' ', lambda x: x.fctx.path(), pycompat.bytestr),
378 ('path', ' ', lambda x: x.fctx.path(), pycompat.bytestr),
379 ('lineno', ':', lambda x: x.lineno, pycompat.bytestr),
379 ('lineno', ':', lambda x: x.lineno, pycompat.bytestr),
380 ]
380 ]
381 opnamemap = {
381 opnamemap = {
382 'rev': 'number',
382 'rev': 'number',
383 'node': 'changeset',
383 'node': 'changeset',
384 'path': 'file',
384 'path': 'file',
385 'lineno': 'line_number',
385 'lineno': 'line_number',
386 }
386 }
387
387
388 if rootfm.isplain():
388 if rootfm.isplain():
389 def makefunc(get, fmt):
389 def makefunc(get, fmt):
390 return lambda x: fmt(get(x))
390 return lambda x: fmt(get(x))
391 else:
391 else:
392 def makefunc(get, fmt):
392 def makefunc(get, fmt):
393 return get
393 return get
394 datahint = rootfm.datahint()
394 datahint = rootfm.datahint()
395 funcmap = [(makefunc(get, fmt), sep) for fn, sep, get, fmt in opmap
395 funcmap = [(makefunc(get, fmt), sep) for fn, sep, get, fmt in opmap
396 if opts.get(opnamemap.get(fn, fn)) or fn in datahint]
396 if opts.get(opnamemap.get(fn, fn)) or fn in datahint]
397 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
397 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
398 fields = ' '.join(fn for fn, sep, get, fmt in opmap
398 fields = ' '.join(fn for fn, sep, get, fmt in opmap
399 if opts.get(opnamemap.get(fn, fn)) or fn in datahint)
399 if opts.get(opnamemap.get(fn, fn)) or fn in datahint)
400
400
401 def bad(x, y):
401 def bad(x, y):
402 raise error.Abort("%s: %s" % (x, y))
402 raise error.Abort("%s: %s" % (x, y))
403
403
404 m = scmutil.match(ctx, pats, opts, badfn=bad)
404 m = scmutil.match(ctx, pats, opts, badfn=bad)
405
405
406 follow = not opts.get('no_follow')
406 follow = not opts.get('no_follow')
407 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
407 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
408 whitespace=True)
408 whitespace=True)
409 skiprevs = opts.get('skip')
409 skiprevs = opts.get('skip')
410 if skiprevs:
410 if skiprevs:
411 skiprevs = scmutil.revrange(repo, skiprevs)
411 skiprevs = scmutil.revrange(repo, skiprevs)
412
412
413 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
413 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
414 for abs in ctx.walk(m):
414 for abs in ctx.walk(m):
415 fctx = ctx[abs]
415 fctx = ctx[abs]
416 rootfm.startitem()
416 rootfm.startitem()
417 rootfm.data(path=abs)
417 rootfm.data(path=abs)
418 if not opts.get('text') and fctx.isbinary():
418 if not opts.get('text') and fctx.isbinary():
419 rootfm.plain(_("%s: binary file\n") % uipathfn(abs))
419 rootfm.plain(_("%s: binary file\n") % uipathfn(abs))
420 continue
420 continue
421
421
422 fm = rootfm.nested('lines', tmpl='{rev}: {line}')
422 fm = rootfm.nested('lines', tmpl='{rev}: {line}')
423 lines = fctx.annotate(follow=follow, skiprevs=skiprevs,
423 lines = fctx.annotate(follow=follow, skiprevs=skiprevs,
424 diffopts=diffopts)
424 diffopts=diffopts)
425 if not lines:
425 if not lines:
426 fm.end()
426 fm.end()
427 continue
427 continue
428 formats = []
428 formats = []
429 pieces = []
429 pieces = []
430
430
431 for f, sep in funcmap:
431 for f, sep in funcmap:
432 l = [f(n) for n in lines]
432 l = [f(n) for n in lines]
433 if fm.isplain():
433 if fm.isplain():
434 sizes = [encoding.colwidth(x) for x in l]
434 sizes = [encoding.colwidth(x) for x in l]
435 ml = max(sizes)
435 ml = max(sizes)
436 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
436 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
437 else:
437 else:
438 formats.append(['%s' for x in l])
438 formats.append(['%s' for x in l])
439 pieces.append(l)
439 pieces.append(l)
440
440
441 for f, p, n in zip(zip(*formats), zip(*pieces), lines):
441 for f, p, n in zip(zip(*formats), zip(*pieces), lines):
442 fm.startitem()
442 fm.startitem()
443 fm.context(fctx=n.fctx)
443 fm.context(fctx=n.fctx)
444 fm.write(fields, "".join(f), *p)
444 fm.write(fields, "".join(f), *p)
445 if n.skip:
445 if n.skip:
446 fmt = "* %s"
446 fmt = "* %s"
447 else:
447 else:
448 fmt = ": %s"
448 fmt = ": %s"
449 fm.write('line', fmt, n.text)
449 fm.write('line', fmt, n.text)
450
450
451 if not lines[-1].text.endswith('\n'):
451 if not lines[-1].text.endswith('\n'):
452 fm.plain('\n')
452 fm.plain('\n')
453 fm.end()
453 fm.end()
454
454
455 rootfm.end()
455 rootfm.end()
456
456
457 @command('archive',
457 @command('archive',
458 [('', 'no-decode', None, _('do not pass files through decoders')),
458 [('', 'no-decode', None, _('do not pass files through decoders')),
459 ('p', 'prefix', '', _('directory prefix for files in archive'),
459 ('p', 'prefix', '', _('directory prefix for files in archive'),
460 _('PREFIX')),
460 _('PREFIX')),
461 ('r', 'rev', '', _('revision to distribute'), _('REV')),
461 ('r', 'rev', '', _('revision to distribute'), _('REV')),
462 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
462 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
463 ] + subrepoopts + walkopts,
463 ] + subrepoopts + walkopts,
464 _('[OPTION]... DEST'),
464 _('[OPTION]... DEST'),
465 helpcategory=command.CATEGORY_IMPORT_EXPORT)
465 helpcategory=command.CATEGORY_IMPORT_EXPORT)
466 def archive(ui, repo, dest, **opts):
466 def archive(ui, repo, dest, **opts):
467 '''create an unversioned archive of a repository revision
467 '''create an unversioned archive of a repository revision
468
468
469 By default, the revision used is the parent of the working
469 By default, the revision used is the parent of the working
470 directory; use -r/--rev to specify a different revision.
470 directory; use -r/--rev to specify a different revision.
471
471
472 The archive type is automatically detected based on file
472 The archive type is automatically detected based on file
473 extension (to override, use -t/--type).
473 extension (to override, use -t/--type).
474
474
475 .. container:: verbose
475 .. container:: verbose
476
476
477 Examples:
477 Examples:
478
478
479 - create a zip file containing the 1.0 release::
479 - create a zip file containing the 1.0 release::
480
480
481 hg archive -r 1.0 project-1.0.zip
481 hg archive -r 1.0 project-1.0.zip
482
482
483 - create a tarball excluding .hg files::
483 - create a tarball excluding .hg files::
484
484
485 hg archive project.tar.gz -X ".hg*"
485 hg archive project.tar.gz -X ".hg*"
486
486
487 Valid types are:
487 Valid types are:
488
488
489 :``files``: a directory full of files (default)
489 :``files``: a directory full of files (default)
490 :``tar``: tar archive, uncompressed
490 :``tar``: tar archive, uncompressed
491 :``tbz2``: tar archive, compressed using bzip2
491 :``tbz2``: tar archive, compressed using bzip2
492 :``tgz``: tar archive, compressed using gzip
492 :``tgz``: tar archive, compressed using gzip
493 :``uzip``: zip archive, uncompressed
493 :``uzip``: zip archive, uncompressed
494 :``zip``: zip archive, compressed using deflate
494 :``zip``: zip archive, compressed using deflate
495
495
496 The exact name of the destination archive or directory is given
496 The exact name of the destination archive or directory is given
497 using a format string; see :hg:`help export` for details.
497 using a format string; see :hg:`help export` for details.
498
498
499 Each member added to an archive file has a directory prefix
499 Each member added to an archive file has a directory prefix
500 prepended. Use -p/--prefix to specify a format string for the
500 prepended. Use -p/--prefix to specify a format string for the
501 prefix. The default is the basename of the archive, with suffixes
501 prefix. The default is the basename of the archive, with suffixes
502 removed.
502 removed.
503
503
504 Returns 0 on success.
504 Returns 0 on success.
505 '''
505 '''
506
506
507 opts = pycompat.byteskwargs(opts)
507 opts = pycompat.byteskwargs(opts)
508 rev = opts.get('rev')
508 rev = opts.get('rev')
509 if rev:
509 if rev:
510 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
510 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
511 ctx = scmutil.revsingle(repo, rev)
511 ctx = scmutil.revsingle(repo, rev)
512 if not ctx:
512 if not ctx:
513 raise error.Abort(_('no working directory: please specify a revision'))
513 raise error.Abort(_('no working directory: please specify a revision'))
514 node = ctx.node()
514 node = ctx.node()
515 dest = cmdutil.makefilename(ctx, dest)
515 dest = cmdutil.makefilename(ctx, dest)
516 if os.path.realpath(dest) == repo.root:
516 if os.path.realpath(dest) == repo.root:
517 raise error.Abort(_('repository root cannot be destination'))
517 raise error.Abort(_('repository root cannot be destination'))
518
518
519 kind = opts.get('type') or archival.guesskind(dest) or 'files'
519 kind = opts.get('type') or archival.guesskind(dest) or 'files'
520 prefix = opts.get('prefix')
520 prefix = opts.get('prefix')
521
521
522 if dest == '-':
522 if dest == '-':
523 if kind == 'files':
523 if kind == 'files':
524 raise error.Abort(_('cannot archive plain files to stdout'))
524 raise error.Abort(_('cannot archive plain files to stdout'))
525 dest = cmdutil.makefileobj(ctx, dest)
525 dest = cmdutil.makefileobj(ctx, dest)
526 if not prefix:
526 if not prefix:
527 prefix = os.path.basename(repo.root) + '-%h'
527 prefix = os.path.basename(repo.root) + '-%h'
528
528
529 prefix = cmdutil.makefilename(ctx, prefix)
529 prefix = cmdutil.makefilename(ctx, prefix)
530 match = scmutil.match(ctx, [], opts)
530 match = scmutil.match(ctx, [], opts)
531 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
531 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
532 match, prefix, subrepos=opts.get('subrepos'))
532 match, prefix, subrepos=opts.get('subrepos'))
533
533
534 @command('backout',
534 @command('backout',
535 [('', 'merge', None, _('merge with old dirstate parent after backout')),
535 [('', 'merge', None, _('merge with old dirstate parent after backout')),
536 ('', 'commit', None,
536 ('', 'commit', None,
537 _('commit if no conflicts were encountered (DEPRECATED)')),
537 _('commit if no conflicts were encountered (DEPRECATED)')),
538 ('', 'no-commit', None, _('do not commit')),
538 ('', 'no-commit', None, _('do not commit')),
539 ('', 'parent', '',
539 ('', 'parent', '',
540 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
540 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
541 ('r', 'rev', '', _('revision to backout'), _('REV')),
541 ('r', 'rev', '', _('revision to backout'), _('REV')),
542 ('e', 'edit', False, _('invoke editor on commit messages')),
542 ('e', 'edit', False, _('invoke editor on commit messages')),
543 ] + mergetoolopts + walkopts + commitopts + commitopts2,
543 ] + mergetoolopts + walkopts + commitopts + commitopts2,
544 _('[OPTION]... [-r] REV'),
544 _('[OPTION]... [-r] REV'),
545 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT)
545 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT)
546 def backout(ui, repo, node=None, rev=None, **opts):
546 def backout(ui, repo, node=None, rev=None, **opts):
547 '''reverse effect of earlier changeset
547 '''reverse effect of earlier changeset
548
548
549 Prepare a new changeset with the effect of REV undone in the
549 Prepare a new changeset with the effect of REV undone in the
550 current working directory. If no conflicts were encountered,
550 current working directory. If no conflicts were encountered,
551 it will be committed immediately.
551 it will be committed immediately.
552
552
553 If REV is the parent of the working directory, then this new changeset
553 If REV is the parent of the working directory, then this new changeset
554 is committed automatically (unless --no-commit is specified).
554 is committed automatically (unless --no-commit is specified).
555
555
556 .. note::
556 .. note::
557
557
558 :hg:`backout` cannot be used to fix either an unwanted or
558 :hg:`backout` cannot be used to fix either an unwanted or
559 incorrect merge.
559 incorrect merge.
560
560
561 .. container:: verbose
561 .. container:: verbose
562
562
563 Examples:
563 Examples:
564
564
565 - Reverse the effect of the parent of the working directory.
565 - Reverse the effect of the parent of the working directory.
566 This backout will be committed immediately::
566 This backout will be committed immediately::
567
567
568 hg backout -r .
568 hg backout -r .
569
569
570 - Reverse the effect of previous bad revision 23::
570 - Reverse the effect of previous bad revision 23::
571
571
572 hg backout -r 23
572 hg backout -r 23
573
573
574 - Reverse the effect of previous bad revision 23 and
574 - Reverse the effect of previous bad revision 23 and
575 leave changes uncommitted::
575 leave changes uncommitted::
576
576
577 hg backout -r 23 --no-commit
577 hg backout -r 23 --no-commit
578 hg commit -m "Backout revision 23"
578 hg commit -m "Backout revision 23"
579
579
580 By default, the pending changeset will have one parent,
580 By default, the pending changeset will have one parent,
581 maintaining a linear history. With --merge, the pending
581 maintaining a linear history. With --merge, the pending
582 changeset will instead have two parents: the old parent of the
582 changeset will instead have two parents: the old parent of the
583 working directory and a new child of REV that simply undoes REV.
583 working directory and a new child of REV that simply undoes REV.
584
584
585 Before version 1.7, the behavior without --merge was equivalent
585 Before version 1.7, the behavior without --merge was equivalent
586 to specifying --merge followed by :hg:`update --clean .` to
586 to specifying --merge followed by :hg:`update --clean .` to
587 cancel the merge and leave the child of REV as a head to be
587 cancel the merge and leave the child of REV as a head to be
588 merged separately.
588 merged separately.
589
589
590 See :hg:`help dates` for a list of formats valid for -d/--date.
590 See :hg:`help dates` for a list of formats valid for -d/--date.
591
591
592 See :hg:`help revert` for a way to restore files to the state
592 See :hg:`help revert` for a way to restore files to the state
593 of another revision.
593 of another revision.
594
594
595 Returns 0 on success, 1 if nothing to backout or there are unresolved
595 Returns 0 on success, 1 if nothing to backout or there are unresolved
596 files.
596 files.
597 '''
597 '''
598 with repo.wlock(), repo.lock():
598 with repo.wlock(), repo.lock():
599 return _dobackout(ui, repo, node, rev, **opts)
599 return _dobackout(ui, repo, node, rev, **opts)
600
600
601 def _dobackout(ui, repo, node=None, rev=None, **opts):
601 def _dobackout(ui, repo, node=None, rev=None, **opts):
602 opts = pycompat.byteskwargs(opts)
602 opts = pycompat.byteskwargs(opts)
603 if opts.get('commit') and opts.get('no_commit'):
603 if opts.get('commit') and opts.get('no_commit'):
604 raise error.Abort(_("cannot use --commit with --no-commit"))
604 raise error.Abort(_("cannot use --commit with --no-commit"))
605 if opts.get('merge') and opts.get('no_commit'):
605 if opts.get('merge') and opts.get('no_commit'):
606 raise error.Abort(_("cannot use --merge with --no-commit"))
606 raise error.Abort(_("cannot use --merge with --no-commit"))
607
607
608 if rev and node:
608 if rev and node:
609 raise error.Abort(_("please specify just one revision"))
609 raise error.Abort(_("please specify just one revision"))
610
610
611 if not rev:
611 if not rev:
612 rev = node
612 rev = node
613
613
614 if not rev:
614 if not rev:
615 raise error.Abort(_("please specify a revision to backout"))
615 raise error.Abort(_("please specify a revision to backout"))
616
616
617 date = opts.get('date')
617 date = opts.get('date')
618 if date:
618 if date:
619 opts['date'] = dateutil.parsedate(date)
619 opts['date'] = dateutil.parsedate(date)
620
620
621 cmdutil.checkunfinished(repo)
621 cmdutil.checkunfinished(repo)
622 cmdutil.bailifchanged(repo)
622 cmdutil.bailifchanged(repo)
623 node = scmutil.revsingle(repo, rev).node()
623 node = scmutil.revsingle(repo, rev).node()
624
624
625 op1, op2 = repo.dirstate.parents()
625 op1, op2 = repo.dirstate.parents()
626 if not repo.changelog.isancestor(node, op1):
626 if not repo.changelog.isancestor(node, op1):
627 raise error.Abort(_('cannot backout change that is not an ancestor'))
627 raise error.Abort(_('cannot backout change that is not an ancestor'))
628
628
629 p1, p2 = repo.changelog.parents(node)
629 p1, p2 = repo.changelog.parents(node)
630 if p1 == nullid:
630 if p1 == nullid:
631 raise error.Abort(_('cannot backout a change with no parents'))
631 raise error.Abort(_('cannot backout a change with no parents'))
632 if p2 != nullid:
632 if p2 != nullid:
633 if not opts.get('parent'):
633 if not opts.get('parent'):
634 raise error.Abort(_('cannot backout a merge changeset'))
634 raise error.Abort(_('cannot backout a merge changeset'))
635 p = repo.lookup(opts['parent'])
635 p = repo.lookup(opts['parent'])
636 if p not in (p1, p2):
636 if p not in (p1, p2):
637 raise error.Abort(_('%s is not a parent of %s') %
637 raise error.Abort(_('%s is not a parent of %s') %
638 (short(p), short(node)))
638 (short(p), short(node)))
639 parent = p
639 parent = p
640 else:
640 else:
641 if opts.get('parent'):
641 if opts.get('parent'):
642 raise error.Abort(_('cannot use --parent on non-merge changeset'))
642 raise error.Abort(_('cannot use --parent on non-merge changeset'))
643 parent = p1
643 parent = p1
644
644
645 # the backout should appear on the same branch
645 # the backout should appear on the same branch
646 branch = repo.dirstate.branch()
646 branch = repo.dirstate.branch()
647 bheads = repo.branchheads(branch)
647 bheads = repo.branchheads(branch)
648 rctx = scmutil.revsingle(repo, hex(parent))
648 rctx = scmutil.revsingle(repo, hex(parent))
649 if not opts.get('merge') and op1 != node:
649 if not opts.get('merge') and op1 != node:
650 with dirstateguard.dirstateguard(repo, 'backout'):
650 with dirstateguard.dirstateguard(repo, 'backout'):
651 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
651 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
652 with ui.configoverride(overrides, 'backout'):
652 with ui.configoverride(overrides, 'backout'):
653 stats = mergemod.update(repo, parent, branchmerge=True,
653 stats = mergemod.update(repo, parent, branchmerge=True,
654 force=True, ancestor=node,
654 force=True, ancestor=node,
655 mergeancestor=False)
655 mergeancestor=False)
656 repo.setparents(op1, op2)
656 repo.setparents(op1, op2)
657 hg._showstats(repo, stats)
657 hg._showstats(repo, stats)
658 if stats.unresolvedcount:
658 if stats.unresolvedcount:
659 repo.ui.status(_("use 'hg resolve' to retry unresolved "
659 repo.ui.status(_("use 'hg resolve' to retry unresolved "
660 "file merges\n"))
660 "file merges\n"))
661 return 1
661 return 1
662 else:
662 else:
663 hg.clean(repo, node, show_stats=False)
663 hg.clean(repo, node, show_stats=False)
664 repo.dirstate.setbranch(branch)
664 repo.dirstate.setbranch(branch)
665 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
665 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
666
666
667 if opts.get('no_commit'):
667 if opts.get('no_commit'):
668 msg = _("changeset %s backed out, "
668 msg = _("changeset %s backed out, "
669 "don't forget to commit.\n")
669 "don't forget to commit.\n")
670 ui.status(msg % short(node))
670 ui.status(msg % short(node))
671 return 0
671 return 0
672
672
673 def commitfunc(ui, repo, message, match, opts):
673 def commitfunc(ui, repo, message, match, opts):
674 editform = 'backout'
674 editform = 'backout'
675 e = cmdutil.getcommiteditor(editform=editform,
675 e = cmdutil.getcommiteditor(editform=editform,
676 **pycompat.strkwargs(opts))
676 **pycompat.strkwargs(opts))
677 if not message:
677 if not message:
678 # we don't translate commit messages
678 # we don't translate commit messages
679 message = "Backed out changeset %s" % short(node)
679 message = "Backed out changeset %s" % short(node)
680 e = cmdutil.getcommiteditor(edit=True, editform=editform)
680 e = cmdutil.getcommiteditor(edit=True, editform=editform)
681 return repo.commit(message, opts.get('user'), opts.get('date'),
681 return repo.commit(message, opts.get('user'), opts.get('date'),
682 match, editor=e)
682 match, editor=e)
683 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
683 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
684 if not newnode:
684 if not newnode:
685 ui.status(_("nothing changed\n"))
685 ui.status(_("nothing changed\n"))
686 return 1
686 return 1
687 cmdutil.commitstatus(repo, newnode, branch, bheads)
687 cmdutil.commitstatus(repo, newnode, branch, bheads)
688
688
689 def nice(node):
689 def nice(node):
690 return '%d:%s' % (repo.changelog.rev(node), short(node))
690 return '%d:%s' % (repo.changelog.rev(node), short(node))
691 ui.status(_('changeset %s backs out changeset %s\n') %
691 ui.status(_('changeset %s backs out changeset %s\n') %
692 (nice(repo.changelog.tip()), nice(node)))
692 (nice(repo.changelog.tip()), nice(node)))
693 if opts.get('merge') and op1 != node:
693 if opts.get('merge') and op1 != node:
694 hg.clean(repo, op1, show_stats=False)
694 hg.clean(repo, op1, show_stats=False)
695 ui.status(_('merging with changeset %s\n')
695 ui.status(_('merging with changeset %s\n')
696 % nice(repo.changelog.tip()))
696 % nice(repo.changelog.tip()))
697 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
697 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
698 with ui.configoverride(overrides, 'backout'):
698 with ui.configoverride(overrides, 'backout'):
699 return hg.merge(repo, hex(repo.changelog.tip()))
699 return hg.merge(repo, hex(repo.changelog.tip()))
700 return 0
700 return 0
701
701
702 @command('bisect',
702 @command('bisect',
703 [('r', 'reset', False, _('reset bisect state')),
703 [('r', 'reset', False, _('reset bisect state')),
704 ('g', 'good', False, _('mark changeset good')),
704 ('g', 'good', False, _('mark changeset good')),
705 ('b', 'bad', False, _('mark changeset bad')),
705 ('b', 'bad', False, _('mark changeset bad')),
706 ('s', 'skip', False, _('skip testing changeset')),
706 ('s', 'skip', False, _('skip testing changeset')),
707 ('e', 'extend', False, _('extend the bisect range')),
707 ('e', 'extend', False, _('extend the bisect range')),
708 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
708 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
709 ('U', 'noupdate', False, _('do not update to target'))],
709 ('U', 'noupdate', False, _('do not update to target'))],
710 _("[-gbsr] [-U] [-c CMD] [REV]"),
710 _("[-gbsr] [-U] [-c CMD] [REV]"),
711 helpcategory=command.CATEGORY_CHANGE_NAVIGATION)
711 helpcategory=command.CATEGORY_CHANGE_NAVIGATION)
712 def bisect(ui, repo, rev=None, extra=None, command=None,
712 def bisect(ui, repo, rev=None, extra=None, command=None,
713 reset=None, good=None, bad=None, skip=None, extend=None,
713 reset=None, good=None, bad=None, skip=None, extend=None,
714 noupdate=None):
714 noupdate=None):
715 """subdivision search of changesets
715 """subdivision search of changesets
716
716
717 This command helps to find changesets which introduce problems. To
717 This command helps to find changesets which introduce problems. To
718 use, mark the earliest changeset you know exhibits the problem as
718 use, mark the earliest changeset you know exhibits the problem as
719 bad, then mark the latest changeset which is free from the problem
719 bad, then mark the latest changeset which is free from the problem
720 as good. Bisect will update your working directory to a revision
720 as good. Bisect will update your working directory to a revision
721 for testing (unless the -U/--noupdate option is specified). Once
721 for testing (unless the -U/--noupdate option is specified). Once
722 you have performed tests, mark the working directory as good or
722 you have performed tests, mark the working directory as good or
723 bad, and bisect will either update to another candidate changeset
723 bad, and bisect will either update to another candidate changeset
724 or announce that it has found the bad revision.
724 or announce that it has found the bad revision.
725
725
726 As a shortcut, you can also use the revision argument to mark a
726 As a shortcut, you can also use the revision argument to mark a
727 revision as good or bad without checking it out first.
727 revision as good or bad without checking it out first.
728
728
729 If you supply a command, it will be used for automatic bisection.
729 If you supply a command, it will be used for automatic bisection.
730 The environment variable HG_NODE will contain the ID of the
730 The environment variable HG_NODE will contain the ID of the
731 changeset being tested. The exit status of the command will be
731 changeset being tested. The exit status of the command will be
732 used to mark revisions as good or bad: status 0 means good, 125
732 used to mark revisions as good or bad: status 0 means good, 125
733 means to skip the revision, 127 (command not found) will abort the
733 means to skip the revision, 127 (command not found) will abort the
734 bisection, and any other non-zero exit status means the revision
734 bisection, and any other non-zero exit status means the revision
735 is bad.
735 is bad.
736
736
737 .. container:: verbose
737 .. container:: verbose
738
738
739 Some examples:
739 Some examples:
740
740
741 - start a bisection with known bad revision 34, and good revision 12::
741 - start a bisection with known bad revision 34, and good revision 12::
742
742
743 hg bisect --bad 34
743 hg bisect --bad 34
744 hg bisect --good 12
744 hg bisect --good 12
745
745
746 - advance the current bisection by marking current revision as good or
746 - advance the current bisection by marking current revision as good or
747 bad::
747 bad::
748
748
749 hg bisect --good
749 hg bisect --good
750 hg bisect --bad
750 hg bisect --bad
751
751
752 - mark the current revision, or a known revision, to be skipped (e.g. if
752 - mark the current revision, or a known revision, to be skipped (e.g. if
753 that revision is not usable because of another issue)::
753 that revision is not usable because of another issue)::
754
754
755 hg bisect --skip
755 hg bisect --skip
756 hg bisect --skip 23
756 hg bisect --skip 23
757
757
758 - skip all revisions that do not touch directories ``foo`` or ``bar``::
758 - skip all revisions that do not touch directories ``foo`` or ``bar``::
759
759
760 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
760 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
761
761
762 - forget the current bisection::
762 - forget the current bisection::
763
763
764 hg bisect --reset
764 hg bisect --reset
765
765
766 - use 'make && make tests' to automatically find the first broken
766 - use 'make && make tests' to automatically find the first broken
767 revision::
767 revision::
768
768
769 hg bisect --reset
769 hg bisect --reset
770 hg bisect --bad 34
770 hg bisect --bad 34
771 hg bisect --good 12
771 hg bisect --good 12
772 hg bisect --command "make && make tests"
772 hg bisect --command "make && make tests"
773
773
774 - see all changesets whose states are already known in the current
774 - see all changesets whose states are already known in the current
775 bisection::
775 bisection::
776
776
777 hg log -r "bisect(pruned)"
777 hg log -r "bisect(pruned)"
778
778
779 - see the changeset currently being bisected (especially useful
779 - see the changeset currently being bisected (especially useful
780 if running with -U/--noupdate)::
780 if running with -U/--noupdate)::
781
781
782 hg log -r "bisect(current)"
782 hg log -r "bisect(current)"
783
783
784 - see all changesets that took part in the current bisection::
784 - see all changesets that took part in the current bisection::
785
785
786 hg log -r "bisect(range)"
786 hg log -r "bisect(range)"
787
787
788 - you can even get a nice graph::
788 - you can even get a nice graph::
789
789
790 hg log --graph -r "bisect(range)"
790 hg log --graph -r "bisect(range)"
791
791
792 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
792 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
793
793
794 Returns 0 on success.
794 Returns 0 on success.
795 """
795 """
796 # backward compatibility
796 # backward compatibility
797 if rev in "good bad reset init".split():
797 if rev in "good bad reset init".split():
798 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
798 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
799 cmd, rev, extra = rev, extra, None
799 cmd, rev, extra = rev, extra, None
800 if cmd == "good":
800 if cmd == "good":
801 good = True
801 good = True
802 elif cmd == "bad":
802 elif cmd == "bad":
803 bad = True
803 bad = True
804 else:
804 else:
805 reset = True
805 reset = True
806 elif extra:
806 elif extra:
807 raise error.Abort(_('incompatible arguments'))
807 raise error.Abort(_('incompatible arguments'))
808
808
809 incompatibles = {
809 incompatibles = {
810 '--bad': bad,
810 '--bad': bad,
811 '--command': bool(command),
811 '--command': bool(command),
812 '--extend': extend,
812 '--extend': extend,
813 '--good': good,
813 '--good': good,
814 '--reset': reset,
814 '--reset': reset,
815 '--skip': skip,
815 '--skip': skip,
816 }
816 }
817
817
818 enabled = [x for x in incompatibles if incompatibles[x]]
818 enabled = [x for x in incompatibles if incompatibles[x]]
819
819
820 if len(enabled) > 1:
820 if len(enabled) > 1:
821 raise error.Abort(_('%s and %s are incompatible') %
821 raise error.Abort(_('%s and %s are incompatible') %
822 tuple(sorted(enabled)[0:2]))
822 tuple(sorted(enabled)[0:2]))
823
823
824 if reset:
824 if reset:
825 hbisect.resetstate(repo)
825 hbisect.resetstate(repo)
826 return
826 return
827
827
828 state = hbisect.load_state(repo)
828 state = hbisect.load_state(repo)
829
829
830 # update state
830 # update state
831 if good or bad or skip:
831 if good or bad or skip:
832 if rev:
832 if rev:
833 nodes = [repo[i].node() for i in scmutil.revrange(repo, [rev])]
833 nodes = [repo[i].node() for i in scmutil.revrange(repo, [rev])]
834 else:
834 else:
835 nodes = [repo.lookup('.')]
835 nodes = [repo.lookup('.')]
836 if good:
836 if good:
837 state['good'] += nodes
837 state['good'] += nodes
838 elif bad:
838 elif bad:
839 state['bad'] += nodes
839 state['bad'] += nodes
840 elif skip:
840 elif skip:
841 state['skip'] += nodes
841 state['skip'] += nodes
842 hbisect.save_state(repo, state)
842 hbisect.save_state(repo, state)
843 if not (state['good'] and state['bad']):
843 if not (state['good'] and state['bad']):
844 return
844 return
845
845
846 def mayupdate(repo, node, show_stats=True):
846 def mayupdate(repo, node, show_stats=True):
847 """common used update sequence"""
847 """common used update sequence"""
848 if noupdate:
848 if noupdate:
849 return
849 return
850 cmdutil.checkunfinished(repo)
850 cmdutil.checkunfinished(repo)
851 cmdutil.bailifchanged(repo)
851 cmdutil.bailifchanged(repo)
852 return hg.clean(repo, node, show_stats=show_stats)
852 return hg.clean(repo, node, show_stats=show_stats)
853
853
854 displayer = logcmdutil.changesetdisplayer(ui, repo, {})
854 displayer = logcmdutil.changesetdisplayer(ui, repo, {})
855
855
856 if command:
856 if command:
857 changesets = 1
857 changesets = 1
858 if noupdate:
858 if noupdate:
859 try:
859 try:
860 node = state['current'][0]
860 node = state['current'][0]
861 except LookupError:
861 except LookupError:
862 raise error.Abort(_('current bisect revision is unknown - '
862 raise error.Abort(_('current bisect revision is unknown - '
863 'start a new bisect to fix'))
863 'start a new bisect to fix'))
864 else:
864 else:
865 node, p2 = repo.dirstate.parents()
865 node, p2 = repo.dirstate.parents()
866 if p2 != nullid:
866 if p2 != nullid:
867 raise error.Abort(_('current bisect revision is a merge'))
867 raise error.Abort(_('current bisect revision is a merge'))
868 if rev:
868 if rev:
869 node = repo[scmutil.revsingle(repo, rev, node)].node()
869 node = repo[scmutil.revsingle(repo, rev, node)].node()
870 try:
870 try:
871 while changesets:
871 while changesets:
872 # update state
872 # update state
873 state['current'] = [node]
873 state['current'] = [node]
874 hbisect.save_state(repo, state)
874 hbisect.save_state(repo, state)
875 status = ui.system(command, environ={'HG_NODE': hex(node)},
875 status = ui.system(command, environ={'HG_NODE': hex(node)},
876 blockedtag='bisect_check')
876 blockedtag='bisect_check')
877 if status == 125:
877 if status == 125:
878 transition = "skip"
878 transition = "skip"
879 elif status == 0:
879 elif status == 0:
880 transition = "good"
880 transition = "good"
881 # status < 0 means process was killed
881 # status < 0 means process was killed
882 elif status == 127:
882 elif status == 127:
883 raise error.Abort(_("failed to execute %s") % command)
883 raise error.Abort(_("failed to execute %s") % command)
884 elif status < 0:
884 elif status < 0:
885 raise error.Abort(_("%s killed") % command)
885 raise error.Abort(_("%s killed") % command)
886 else:
886 else:
887 transition = "bad"
887 transition = "bad"
888 state[transition].append(node)
888 state[transition].append(node)
889 ctx = repo[node]
889 ctx = repo[node]
890 ui.status(_('changeset %d:%s: %s\n') % (ctx.rev(), ctx,
890 ui.status(_('changeset %d:%s: %s\n') % (ctx.rev(), ctx,
891 transition))
891 transition))
892 hbisect.checkstate(state)
892 hbisect.checkstate(state)
893 # bisect
893 # bisect
894 nodes, changesets, bgood = hbisect.bisect(repo, state)
894 nodes, changesets, bgood = hbisect.bisect(repo, state)
895 # update to next check
895 # update to next check
896 node = nodes[0]
896 node = nodes[0]
897 mayupdate(repo, node, show_stats=False)
897 mayupdate(repo, node, show_stats=False)
898 finally:
898 finally:
899 state['current'] = [node]
899 state['current'] = [node]
900 hbisect.save_state(repo, state)
900 hbisect.save_state(repo, state)
901 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
901 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
902 return
902 return
903
903
904 hbisect.checkstate(state)
904 hbisect.checkstate(state)
905
905
906 # actually bisect
906 # actually bisect
907 nodes, changesets, good = hbisect.bisect(repo, state)
907 nodes, changesets, good = hbisect.bisect(repo, state)
908 if extend:
908 if extend:
909 if not changesets:
909 if not changesets:
910 extendnode = hbisect.extendrange(repo, state, nodes, good)
910 extendnode = hbisect.extendrange(repo, state, nodes, good)
911 if extendnode is not None:
911 if extendnode is not None:
912 ui.write(_("Extending search to changeset %d:%s\n")
912 ui.write(_("Extending search to changeset %d:%s\n")
913 % (extendnode.rev(), extendnode))
913 % (extendnode.rev(), extendnode))
914 state['current'] = [extendnode.node()]
914 state['current'] = [extendnode.node()]
915 hbisect.save_state(repo, state)
915 hbisect.save_state(repo, state)
916 return mayupdate(repo, extendnode.node())
916 return mayupdate(repo, extendnode.node())
917 raise error.Abort(_("nothing to extend"))
917 raise error.Abort(_("nothing to extend"))
918
918
919 if changesets == 0:
919 if changesets == 0:
920 hbisect.printresult(ui, repo, state, displayer, nodes, good)
920 hbisect.printresult(ui, repo, state, displayer, nodes, good)
921 else:
921 else:
922 assert len(nodes) == 1 # only a single node can be tested next
922 assert len(nodes) == 1 # only a single node can be tested next
923 node = nodes[0]
923 node = nodes[0]
924 # compute the approximate number of remaining tests
924 # compute the approximate number of remaining tests
925 tests, size = 0, 2
925 tests, size = 0, 2
926 while size <= changesets:
926 while size <= changesets:
927 tests, size = tests + 1, size * 2
927 tests, size = tests + 1, size * 2
928 rev = repo.changelog.rev(node)
928 rev = repo.changelog.rev(node)
929 ui.write(_("Testing changeset %d:%s "
929 ui.write(_("Testing changeset %d:%s "
930 "(%d changesets remaining, ~%d tests)\n")
930 "(%d changesets remaining, ~%d tests)\n")
931 % (rev, short(node), changesets, tests))
931 % (rev, short(node), changesets, tests))
932 state['current'] = [node]
932 state['current'] = [node]
933 hbisect.save_state(repo, state)
933 hbisect.save_state(repo, state)
934 return mayupdate(repo, node)
934 return mayupdate(repo, node)
935
935
936 @command('bookmarks|bookmark',
936 @command('bookmarks|bookmark',
937 [('f', 'force', False, _('force')),
937 [('f', 'force', False, _('force')),
938 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
938 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
939 ('d', 'delete', False, _('delete a given bookmark')),
939 ('d', 'delete', False, _('delete a given bookmark')),
940 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
940 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
941 ('i', 'inactive', False, _('mark a bookmark inactive')),
941 ('i', 'inactive', False, _('mark a bookmark inactive')),
942 ('l', 'list', False, _('list existing bookmarks')),
942 ('l', 'list', False, _('list existing bookmarks')),
943 ] + formatteropts,
943 ] + formatteropts,
944 _('hg bookmarks [OPTIONS]... [NAME]...'),
944 _('hg bookmarks [OPTIONS]... [NAME]...'),
945 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION)
945 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION)
946 def bookmark(ui, repo, *names, **opts):
946 def bookmark(ui, repo, *names, **opts):
947 '''create a new bookmark or list existing bookmarks
947 '''create a new bookmark or list existing bookmarks
948
948
949 Bookmarks are labels on changesets to help track lines of development.
949 Bookmarks are labels on changesets to help track lines of development.
950 Bookmarks are unversioned and can be moved, renamed and deleted.
950 Bookmarks are unversioned and can be moved, renamed and deleted.
951 Deleting or moving a bookmark has no effect on the associated changesets.
951 Deleting or moving a bookmark has no effect on the associated changesets.
952
952
953 Creating or updating to a bookmark causes it to be marked as 'active'.
953 Creating or updating to a bookmark causes it to be marked as 'active'.
954 The active bookmark is indicated with a '*'.
954 The active bookmark is indicated with a '*'.
955 When a commit is made, the active bookmark will advance to the new commit.
955 When a commit is made, the active bookmark will advance to the new commit.
956 A plain :hg:`update` will also advance an active bookmark, if possible.
956 A plain :hg:`update` will also advance an active bookmark, if possible.
957 Updating away from a bookmark will cause it to be deactivated.
957 Updating away from a bookmark will cause it to be deactivated.
958
958
959 Bookmarks can be pushed and pulled between repositories (see
959 Bookmarks can be pushed and pulled between repositories (see
960 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
960 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
961 diverged, a new 'divergent bookmark' of the form 'name@path' will
961 diverged, a new 'divergent bookmark' of the form 'name@path' will
962 be created. Using :hg:`merge` will resolve the divergence.
962 be created. Using :hg:`merge` will resolve the divergence.
963
963
964 Specifying bookmark as '.' to -m/-d/-l options is equivalent to specifying
964 Specifying bookmark as '.' to -m/-d/-l options is equivalent to specifying
965 the active bookmark's name.
965 the active bookmark's name.
966
966
967 A bookmark named '@' has the special property that :hg:`clone` will
967 A bookmark named '@' has the special property that :hg:`clone` will
968 check it out by default if it exists.
968 check it out by default if it exists.
969
969
970 .. container:: verbose
970 .. container:: verbose
971
971
972 Template:
972 Template:
973
973
974 The following keywords are supported in addition to the common template
974 The following keywords are supported in addition to the common template
975 keywords and functions such as ``{bookmark}``. See also
975 keywords and functions such as ``{bookmark}``. See also
976 :hg:`help templates`.
976 :hg:`help templates`.
977
977
978 :active: Boolean. True if the bookmark is active.
978 :active: Boolean. True if the bookmark is active.
979
979
980 Examples:
980 Examples:
981
981
982 - create an active bookmark for a new line of development::
982 - create an active bookmark for a new line of development::
983
983
984 hg book new-feature
984 hg book new-feature
985
985
986 - create an inactive bookmark as a place marker::
986 - create an inactive bookmark as a place marker::
987
987
988 hg book -i reviewed
988 hg book -i reviewed
989
989
990 - create an inactive bookmark on another changeset::
990 - create an inactive bookmark on another changeset::
991
991
992 hg book -r .^ tested
992 hg book -r .^ tested
993
993
994 - rename bookmark turkey to dinner::
994 - rename bookmark turkey to dinner::
995
995
996 hg book -m turkey dinner
996 hg book -m turkey dinner
997
997
998 - move the '@' bookmark from another branch::
998 - move the '@' bookmark from another branch::
999
999
1000 hg book -f @
1000 hg book -f @
1001
1001
1002 - print only the active bookmark name::
1002 - print only the active bookmark name::
1003
1003
1004 hg book -ql .
1004 hg book -ql .
1005 '''
1005 '''
1006 opts = pycompat.byteskwargs(opts)
1006 opts = pycompat.byteskwargs(opts)
1007 force = opts.get('force')
1007 force = opts.get('force')
1008 rev = opts.get('rev')
1008 rev = opts.get('rev')
1009 inactive = opts.get('inactive') # meaning add/rename to inactive bookmark
1009 inactive = opts.get('inactive') # meaning add/rename to inactive bookmark
1010
1010
1011 selactions = [k for k in ['delete', 'rename', 'list'] if opts.get(k)]
1011 selactions = [k for k in ['delete', 'rename', 'list'] if opts.get(k)]
1012 if len(selactions) > 1:
1012 if len(selactions) > 1:
1013 raise error.Abort(_('--%s and --%s are incompatible')
1013 raise error.Abort(_('--%s and --%s are incompatible')
1014 % tuple(selactions[:2]))
1014 % tuple(selactions[:2]))
1015 if selactions:
1015 if selactions:
1016 action = selactions[0]
1016 action = selactions[0]
1017 elif names or rev:
1017 elif names or rev:
1018 action = 'add'
1018 action = 'add'
1019 elif inactive:
1019 elif inactive:
1020 action = 'inactive' # meaning deactivate
1020 action = 'inactive' # meaning deactivate
1021 else:
1021 else:
1022 action = 'list'
1022 action = 'list'
1023
1023
1024 if rev and action in {'delete', 'rename', 'list'}:
1024 if rev and action in {'delete', 'rename', 'list'}:
1025 raise error.Abort(_("--rev is incompatible with --%s") % action)
1025 raise error.Abort(_("--rev is incompatible with --%s") % action)
1026 if inactive and action in {'delete', 'list'}:
1026 if inactive and action in {'delete', 'list'}:
1027 raise error.Abort(_("--inactive is incompatible with --%s") % action)
1027 raise error.Abort(_("--inactive is incompatible with --%s") % action)
1028 if not names and action in {'add', 'delete'}:
1028 if not names and action in {'add', 'delete'}:
1029 raise error.Abort(_("bookmark name required"))
1029 raise error.Abort(_("bookmark name required"))
1030
1030
1031 if action in {'add', 'delete', 'rename', 'inactive'}:
1031 if action in {'add', 'delete', 'rename', 'inactive'}:
1032 with repo.wlock(), repo.lock(), repo.transaction('bookmark') as tr:
1032 with repo.wlock(), repo.lock(), repo.transaction('bookmark') as tr:
1033 if action == 'delete':
1033 if action == 'delete':
1034 names = pycompat.maplist(repo._bookmarks.expandname, names)
1034 names = pycompat.maplist(repo._bookmarks.expandname, names)
1035 bookmarks.delete(repo, tr, names)
1035 bookmarks.delete(repo, tr, names)
1036 elif action == 'rename':
1036 elif action == 'rename':
1037 if not names:
1037 if not names:
1038 raise error.Abort(_("new bookmark name required"))
1038 raise error.Abort(_("new bookmark name required"))
1039 elif len(names) > 1:
1039 elif len(names) > 1:
1040 raise error.Abort(_("only one new bookmark name allowed"))
1040 raise error.Abort(_("only one new bookmark name allowed"))
1041 oldname = repo._bookmarks.expandname(opts['rename'])
1041 oldname = repo._bookmarks.expandname(opts['rename'])
1042 bookmarks.rename(repo, tr, oldname, names[0], force, inactive)
1042 bookmarks.rename(repo, tr, oldname, names[0], force, inactive)
1043 elif action == 'add':
1043 elif action == 'add':
1044 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
1044 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
1045 elif action == 'inactive':
1045 elif action == 'inactive':
1046 if len(repo._bookmarks) == 0:
1046 if len(repo._bookmarks) == 0:
1047 ui.status(_("no bookmarks set\n"))
1047 ui.status(_("no bookmarks set\n"))
1048 elif not repo._activebookmark:
1048 elif not repo._activebookmark:
1049 ui.status(_("no active bookmark\n"))
1049 ui.status(_("no active bookmark\n"))
1050 else:
1050 else:
1051 bookmarks.deactivate(repo)
1051 bookmarks.deactivate(repo)
1052 elif action == 'list':
1052 elif action == 'list':
1053 names = pycompat.maplist(repo._bookmarks.expandname, names)
1053 names = pycompat.maplist(repo._bookmarks.expandname, names)
1054 with ui.formatter('bookmarks', opts) as fm:
1054 with ui.formatter('bookmarks', opts) as fm:
1055 bookmarks.printbookmarks(ui, repo, fm, names)
1055 bookmarks.printbookmarks(ui, repo, fm, names)
1056 else:
1056 else:
1057 raise error.ProgrammingError('invalid action: %s' % action)
1057 raise error.ProgrammingError('invalid action: %s' % action)
1058
1058
1059 @command('branch',
1059 @command('branch',
1060 [('f', 'force', None,
1060 [('f', 'force', None,
1061 _('set branch name even if it shadows an existing branch')),
1061 _('set branch name even if it shadows an existing branch')),
1062 ('C', 'clean', None, _('reset branch name to parent branch name')),
1062 ('C', 'clean', None, _('reset branch name to parent branch name')),
1063 ('r', 'rev', [], _('change branches of the given revs (EXPERIMENTAL)')),
1063 ('r', 'rev', [], _('change branches of the given revs (EXPERIMENTAL)')),
1064 ],
1064 ],
1065 _('[-fC] [NAME]'),
1065 _('[-fC] [NAME]'),
1066 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION)
1066 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION)
1067 def branch(ui, repo, label=None, **opts):
1067 def branch(ui, repo, label=None, **opts):
1068 """set or show the current branch name
1068 """set or show the current branch name
1069
1069
1070 .. note::
1070 .. note::
1071
1071
1072 Branch names are permanent and global. Use :hg:`bookmark` to create a
1072 Branch names are permanent and global. Use :hg:`bookmark` to create a
1073 light-weight bookmark instead. See :hg:`help glossary` for more
1073 light-weight bookmark instead. See :hg:`help glossary` for more
1074 information about named branches and bookmarks.
1074 information about named branches and bookmarks.
1075
1075
1076 With no argument, show the current branch name. With one argument,
1076 With no argument, show the current branch name. With one argument,
1077 set the working directory branch name (the branch will not exist
1077 set the working directory branch name (the branch will not exist
1078 in the repository until the next commit). Standard practice
1078 in the repository until the next commit). Standard practice
1079 recommends that primary development take place on the 'default'
1079 recommends that primary development take place on the 'default'
1080 branch.
1080 branch.
1081
1081
1082 Unless -f/--force is specified, branch will not let you set a
1082 Unless -f/--force is specified, branch will not let you set a
1083 branch name that already exists.
1083 branch name that already exists.
1084
1084
1085 Use -C/--clean to reset the working directory branch to that of
1085 Use -C/--clean to reset the working directory branch to that of
1086 the parent of the working directory, negating a previous branch
1086 the parent of the working directory, negating a previous branch
1087 change.
1087 change.
1088
1088
1089 Use the command :hg:`update` to switch to an existing branch. Use
1089 Use the command :hg:`update` to switch to an existing branch. Use
1090 :hg:`commit --close-branch` to mark this branch head as closed.
1090 :hg:`commit --close-branch` to mark this branch head as closed.
1091 When all heads of a branch are closed, the branch will be
1091 When all heads of a branch are closed, the branch will be
1092 considered closed.
1092 considered closed.
1093
1093
1094 Returns 0 on success.
1094 Returns 0 on success.
1095 """
1095 """
1096 opts = pycompat.byteskwargs(opts)
1096 opts = pycompat.byteskwargs(opts)
1097 revs = opts.get('rev')
1097 revs = opts.get('rev')
1098 if label:
1098 if label:
1099 label = label.strip()
1099 label = label.strip()
1100
1100
1101 if not opts.get('clean') and not label:
1101 if not opts.get('clean') and not label:
1102 if revs:
1102 if revs:
1103 raise error.Abort(_("no branch name specified for the revisions"))
1103 raise error.Abort(_("no branch name specified for the revisions"))
1104 ui.write("%s\n" % repo.dirstate.branch())
1104 ui.write("%s\n" % repo.dirstate.branch())
1105 return
1105 return
1106
1106
1107 with repo.wlock():
1107 with repo.wlock():
1108 if opts.get('clean'):
1108 if opts.get('clean'):
1109 label = repo['.'].branch()
1109 label = repo['.'].branch()
1110 repo.dirstate.setbranch(label)
1110 repo.dirstate.setbranch(label)
1111 ui.status(_('reset working directory to branch %s\n') % label)
1111 ui.status(_('reset working directory to branch %s\n') % label)
1112 elif label:
1112 elif label:
1113
1113
1114 scmutil.checknewlabel(repo, label, 'branch')
1114 scmutil.checknewlabel(repo, label, 'branch')
1115 if revs:
1115 if revs:
1116 return cmdutil.changebranch(ui, repo, revs, label)
1116 return cmdutil.changebranch(ui, repo, revs, label)
1117
1117
1118 if not opts.get('force') and label in repo.branchmap():
1118 if not opts.get('force') and label in repo.branchmap():
1119 if label not in [p.branch() for p in repo[None].parents()]:
1119 if label not in [p.branch() for p in repo[None].parents()]:
1120 raise error.Abort(_('a branch of the same name already'
1120 raise error.Abort(_('a branch of the same name already'
1121 ' exists'),
1121 ' exists'),
1122 # i18n: "it" refers to an existing branch
1122 # i18n: "it" refers to an existing branch
1123 hint=_("use 'hg update' to switch to it"))
1123 hint=_("use 'hg update' to switch to it"))
1124
1124
1125 repo.dirstate.setbranch(label)
1125 repo.dirstate.setbranch(label)
1126 ui.status(_('marked working directory as branch %s\n') % label)
1126 ui.status(_('marked working directory as branch %s\n') % label)
1127
1127
1128 # find any open named branches aside from default
1128 # find any open named branches aside from default
1129 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1129 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1130 if n != "default" and not c]
1130 if n != "default" and not c]
1131 if not others:
1131 if not others:
1132 ui.status(_('(branches are permanent and global, '
1132 ui.status(_('(branches are permanent and global, '
1133 'did you want a bookmark?)\n'))
1133 'did you want a bookmark?)\n'))
1134
1134
1135 @command('branches',
1135 @command('branches',
1136 [('a', 'active', False,
1136 [('a', 'active', False,
1137 _('show only branches that have unmerged heads (DEPRECATED)')),
1137 _('show only branches that have unmerged heads (DEPRECATED)')),
1138 ('c', 'closed', False, _('show normal and closed branches')),
1138 ('c', 'closed', False, _('show normal and closed branches')),
1139 ('r', 'rev', [], _('show branch name(s) of the given rev'))
1139 ('r', 'rev', [], _('show branch name(s) of the given rev'))
1140 ] + formatteropts,
1140 ] + formatteropts,
1141 _('[-c]'),
1141 _('[-c]'),
1142 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1142 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1143 intents={INTENT_READONLY})
1143 intents={INTENT_READONLY})
1144 def branches(ui, repo, active=False, closed=False, **opts):
1144 def branches(ui, repo, active=False, closed=False, **opts):
1145 """list repository named branches
1145 """list repository named branches
1146
1146
1147 List the repository's named branches, indicating which ones are
1147 List the repository's named branches, indicating which ones are
1148 inactive. If -c/--closed is specified, also list branches which have
1148 inactive. If -c/--closed is specified, also list branches which have
1149 been marked closed (see :hg:`commit --close-branch`).
1149 been marked closed (see :hg:`commit --close-branch`).
1150
1150
1151 Use the command :hg:`update` to switch to an existing branch.
1151 Use the command :hg:`update` to switch to an existing branch.
1152
1152
1153 .. container:: verbose
1153 .. container:: verbose
1154
1154
1155 Template:
1155 Template:
1156
1156
1157 The following keywords are supported in addition to the common template
1157 The following keywords are supported in addition to the common template
1158 keywords and functions such as ``{branch}``. See also
1158 keywords and functions such as ``{branch}``. See also
1159 :hg:`help templates`.
1159 :hg:`help templates`.
1160
1160
1161 :active: Boolean. True if the branch is active.
1161 :active: Boolean. True if the branch is active.
1162 :closed: Boolean. True if the branch is closed.
1162 :closed: Boolean. True if the branch is closed.
1163 :current: Boolean. True if it is the current branch.
1163 :current: Boolean. True if it is the current branch.
1164
1164
1165 Returns 0.
1165 Returns 0.
1166 """
1166 """
1167
1167
1168 opts = pycompat.byteskwargs(opts)
1168 opts = pycompat.byteskwargs(opts)
1169 revs = opts.get('rev')
1169 revs = opts.get('rev')
1170 selectedbranches = None
1170 selectedbranches = None
1171 if revs:
1171 if revs:
1172 revs = scmutil.revrange(repo, revs)
1172 revs = scmutil.revrange(repo, revs)
1173 getbi = repo.revbranchcache().branchinfo
1173 getbi = repo.revbranchcache().branchinfo
1174 selectedbranches = {getbi(r)[0] for r in revs}
1174 selectedbranches = {getbi(r)[0] for r in revs}
1175
1175
1176 ui.pager('branches')
1176 ui.pager('branches')
1177 fm = ui.formatter('branches', opts)
1177 fm = ui.formatter('branches', opts)
1178 hexfunc = fm.hexfunc
1178 hexfunc = fm.hexfunc
1179
1179
1180 allheads = set(repo.heads())
1180 allheads = set(repo.heads())
1181 branches = []
1181 branches = []
1182 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1182 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1183 if selectedbranches is not None and tag not in selectedbranches:
1183 if selectedbranches is not None and tag not in selectedbranches:
1184 continue
1184 continue
1185 isactive = False
1185 isactive = False
1186 if not isclosed:
1186 if not isclosed:
1187 openheads = set(repo.branchmap().iteropen(heads))
1187 openheads = set(repo.branchmap().iteropen(heads))
1188 isactive = bool(openheads & allheads)
1188 isactive = bool(openheads & allheads)
1189 branches.append((tag, repo[tip], isactive, not isclosed))
1189 branches.append((tag, repo[tip], isactive, not isclosed))
1190 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1190 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1191 reverse=True)
1191 reverse=True)
1192
1192
1193 for tag, ctx, isactive, isopen in branches:
1193 for tag, ctx, isactive, isopen in branches:
1194 if active and not isactive:
1194 if active and not isactive:
1195 continue
1195 continue
1196 if isactive:
1196 if isactive:
1197 label = 'branches.active'
1197 label = 'branches.active'
1198 notice = ''
1198 notice = ''
1199 elif not isopen:
1199 elif not isopen:
1200 if not closed:
1200 if not closed:
1201 continue
1201 continue
1202 label = 'branches.closed'
1202 label = 'branches.closed'
1203 notice = _(' (closed)')
1203 notice = _(' (closed)')
1204 else:
1204 else:
1205 label = 'branches.inactive'
1205 label = 'branches.inactive'
1206 notice = _(' (inactive)')
1206 notice = _(' (inactive)')
1207 current = (tag == repo.dirstate.branch())
1207 current = (tag == repo.dirstate.branch())
1208 if current:
1208 if current:
1209 label = 'branches.current'
1209 label = 'branches.current'
1210
1210
1211 fm.startitem()
1211 fm.startitem()
1212 fm.write('branch', '%s', tag, label=label)
1212 fm.write('branch', '%s', tag, label=label)
1213 rev = ctx.rev()
1213 rev = ctx.rev()
1214 padsize = max(31 - len("%d" % rev) - encoding.colwidth(tag), 0)
1214 padsize = max(31 - len("%d" % rev) - encoding.colwidth(tag), 0)
1215 fmt = ' ' * padsize + ' %d:%s'
1215 fmt = ' ' * padsize + ' %d:%s'
1216 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1216 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1217 label='log.changeset changeset.%s' % ctx.phasestr())
1217 label='log.changeset changeset.%s' % ctx.phasestr())
1218 fm.context(ctx=ctx)
1218 fm.context(ctx=ctx)
1219 fm.data(active=isactive, closed=not isopen, current=current)
1219 fm.data(active=isactive, closed=not isopen, current=current)
1220 if not ui.quiet:
1220 if not ui.quiet:
1221 fm.plain(notice)
1221 fm.plain(notice)
1222 fm.plain('\n')
1222 fm.plain('\n')
1223 fm.end()
1223 fm.end()
1224
1224
1225 @command('bundle',
1225 @command('bundle',
1226 [('f', 'force', None, _('run even when the destination is unrelated')),
1226 [('f', 'force', None, _('run even when the destination is unrelated')),
1227 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1227 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1228 _('REV')),
1228 _('REV')),
1229 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1229 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1230 _('BRANCH')),
1230 _('BRANCH')),
1231 ('', 'base', [],
1231 ('', 'base', [],
1232 _('a base changeset assumed to be available at the destination'),
1232 _('a base changeset assumed to be available at the destination'),
1233 _('REV')),
1233 _('REV')),
1234 ('a', 'all', None, _('bundle all changesets in the repository')),
1234 ('a', 'all', None, _('bundle all changesets in the repository')),
1235 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1235 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1236 ] + remoteopts,
1236 ] + remoteopts,
1237 _('[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'),
1237 _('[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'),
1238 helpcategory=command.CATEGORY_IMPORT_EXPORT)
1238 helpcategory=command.CATEGORY_IMPORT_EXPORT)
1239 def bundle(ui, repo, fname, dest=None, **opts):
1239 def bundle(ui, repo, fname, dest=None, **opts):
1240 """create a bundle file
1240 """create a bundle file
1241
1241
1242 Generate a bundle file containing data to be transferred to another
1242 Generate a bundle file containing data to be transferred to another
1243 repository.
1243 repository.
1244
1244
1245 To create a bundle containing all changesets, use -a/--all
1245 To create a bundle containing all changesets, use -a/--all
1246 (or --base null). Otherwise, hg assumes the destination will have
1246 (or --base null). Otherwise, hg assumes the destination will have
1247 all the nodes you specify with --base parameters. Otherwise, hg
1247 all the nodes you specify with --base parameters. Otherwise, hg
1248 will assume the repository has all the nodes in destination, or
1248 will assume the repository has all the nodes in destination, or
1249 default-push/default if no destination is specified, where destination
1249 default-push/default if no destination is specified, where destination
1250 is the repository you provide through DEST option.
1250 is the repository you provide through DEST option.
1251
1251
1252 You can change bundle format with the -t/--type option. See
1252 You can change bundle format with the -t/--type option. See
1253 :hg:`help bundlespec` for documentation on this format. By default,
1253 :hg:`help bundlespec` for documentation on this format. By default,
1254 the most appropriate format is used and compression defaults to
1254 the most appropriate format is used and compression defaults to
1255 bzip2.
1255 bzip2.
1256
1256
1257 The bundle file can then be transferred using conventional means
1257 The bundle file can then be transferred using conventional means
1258 and applied to another repository with the unbundle or pull
1258 and applied to another repository with the unbundle or pull
1259 command. This is useful when direct push and pull are not
1259 command. This is useful when direct push and pull are not
1260 available or when exporting an entire repository is undesirable.
1260 available or when exporting an entire repository is undesirable.
1261
1261
1262 Applying bundles preserves all changeset contents including
1262 Applying bundles preserves all changeset contents including
1263 permissions, copy/rename information, and revision history.
1263 permissions, copy/rename information, and revision history.
1264
1264
1265 Returns 0 on success, 1 if no changes found.
1265 Returns 0 on success, 1 if no changes found.
1266 """
1266 """
1267 opts = pycompat.byteskwargs(opts)
1267 opts = pycompat.byteskwargs(opts)
1268 revs = None
1268 revs = None
1269 if 'rev' in opts:
1269 if 'rev' in opts:
1270 revstrings = opts['rev']
1270 revstrings = opts['rev']
1271 revs = scmutil.revrange(repo, revstrings)
1271 revs = scmutil.revrange(repo, revstrings)
1272 if revstrings and not revs:
1272 if revstrings and not revs:
1273 raise error.Abort(_('no commits to bundle'))
1273 raise error.Abort(_('no commits to bundle'))
1274
1274
1275 bundletype = opts.get('type', 'bzip2').lower()
1275 bundletype = opts.get('type', 'bzip2').lower()
1276 try:
1276 try:
1277 bundlespec = exchange.parsebundlespec(repo, bundletype, strict=False)
1277 bundlespec = exchange.parsebundlespec(repo, bundletype, strict=False)
1278 except error.UnsupportedBundleSpecification as e:
1278 except error.UnsupportedBundleSpecification as e:
1279 raise error.Abort(pycompat.bytestr(e),
1279 raise error.Abort(pycompat.bytestr(e),
1280 hint=_("see 'hg help bundlespec' for supported "
1280 hint=_("see 'hg help bundlespec' for supported "
1281 "values for --type"))
1281 "values for --type"))
1282 cgversion = bundlespec.contentopts["cg.version"]
1282 cgversion = bundlespec.contentopts["cg.version"]
1283
1283
1284 # Packed bundles are a pseudo bundle format for now.
1284 # Packed bundles are a pseudo bundle format for now.
1285 if cgversion == 's1':
1285 if cgversion == 's1':
1286 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1286 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1287 hint=_("use 'hg debugcreatestreamclonebundle'"))
1287 hint=_("use 'hg debugcreatestreamclonebundle'"))
1288
1288
1289 if opts.get('all'):
1289 if opts.get('all'):
1290 if dest:
1290 if dest:
1291 raise error.Abort(_("--all is incompatible with specifying "
1291 raise error.Abort(_("--all is incompatible with specifying "
1292 "a destination"))
1292 "a destination"))
1293 if opts.get('base'):
1293 if opts.get('base'):
1294 ui.warn(_("ignoring --base because --all was specified\n"))
1294 ui.warn(_("ignoring --base because --all was specified\n"))
1295 base = [nullrev]
1295 base = [nullrev]
1296 else:
1296 else:
1297 base = scmutil.revrange(repo, opts.get('base'))
1297 base = scmutil.revrange(repo, opts.get('base'))
1298 if cgversion not in changegroup.supportedoutgoingversions(repo):
1298 if cgversion not in changegroup.supportedoutgoingversions(repo):
1299 raise error.Abort(_("repository does not support bundle version %s") %
1299 raise error.Abort(_("repository does not support bundle version %s") %
1300 cgversion)
1300 cgversion)
1301
1301
1302 if base:
1302 if base:
1303 if dest:
1303 if dest:
1304 raise error.Abort(_("--base is incompatible with specifying "
1304 raise error.Abort(_("--base is incompatible with specifying "
1305 "a destination"))
1305 "a destination"))
1306 common = [repo[rev].node() for rev in base]
1306 common = [repo[rev].node() for rev in base]
1307 heads = [repo[r].node() for r in revs] if revs else None
1307 heads = [repo[r].node() for r in revs] if revs else None
1308 outgoing = discovery.outgoing(repo, common, heads)
1308 outgoing = discovery.outgoing(repo, common, heads)
1309 else:
1309 else:
1310 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1310 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1311 dest, branches = hg.parseurl(dest, opts.get('branch'))
1311 dest, branches = hg.parseurl(dest, opts.get('branch'))
1312 other = hg.peer(repo, opts, dest)
1312 other = hg.peer(repo, opts, dest)
1313 revs = [repo[r].hex() for r in revs]
1313 revs = [repo[r].hex() for r in revs]
1314 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1314 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1315 heads = revs and pycompat.maplist(repo.lookup, revs) or revs
1315 heads = revs and pycompat.maplist(repo.lookup, revs) or revs
1316 outgoing = discovery.findcommonoutgoing(repo, other,
1316 outgoing = discovery.findcommonoutgoing(repo, other,
1317 onlyheads=heads,
1317 onlyheads=heads,
1318 force=opts.get('force'),
1318 force=opts.get('force'),
1319 portable=True)
1319 portable=True)
1320
1320
1321 if not outgoing.missing:
1321 if not outgoing.missing:
1322 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1322 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1323 return 1
1323 return 1
1324
1324
1325 if cgversion == '01': #bundle1
1325 if cgversion == '01': #bundle1
1326 bversion = 'HG10' + bundlespec.wirecompression
1326 bversion = 'HG10' + bundlespec.wirecompression
1327 bcompression = None
1327 bcompression = None
1328 elif cgversion in ('02', '03'):
1328 elif cgversion in ('02', '03'):
1329 bversion = 'HG20'
1329 bversion = 'HG20'
1330 bcompression = bundlespec.wirecompression
1330 bcompression = bundlespec.wirecompression
1331 else:
1331 else:
1332 raise error.ProgrammingError(
1332 raise error.ProgrammingError(
1333 'bundle: unexpected changegroup version %s' % cgversion)
1333 'bundle: unexpected changegroup version %s' % cgversion)
1334
1334
1335 # TODO compression options should be derived from bundlespec parsing.
1335 # TODO compression options should be derived from bundlespec parsing.
1336 # This is a temporary hack to allow adjusting bundle compression
1336 # This is a temporary hack to allow adjusting bundle compression
1337 # level without a) formalizing the bundlespec changes to declare it
1337 # level without a) formalizing the bundlespec changes to declare it
1338 # b) introducing a command flag.
1338 # b) introducing a command flag.
1339 compopts = {}
1339 compopts = {}
1340 complevel = ui.configint('experimental',
1340 complevel = ui.configint('experimental',
1341 'bundlecomplevel.' + bundlespec.compression)
1341 'bundlecomplevel.' + bundlespec.compression)
1342 if complevel is None:
1342 if complevel is None:
1343 complevel = ui.configint('experimental', 'bundlecomplevel')
1343 complevel = ui.configint('experimental', 'bundlecomplevel')
1344 if complevel is not None:
1344 if complevel is not None:
1345 compopts['level'] = complevel
1345 compopts['level'] = complevel
1346
1346
1347 # Allow overriding the bundling of obsmarker in phases through
1347 # Allow overriding the bundling of obsmarker in phases through
1348 # configuration while we don't have a bundle version that include them
1348 # configuration while we don't have a bundle version that include them
1349 if repo.ui.configbool('experimental', 'evolution.bundle-obsmarker'):
1349 if repo.ui.configbool('experimental', 'evolution.bundle-obsmarker'):
1350 bundlespec.contentopts['obsolescence'] = True
1350 bundlespec.contentopts['obsolescence'] = True
1351 if repo.ui.configbool('experimental', 'bundle-phases'):
1351 if repo.ui.configbool('experimental', 'bundle-phases'):
1352 bundlespec.contentopts['phases'] = True
1352 bundlespec.contentopts['phases'] = True
1353
1353
1354 bundle2.writenewbundle(ui, repo, 'bundle', fname, bversion, outgoing,
1354 bundle2.writenewbundle(ui, repo, 'bundle', fname, bversion, outgoing,
1355 bundlespec.contentopts, compression=bcompression,
1355 bundlespec.contentopts, compression=bcompression,
1356 compopts=compopts)
1356 compopts=compopts)
1357
1357
1358 @command('cat',
1358 @command('cat',
1359 [('o', 'output', '',
1359 [('o', 'output', '',
1360 _('print output to file with formatted name'), _('FORMAT')),
1360 _('print output to file with formatted name'), _('FORMAT')),
1361 ('r', 'rev', '', _('print the given revision'), _('REV')),
1361 ('r', 'rev', '', _('print the given revision'), _('REV')),
1362 ('', 'decode', None, _('apply any matching decode filter')),
1362 ('', 'decode', None, _('apply any matching decode filter')),
1363 ] + walkopts + formatteropts,
1363 ] + walkopts + formatteropts,
1364 _('[OPTION]... FILE...'),
1364 _('[OPTION]... FILE...'),
1365 helpcategory=command.CATEGORY_FILE_CONTENTS,
1365 helpcategory=command.CATEGORY_FILE_CONTENTS,
1366 inferrepo=True,
1366 inferrepo=True,
1367 intents={INTENT_READONLY})
1367 intents={INTENT_READONLY})
1368 def cat(ui, repo, file1, *pats, **opts):
1368 def cat(ui, repo, file1, *pats, **opts):
1369 """output the current or given revision of files
1369 """output the current or given revision of files
1370
1370
1371 Print the specified files as they were at the given revision. If
1371 Print the specified files as they were at the given revision. If
1372 no revision is given, the parent of the working directory is used.
1372 no revision is given, the parent of the working directory is used.
1373
1373
1374 Output may be to a file, in which case the name of the file is
1374 Output may be to a file, in which case the name of the file is
1375 given using a template string. See :hg:`help templates`. In addition
1375 given using a template string. See :hg:`help templates`. In addition
1376 to the common template keywords, the following formatting rules are
1376 to the common template keywords, the following formatting rules are
1377 supported:
1377 supported:
1378
1378
1379 :``%%``: literal "%" character
1379 :``%%``: literal "%" character
1380 :``%s``: basename of file being printed
1380 :``%s``: basename of file being printed
1381 :``%d``: dirname of file being printed, or '.' if in repository root
1381 :``%d``: dirname of file being printed, or '.' if in repository root
1382 :``%p``: root-relative path name of file being printed
1382 :``%p``: root-relative path name of file being printed
1383 :``%H``: changeset hash (40 hexadecimal digits)
1383 :``%H``: changeset hash (40 hexadecimal digits)
1384 :``%R``: changeset revision number
1384 :``%R``: changeset revision number
1385 :``%h``: short-form changeset hash (12 hexadecimal digits)
1385 :``%h``: short-form changeset hash (12 hexadecimal digits)
1386 :``%r``: zero-padded changeset revision number
1386 :``%r``: zero-padded changeset revision number
1387 :``%b``: basename of the exporting repository
1387 :``%b``: basename of the exporting repository
1388 :``\\``: literal "\\" character
1388 :``\\``: literal "\\" character
1389
1389
1390 .. container:: verbose
1390 .. container:: verbose
1391
1391
1392 Template:
1392 Template:
1393
1393
1394 The following keywords are supported in addition to the common template
1394 The following keywords are supported in addition to the common template
1395 keywords and functions. See also :hg:`help templates`.
1395 keywords and functions. See also :hg:`help templates`.
1396
1396
1397 :data: String. File content.
1397 :data: String. File content.
1398 :path: String. Repository-absolute path of the file.
1398 :path: String. Repository-absolute path of the file.
1399
1399
1400 Returns 0 on success.
1400 Returns 0 on success.
1401 """
1401 """
1402 opts = pycompat.byteskwargs(opts)
1402 opts = pycompat.byteskwargs(opts)
1403 rev = opts.get('rev')
1403 rev = opts.get('rev')
1404 if rev:
1404 if rev:
1405 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
1405 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
1406 ctx = scmutil.revsingle(repo, rev)
1406 ctx = scmutil.revsingle(repo, rev)
1407 m = scmutil.match(ctx, (file1,) + pats, opts)
1407 m = scmutil.match(ctx, (file1,) + pats, opts)
1408 fntemplate = opts.pop('output', '')
1408 fntemplate = opts.pop('output', '')
1409 if cmdutil.isstdiofilename(fntemplate):
1409 if cmdutil.isstdiofilename(fntemplate):
1410 fntemplate = ''
1410 fntemplate = ''
1411
1411
1412 if fntemplate:
1412 if fntemplate:
1413 fm = formatter.nullformatter(ui, 'cat', opts)
1413 fm = formatter.nullformatter(ui, 'cat', opts)
1414 else:
1414 else:
1415 ui.pager('cat')
1415 ui.pager('cat')
1416 fm = ui.formatter('cat', opts)
1416 fm = ui.formatter('cat', opts)
1417 with fm:
1417 with fm:
1418 return cmdutil.cat(ui, repo, ctx, m, fm, fntemplate, '',
1418 return cmdutil.cat(ui, repo, ctx, m, fm, fntemplate, '',
1419 **pycompat.strkwargs(opts))
1419 **pycompat.strkwargs(opts))
1420
1420
1421 @command('clone',
1421 @command('clone',
1422 [('U', 'noupdate', None, _('the clone will include an empty working '
1422 [('U', 'noupdate', None, _('the clone will include an empty working '
1423 'directory (only a repository)')),
1423 'directory (only a repository)')),
1424 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1424 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1425 _('REV')),
1425 _('REV')),
1426 ('r', 'rev', [], _('do not clone everything, but include this changeset'
1426 ('r', 'rev', [], _('do not clone everything, but include this changeset'
1427 ' and its ancestors'), _('REV')),
1427 ' and its ancestors'), _('REV')),
1428 ('b', 'branch', [], _('do not clone everything, but include this branch\'s'
1428 ('b', 'branch', [], _('do not clone everything, but include this branch\'s'
1429 ' changesets and their ancestors'), _('BRANCH')),
1429 ' changesets and their ancestors'), _('BRANCH')),
1430 ('', 'pull', None, _('use pull protocol to copy metadata')),
1430 ('', 'pull', None, _('use pull protocol to copy metadata')),
1431 ('', 'uncompressed', None,
1431 ('', 'uncompressed', None,
1432 _('an alias to --stream (DEPRECATED)')),
1432 _('an alias to --stream (DEPRECATED)')),
1433 ('', 'stream', None,
1433 ('', 'stream', None,
1434 _('clone with minimal data processing')),
1434 _('clone with minimal data processing')),
1435 ] + remoteopts,
1435 ] + remoteopts,
1436 _('[OPTION]... SOURCE [DEST]'),
1436 _('[OPTION]... SOURCE [DEST]'),
1437 helpcategory=command.CATEGORY_REPO_CREATION,
1437 helpcategory=command.CATEGORY_REPO_CREATION,
1438 helpbasic=True, norepo=True)
1438 helpbasic=True, norepo=True)
1439 def clone(ui, source, dest=None, **opts):
1439 def clone(ui, source, dest=None, **opts):
1440 """make a copy of an existing repository
1440 """make a copy of an existing repository
1441
1441
1442 Create a copy of an existing repository in a new directory.
1442 Create a copy of an existing repository in a new directory.
1443
1443
1444 If no destination directory name is specified, it defaults to the
1444 If no destination directory name is specified, it defaults to the
1445 basename of the source.
1445 basename of the source.
1446
1446
1447 The location of the source is added to the new repository's
1447 The location of the source is added to the new repository's
1448 ``.hg/hgrc`` file, as the default to be used for future pulls.
1448 ``.hg/hgrc`` file, as the default to be used for future pulls.
1449
1449
1450 Only local paths and ``ssh://`` URLs are supported as
1450 Only local paths and ``ssh://`` URLs are supported as
1451 destinations. For ``ssh://`` destinations, no working directory or
1451 destinations. For ``ssh://`` destinations, no working directory or
1452 ``.hg/hgrc`` will be created on the remote side.
1452 ``.hg/hgrc`` will be created on the remote side.
1453
1453
1454 If the source repository has a bookmark called '@' set, that
1454 If the source repository has a bookmark called '@' set, that
1455 revision will be checked out in the new repository by default.
1455 revision will be checked out in the new repository by default.
1456
1456
1457 To check out a particular version, use -u/--update, or
1457 To check out a particular version, use -u/--update, or
1458 -U/--noupdate to create a clone with no working directory.
1458 -U/--noupdate to create a clone with no working directory.
1459
1459
1460 To pull only a subset of changesets, specify one or more revisions
1460 To pull only a subset of changesets, specify one or more revisions
1461 identifiers with -r/--rev or branches with -b/--branch. The
1461 identifiers with -r/--rev or branches with -b/--branch. The
1462 resulting clone will contain only the specified changesets and
1462 resulting clone will contain only the specified changesets and
1463 their ancestors. These options (or 'clone src#rev dest') imply
1463 their ancestors. These options (or 'clone src#rev dest') imply
1464 --pull, even for local source repositories.
1464 --pull, even for local source repositories.
1465
1465
1466 In normal clone mode, the remote normalizes repository data into a common
1466 In normal clone mode, the remote normalizes repository data into a common
1467 exchange format and the receiving end translates this data into its local
1467 exchange format and the receiving end translates this data into its local
1468 storage format. --stream activates a different clone mode that essentially
1468 storage format. --stream activates a different clone mode that essentially
1469 copies repository files from the remote with minimal data processing. This
1469 copies repository files from the remote with minimal data processing. This
1470 significantly reduces the CPU cost of a clone both remotely and locally.
1470 significantly reduces the CPU cost of a clone both remotely and locally.
1471 However, it often increases the transferred data size by 30-40%. This can
1471 However, it often increases the transferred data size by 30-40%. This can
1472 result in substantially faster clones where I/O throughput is plentiful,
1472 result in substantially faster clones where I/O throughput is plentiful,
1473 especially for larger repositories. A side-effect of --stream clones is
1473 especially for larger repositories. A side-effect of --stream clones is
1474 that storage settings and requirements on the remote are applied locally:
1474 that storage settings and requirements on the remote are applied locally:
1475 a modern client may inherit legacy or inefficient storage used by the
1475 a modern client may inherit legacy or inefficient storage used by the
1476 remote or a legacy Mercurial client may not be able to clone from a
1476 remote or a legacy Mercurial client may not be able to clone from a
1477 modern Mercurial remote.
1477 modern Mercurial remote.
1478
1478
1479 .. note::
1479 .. note::
1480
1480
1481 Specifying a tag will include the tagged changeset but not the
1481 Specifying a tag will include the tagged changeset but not the
1482 changeset containing the tag.
1482 changeset containing the tag.
1483
1483
1484 .. container:: verbose
1484 .. container:: verbose
1485
1485
1486 For efficiency, hardlinks are used for cloning whenever the
1486 For efficiency, hardlinks are used for cloning whenever the
1487 source and destination are on the same filesystem (note this
1487 source and destination are on the same filesystem (note this
1488 applies only to the repository data, not to the working
1488 applies only to the repository data, not to the working
1489 directory). Some filesystems, such as AFS, implement hardlinking
1489 directory). Some filesystems, such as AFS, implement hardlinking
1490 incorrectly, but do not report errors. In these cases, use the
1490 incorrectly, but do not report errors. In these cases, use the
1491 --pull option to avoid hardlinking.
1491 --pull option to avoid hardlinking.
1492
1492
1493 Mercurial will update the working directory to the first applicable
1493 Mercurial will update the working directory to the first applicable
1494 revision from this list:
1494 revision from this list:
1495
1495
1496 a) null if -U or the source repository has no changesets
1496 a) null if -U or the source repository has no changesets
1497 b) if -u . and the source repository is local, the first parent of
1497 b) if -u . and the source repository is local, the first parent of
1498 the source repository's working directory
1498 the source repository's working directory
1499 c) the changeset specified with -u (if a branch name, this means the
1499 c) the changeset specified with -u (if a branch name, this means the
1500 latest head of that branch)
1500 latest head of that branch)
1501 d) the changeset specified with -r
1501 d) the changeset specified with -r
1502 e) the tipmost head specified with -b
1502 e) the tipmost head specified with -b
1503 f) the tipmost head specified with the url#branch source syntax
1503 f) the tipmost head specified with the url#branch source syntax
1504 g) the revision marked with the '@' bookmark, if present
1504 g) the revision marked with the '@' bookmark, if present
1505 h) the tipmost head of the default branch
1505 h) the tipmost head of the default branch
1506 i) tip
1506 i) tip
1507
1507
1508 When cloning from servers that support it, Mercurial may fetch
1508 When cloning from servers that support it, Mercurial may fetch
1509 pre-generated data from a server-advertised URL or inline from the
1509 pre-generated data from a server-advertised URL or inline from the
1510 same stream. When this is done, hooks operating on incoming changesets
1510 same stream. When this is done, hooks operating on incoming changesets
1511 and changegroups may fire more than once, once for each pre-generated
1511 and changegroups may fire more than once, once for each pre-generated
1512 bundle and as well as for any additional remaining data. In addition,
1512 bundle and as well as for any additional remaining data. In addition,
1513 if an error occurs, the repository may be rolled back to a partial
1513 if an error occurs, the repository may be rolled back to a partial
1514 clone. This behavior may change in future releases.
1514 clone. This behavior may change in future releases.
1515 See :hg:`help -e clonebundles` for more.
1515 See :hg:`help -e clonebundles` for more.
1516
1516
1517 Examples:
1517 Examples:
1518
1518
1519 - clone a remote repository to a new directory named hg/::
1519 - clone a remote repository to a new directory named hg/::
1520
1520
1521 hg clone https://www.mercurial-scm.org/repo/hg/
1521 hg clone https://www.mercurial-scm.org/repo/hg/
1522
1522
1523 - create a lightweight local clone::
1523 - create a lightweight local clone::
1524
1524
1525 hg clone project/ project-feature/
1525 hg clone project/ project-feature/
1526
1526
1527 - clone from an absolute path on an ssh server (note double-slash)::
1527 - clone from an absolute path on an ssh server (note double-slash)::
1528
1528
1529 hg clone ssh://user@server//home/projects/alpha/
1529 hg clone ssh://user@server//home/projects/alpha/
1530
1530
1531 - do a streaming clone while checking out a specified version::
1531 - do a streaming clone while checking out a specified version::
1532
1532
1533 hg clone --stream http://server/repo -u 1.5
1533 hg clone --stream http://server/repo -u 1.5
1534
1534
1535 - create a repository without changesets after a particular revision::
1535 - create a repository without changesets after a particular revision::
1536
1536
1537 hg clone -r 04e544 experimental/ good/
1537 hg clone -r 04e544 experimental/ good/
1538
1538
1539 - clone (and track) a particular named branch::
1539 - clone (and track) a particular named branch::
1540
1540
1541 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1541 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1542
1542
1543 See :hg:`help urls` for details on specifying URLs.
1543 See :hg:`help urls` for details on specifying URLs.
1544
1544
1545 Returns 0 on success.
1545 Returns 0 on success.
1546 """
1546 """
1547 opts = pycompat.byteskwargs(opts)
1547 opts = pycompat.byteskwargs(opts)
1548 if opts.get('noupdate') and opts.get('updaterev'):
1548 if opts.get('noupdate') and opts.get('updaterev'):
1549 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1549 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1550
1550
1551 # --include/--exclude can come from narrow or sparse.
1551 # --include/--exclude can come from narrow or sparse.
1552 includepats, excludepats = None, None
1552 includepats, excludepats = None, None
1553
1553
1554 # hg.clone() differentiates between None and an empty set. So make sure
1554 # hg.clone() differentiates between None and an empty set. So make sure
1555 # patterns are sets if narrow is requested without patterns.
1555 # patterns are sets if narrow is requested without patterns.
1556 if opts.get('narrow'):
1556 if opts.get('narrow'):
1557 includepats = set()
1557 includepats = set()
1558 excludepats = set()
1558 excludepats = set()
1559
1559
1560 if opts.get('include'):
1560 if opts.get('include'):
1561 includepats = narrowspec.parsepatterns(opts.get('include'))
1561 includepats = narrowspec.parsepatterns(opts.get('include'))
1562 if opts.get('exclude'):
1562 if opts.get('exclude'):
1563 excludepats = narrowspec.parsepatterns(opts.get('exclude'))
1563 excludepats = narrowspec.parsepatterns(opts.get('exclude'))
1564
1564
1565 r = hg.clone(ui, opts, source, dest,
1565 r = hg.clone(ui, opts, source, dest,
1566 pull=opts.get('pull'),
1566 pull=opts.get('pull'),
1567 stream=opts.get('stream') or opts.get('uncompressed'),
1567 stream=opts.get('stream') or opts.get('uncompressed'),
1568 revs=opts.get('rev'),
1568 revs=opts.get('rev'),
1569 update=opts.get('updaterev') or not opts.get('noupdate'),
1569 update=opts.get('updaterev') or not opts.get('noupdate'),
1570 branch=opts.get('branch'),
1570 branch=opts.get('branch'),
1571 shareopts=opts.get('shareopts'),
1571 shareopts=opts.get('shareopts'),
1572 storeincludepats=includepats,
1572 storeincludepats=includepats,
1573 storeexcludepats=excludepats,
1573 storeexcludepats=excludepats,
1574 depth=opts.get('depth') or None)
1574 depth=opts.get('depth') or None)
1575
1575
1576 return r is None
1576 return r is None
1577
1577
1578 @command('commit|ci',
1578 @command('commit|ci',
1579 [('A', 'addremove', None,
1579 [('A', 'addremove', None,
1580 _('mark new/missing files as added/removed before committing')),
1580 _('mark new/missing files as added/removed before committing')),
1581 ('', 'close-branch', None,
1581 ('', 'close-branch', None,
1582 _('mark a branch head as closed')),
1582 _('mark a branch head as closed')),
1583 ('', 'amend', None, _('amend the parent of the working directory')),
1583 ('', 'amend', None, _('amend the parent of the working directory')),
1584 ('s', 'secret', None, _('use the secret phase for committing')),
1584 ('s', 'secret', None, _('use the secret phase for committing')),
1585 ('e', 'edit', None, _('invoke editor on commit messages')),
1585 ('e', 'edit', None, _('invoke editor on commit messages')),
1586 ('i', 'interactive', None, _('use interactive mode')),
1586 ('i', 'interactive', None, _('use interactive mode')),
1587 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1587 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1588 _('[OPTION]... [FILE]...'),
1588 _('[OPTION]... [FILE]...'),
1589 helpcategory=command.CATEGORY_COMMITTING, helpbasic=True,
1589 helpcategory=command.CATEGORY_COMMITTING, helpbasic=True,
1590 inferrepo=True)
1590 inferrepo=True)
1591 def commit(ui, repo, *pats, **opts):
1591 def commit(ui, repo, *pats, **opts):
1592 """commit the specified files or all outstanding changes
1592 """commit the specified files or all outstanding changes
1593
1593
1594 Commit changes to the given files into the repository. Unlike a
1594 Commit changes to the given files into the repository. Unlike a
1595 centralized SCM, this operation is a local operation. See
1595 centralized SCM, this operation is a local operation. See
1596 :hg:`push` for a way to actively distribute your changes.
1596 :hg:`push` for a way to actively distribute your changes.
1597
1597
1598 If a list of files is omitted, all changes reported by :hg:`status`
1598 If a list of files is omitted, all changes reported by :hg:`status`
1599 will be committed.
1599 will be committed.
1600
1600
1601 If you are committing the result of a merge, do not provide any
1601 If you are committing the result of a merge, do not provide any
1602 filenames or -I/-X filters.
1602 filenames or -I/-X filters.
1603
1603
1604 If no commit message is specified, Mercurial starts your
1604 If no commit message is specified, Mercurial starts your
1605 configured editor where you can enter a message. In case your
1605 configured editor where you can enter a message. In case your
1606 commit fails, you will find a backup of your message in
1606 commit fails, you will find a backup of your message in
1607 ``.hg/last-message.txt``.
1607 ``.hg/last-message.txt``.
1608
1608
1609 The --close-branch flag can be used to mark the current branch
1609 The --close-branch flag can be used to mark the current branch
1610 head closed. When all heads of a branch are closed, the branch
1610 head closed. When all heads of a branch are closed, the branch
1611 will be considered closed and no longer listed.
1611 will be considered closed and no longer listed.
1612
1612
1613 The --amend flag can be used to amend the parent of the
1613 The --amend flag can be used to amend the parent of the
1614 working directory with a new commit that contains the changes
1614 working directory with a new commit that contains the changes
1615 in the parent in addition to those currently reported by :hg:`status`,
1615 in the parent in addition to those currently reported by :hg:`status`,
1616 if there are any. The old commit is stored in a backup bundle in
1616 if there are any. The old commit is stored in a backup bundle in
1617 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1617 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1618 on how to restore it).
1618 on how to restore it).
1619
1619
1620 Message, user and date are taken from the amended commit unless
1620 Message, user and date are taken from the amended commit unless
1621 specified. When a message isn't specified on the command line,
1621 specified. When a message isn't specified on the command line,
1622 the editor will open with the message of the amended commit.
1622 the editor will open with the message of the amended commit.
1623
1623
1624 It is not possible to amend public changesets (see :hg:`help phases`)
1624 It is not possible to amend public changesets (see :hg:`help phases`)
1625 or changesets that have children.
1625 or changesets that have children.
1626
1626
1627 See :hg:`help dates` for a list of formats valid for -d/--date.
1627 See :hg:`help dates` for a list of formats valid for -d/--date.
1628
1628
1629 Returns 0 on success, 1 if nothing changed.
1629 Returns 0 on success, 1 if nothing changed.
1630
1630
1631 .. container:: verbose
1631 .. container:: verbose
1632
1632
1633 Examples:
1633 Examples:
1634
1634
1635 - commit all files ending in .py::
1635 - commit all files ending in .py::
1636
1636
1637 hg commit --include "set:**.py"
1637 hg commit --include "set:**.py"
1638
1638
1639 - commit all non-binary files::
1639 - commit all non-binary files::
1640
1640
1641 hg commit --exclude "set:binary()"
1641 hg commit --exclude "set:binary()"
1642
1642
1643 - amend the current commit and set the date to now::
1643 - amend the current commit and set the date to now::
1644
1644
1645 hg commit --amend --date now
1645 hg commit --amend --date now
1646 """
1646 """
1647 with repo.wlock(), repo.lock():
1647 with repo.wlock(), repo.lock():
1648 return _docommit(ui, repo, *pats, **opts)
1648 return _docommit(ui, repo, *pats, **opts)
1649
1649
1650 def _docommit(ui, repo, *pats, **opts):
1650 def _docommit(ui, repo, *pats, **opts):
1651 if opts.get(r'interactive'):
1651 if opts.get(r'interactive'):
1652 opts.pop(r'interactive')
1652 opts.pop(r'interactive')
1653 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1653 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1654 cmdutil.recordfilter, *pats,
1654 cmdutil.recordfilter, *pats,
1655 **opts)
1655 **opts)
1656 # ret can be 0 (no changes to record) or the value returned by
1656 # ret can be 0 (no changes to record) or the value returned by
1657 # commit(), 1 if nothing changed or None on success.
1657 # commit(), 1 if nothing changed or None on success.
1658 return 1 if ret == 0 else ret
1658 return 1 if ret == 0 else ret
1659
1659
1660 opts = pycompat.byteskwargs(opts)
1660 opts = pycompat.byteskwargs(opts)
1661 if opts.get('subrepos'):
1661 if opts.get('subrepos'):
1662 if opts.get('amend'):
1662 if opts.get('amend'):
1663 raise error.Abort(_('cannot amend with --subrepos'))
1663 raise error.Abort(_('cannot amend with --subrepos'))
1664 # Let --subrepos on the command line override config setting.
1664 # Let --subrepos on the command line override config setting.
1665 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1665 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1666
1666
1667 cmdutil.checkunfinished(repo, commit=True)
1667 cmdutil.checkunfinished(repo, commit=True)
1668
1668
1669 branch = repo[None].branch()
1669 branch = repo[None].branch()
1670 bheads = repo.branchheads(branch)
1670 bheads = repo.branchheads(branch)
1671
1671
1672 extra = {}
1672 extra = {}
1673 if opts.get('close_branch'):
1673 if opts.get('close_branch'):
1674 extra['close'] = '1'
1674 extra['close'] = '1'
1675
1675
1676 if not bheads:
1676 if not bheads:
1677 raise error.Abort(_('can only close branch heads'))
1677 raise error.Abort(_('can only close branch heads'))
1678 elif opts.get('amend'):
1678 elif opts.get('amend'):
1679 if repo['.'].p1().branch() != branch and \
1679 if repo['.'].p1().branch() != branch and \
1680 repo['.'].p2().branch() != branch:
1680 repo['.'].p2().branch() != branch:
1681 raise error.Abort(_('can only close branch heads'))
1681 raise error.Abort(_('can only close branch heads'))
1682
1682
1683 if opts.get('amend'):
1683 if opts.get('amend'):
1684 if ui.configbool('ui', 'commitsubrepos'):
1684 if ui.configbool('ui', 'commitsubrepos'):
1685 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1685 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1686
1686
1687 old = repo['.']
1687 old = repo['.']
1688 rewriteutil.precheck(repo, [old.rev()], 'amend')
1688 rewriteutil.precheck(repo, [old.rev()], 'amend')
1689
1689
1690 # Currently histedit gets confused if an amend happens while histedit
1690 # Currently histedit gets confused if an amend happens while histedit
1691 # is in progress. Since we have a checkunfinished command, we are
1691 # is in progress. Since we have a checkunfinished command, we are
1692 # temporarily honoring it.
1692 # temporarily honoring it.
1693 #
1693 #
1694 # Note: eventually this guard will be removed. Please do not expect
1694 # Note: eventually this guard will be removed. Please do not expect
1695 # this behavior to remain.
1695 # this behavior to remain.
1696 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1696 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1697 cmdutil.checkunfinished(repo)
1697 cmdutil.checkunfinished(repo)
1698
1698
1699 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
1699 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
1700 if node == old.node():
1700 if node == old.node():
1701 ui.status(_("nothing changed\n"))
1701 ui.status(_("nothing changed\n"))
1702 return 1
1702 return 1
1703 else:
1703 else:
1704 def commitfunc(ui, repo, message, match, opts):
1704 def commitfunc(ui, repo, message, match, opts):
1705 overrides = {}
1705 overrides = {}
1706 if opts.get('secret'):
1706 if opts.get('secret'):
1707 overrides[('phases', 'new-commit')] = 'secret'
1707 overrides[('phases', 'new-commit')] = 'secret'
1708
1708
1709 baseui = repo.baseui
1709 baseui = repo.baseui
1710 with baseui.configoverride(overrides, 'commit'):
1710 with baseui.configoverride(overrides, 'commit'):
1711 with ui.configoverride(overrides, 'commit'):
1711 with ui.configoverride(overrides, 'commit'):
1712 editform = cmdutil.mergeeditform(repo[None],
1712 editform = cmdutil.mergeeditform(repo[None],
1713 'commit.normal')
1713 'commit.normal')
1714 editor = cmdutil.getcommiteditor(
1714 editor = cmdutil.getcommiteditor(
1715 editform=editform, **pycompat.strkwargs(opts))
1715 editform=editform, **pycompat.strkwargs(opts))
1716 return repo.commit(message,
1716 return repo.commit(message,
1717 opts.get('user'),
1717 opts.get('user'),
1718 opts.get('date'),
1718 opts.get('date'),
1719 match,
1719 match,
1720 editor=editor,
1720 editor=editor,
1721 extra=extra)
1721 extra=extra)
1722
1722
1723 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1723 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1724
1724
1725 if not node:
1725 if not node:
1726 stat = cmdutil.postcommitstatus(repo, pats, opts)
1726 stat = cmdutil.postcommitstatus(repo, pats, opts)
1727 if stat[3]:
1727 if stat[3]:
1728 ui.status(_("nothing changed (%d missing files, see "
1728 ui.status(_("nothing changed (%d missing files, see "
1729 "'hg status')\n") % len(stat[3]))
1729 "'hg status')\n") % len(stat[3]))
1730 else:
1730 else:
1731 ui.status(_("nothing changed\n"))
1731 ui.status(_("nothing changed\n"))
1732 return 1
1732 return 1
1733
1733
1734 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1734 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1735
1735
1736 @command('config|showconfig|debugconfig',
1736 @command('config|showconfig|debugconfig',
1737 [('u', 'untrusted', None, _('show untrusted configuration options')),
1737 [('u', 'untrusted', None, _('show untrusted configuration options')),
1738 ('e', 'edit', None, _('edit user config')),
1738 ('e', 'edit', None, _('edit user config')),
1739 ('l', 'local', None, _('edit repository config')),
1739 ('l', 'local', None, _('edit repository config')),
1740 ('g', 'global', None, _('edit global config'))] + formatteropts,
1740 ('g', 'global', None, _('edit global config'))] + formatteropts,
1741 _('[-u] [NAME]...'),
1741 _('[-u] [NAME]...'),
1742 helpcategory=command.CATEGORY_HELP,
1742 helpcategory=command.CATEGORY_HELP,
1743 optionalrepo=True,
1743 optionalrepo=True,
1744 intents={INTENT_READONLY})
1744 intents={INTENT_READONLY})
1745 def config(ui, repo, *values, **opts):
1745 def config(ui, repo, *values, **opts):
1746 """show combined config settings from all hgrc files
1746 """show combined config settings from all hgrc files
1747
1747
1748 With no arguments, print names and values of all config items.
1748 With no arguments, print names and values of all config items.
1749
1749
1750 With one argument of the form section.name, print just the value
1750 With one argument of the form section.name, print just the value
1751 of that config item.
1751 of that config item.
1752
1752
1753 With multiple arguments, print names and values of all config
1753 With multiple arguments, print names and values of all config
1754 items with matching section names or section.names.
1754 items with matching section names or section.names.
1755
1755
1756 With --edit, start an editor on the user-level config file. With
1756 With --edit, start an editor on the user-level config file. With
1757 --global, edit the system-wide config file. With --local, edit the
1757 --global, edit the system-wide config file. With --local, edit the
1758 repository-level config file.
1758 repository-level config file.
1759
1759
1760 With --debug, the source (filename and line number) is printed
1760 With --debug, the source (filename and line number) is printed
1761 for each config item.
1761 for each config item.
1762
1762
1763 See :hg:`help config` for more information about config files.
1763 See :hg:`help config` for more information about config files.
1764
1764
1765 .. container:: verbose
1765 .. container:: verbose
1766
1766
1767 Template:
1767 Template:
1768
1768
1769 The following keywords are supported. See also :hg:`help templates`.
1769 The following keywords are supported. See also :hg:`help templates`.
1770
1770
1771 :name: String. Config name.
1771 :name: String. Config name.
1772 :source: String. Filename and line number where the item is defined.
1772 :source: String. Filename and line number where the item is defined.
1773 :value: String. Config value.
1773 :value: String. Config value.
1774
1774
1775 Returns 0 on success, 1 if NAME does not exist.
1775 Returns 0 on success, 1 if NAME does not exist.
1776
1776
1777 """
1777 """
1778
1778
1779 opts = pycompat.byteskwargs(opts)
1779 opts = pycompat.byteskwargs(opts)
1780 if opts.get('edit') or opts.get('local') or opts.get('global'):
1780 if opts.get('edit') or opts.get('local') or opts.get('global'):
1781 if opts.get('local') and opts.get('global'):
1781 if opts.get('local') and opts.get('global'):
1782 raise error.Abort(_("can't use --local and --global together"))
1782 raise error.Abort(_("can't use --local and --global together"))
1783
1783
1784 if opts.get('local'):
1784 if opts.get('local'):
1785 if not repo:
1785 if not repo:
1786 raise error.Abort(_("can't use --local outside a repository"))
1786 raise error.Abort(_("can't use --local outside a repository"))
1787 paths = [repo.vfs.join('hgrc')]
1787 paths = [repo.vfs.join('hgrc')]
1788 elif opts.get('global'):
1788 elif opts.get('global'):
1789 paths = rcutil.systemrcpath()
1789 paths = rcutil.systemrcpath()
1790 else:
1790 else:
1791 paths = rcutil.userrcpath()
1791 paths = rcutil.userrcpath()
1792
1792
1793 for f in paths:
1793 for f in paths:
1794 if os.path.exists(f):
1794 if os.path.exists(f):
1795 break
1795 break
1796 else:
1796 else:
1797 if opts.get('global'):
1797 if opts.get('global'):
1798 samplehgrc = uimod.samplehgrcs['global']
1798 samplehgrc = uimod.samplehgrcs['global']
1799 elif opts.get('local'):
1799 elif opts.get('local'):
1800 samplehgrc = uimod.samplehgrcs['local']
1800 samplehgrc = uimod.samplehgrcs['local']
1801 else:
1801 else:
1802 samplehgrc = uimod.samplehgrcs['user']
1802 samplehgrc = uimod.samplehgrcs['user']
1803
1803
1804 f = paths[0]
1804 f = paths[0]
1805 fp = open(f, "wb")
1805 fp = open(f, "wb")
1806 fp.write(util.tonativeeol(samplehgrc))
1806 fp.write(util.tonativeeol(samplehgrc))
1807 fp.close()
1807 fp.close()
1808
1808
1809 editor = ui.geteditor()
1809 editor = ui.geteditor()
1810 ui.system("%s \"%s\"" % (editor, f),
1810 ui.system("%s \"%s\"" % (editor, f),
1811 onerr=error.Abort, errprefix=_("edit failed"),
1811 onerr=error.Abort, errprefix=_("edit failed"),
1812 blockedtag='config_edit')
1812 blockedtag='config_edit')
1813 return
1813 return
1814 ui.pager('config')
1814 ui.pager('config')
1815 fm = ui.formatter('config', opts)
1815 fm = ui.formatter('config', opts)
1816 for t, f in rcutil.rccomponents():
1816 for t, f in rcutil.rccomponents():
1817 if t == 'path':
1817 if t == 'path':
1818 ui.debug('read config from: %s\n' % f)
1818 ui.debug('read config from: %s\n' % f)
1819 elif t == 'items':
1819 elif t == 'items':
1820 for section, name, value, source in f:
1820 for section, name, value, source in f:
1821 ui.debug('set config by: %s\n' % source)
1821 ui.debug('set config by: %s\n' % source)
1822 else:
1822 else:
1823 raise error.ProgrammingError('unknown rctype: %s' % t)
1823 raise error.ProgrammingError('unknown rctype: %s' % t)
1824 untrusted = bool(opts.get('untrusted'))
1824 untrusted = bool(opts.get('untrusted'))
1825
1825
1826 selsections = selentries = []
1826 selsections = selentries = []
1827 if values:
1827 if values:
1828 selsections = [v for v in values if '.' not in v]
1828 selsections = [v for v in values if '.' not in v]
1829 selentries = [v for v in values if '.' in v]
1829 selentries = [v for v in values if '.' in v]
1830 uniquesel = (len(selentries) == 1 and not selsections)
1830 uniquesel = (len(selentries) == 1 and not selsections)
1831 selsections = set(selsections)
1831 selsections = set(selsections)
1832 selentries = set(selentries)
1832 selentries = set(selentries)
1833
1833
1834 matched = False
1834 matched = False
1835 for section, name, value in ui.walkconfig(untrusted=untrusted):
1835 for section, name, value in ui.walkconfig(untrusted=untrusted):
1836 source = ui.configsource(section, name, untrusted)
1836 source = ui.configsource(section, name, untrusted)
1837 value = pycompat.bytestr(value)
1837 value = pycompat.bytestr(value)
1838 if fm.isplain():
1838 if fm.isplain():
1839 source = source or 'none'
1839 source = source or 'none'
1840 value = value.replace('\n', '\\n')
1840 value = value.replace('\n', '\\n')
1841 entryname = section + '.' + name
1841 entryname = section + '.' + name
1842 if values and not (section in selsections or entryname in selentries):
1842 if values and not (section in selsections or entryname in selentries):
1843 continue
1843 continue
1844 fm.startitem()
1844 fm.startitem()
1845 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1845 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1846 if uniquesel:
1846 if uniquesel:
1847 fm.data(name=entryname)
1847 fm.data(name=entryname)
1848 fm.write('value', '%s\n', value)
1848 fm.write('value', '%s\n', value)
1849 else:
1849 else:
1850 fm.write('name value', '%s=%s\n', entryname, value)
1850 fm.write('name value', '%s=%s\n', entryname, value)
1851 matched = True
1851 matched = True
1852 fm.end()
1852 fm.end()
1853 if matched:
1853 if matched:
1854 return 0
1854 return 0
1855 return 1
1855 return 1
1856
1856
1857 @command('copy|cp',
1857 @command('copy|cp',
1858 [('A', 'after', None, _('record a copy that has already occurred')),
1858 [('A', 'after', None, _('record a copy that has already occurred')),
1859 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1859 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1860 ] + walkopts + dryrunopts,
1860 ] + walkopts + dryrunopts,
1861 _('[OPTION]... [SOURCE]... DEST'),
1861 _('[OPTION]... [SOURCE]... DEST'),
1862 helpcategory=command.CATEGORY_FILE_CONTENTS)
1862 helpcategory=command.CATEGORY_FILE_CONTENTS)
1863 def copy(ui, repo, *pats, **opts):
1863 def copy(ui, repo, *pats, **opts):
1864 """mark files as copied for the next commit
1864 """mark files as copied for the next commit
1865
1865
1866 Mark dest as having copies of source files. If dest is a
1866 Mark dest as having copies of source files. If dest is a
1867 directory, copies are put in that directory. If dest is a file,
1867 directory, copies are put in that directory. If dest is a file,
1868 the source must be a single file.
1868 the source must be a single file.
1869
1869
1870 By default, this command copies the contents of files as they
1870 By default, this command copies the contents of files as they
1871 exist in the working directory. If invoked with -A/--after, the
1871 exist in the working directory. If invoked with -A/--after, the
1872 operation is recorded, but no copying is performed.
1872 operation is recorded, but no copying is performed.
1873
1873
1874 This command takes effect with the next commit. To undo a copy
1874 This command takes effect with the next commit. To undo a copy
1875 before that, see :hg:`revert`.
1875 before that, see :hg:`revert`.
1876
1876
1877 Returns 0 on success, 1 if errors are encountered.
1877 Returns 0 on success, 1 if errors are encountered.
1878 """
1878 """
1879 opts = pycompat.byteskwargs(opts)
1879 opts = pycompat.byteskwargs(opts)
1880 with repo.wlock(False):
1880 with repo.wlock(False):
1881 return cmdutil.copy(ui, repo, pats, opts)
1881 return cmdutil.copy(ui, repo, pats, opts)
1882
1882
1883 @command(
1883 @command(
1884 'debugcommands', [], _('[COMMAND]'),
1884 'debugcommands', [], _('[COMMAND]'),
1885 helpcategory=command.CATEGORY_HELP,
1885 helpcategory=command.CATEGORY_HELP,
1886 norepo=True)
1886 norepo=True)
1887 def debugcommands(ui, cmd='', *args):
1887 def debugcommands(ui, cmd='', *args):
1888 """list all available commands and options"""
1888 """list all available commands and options"""
1889 for cmd, vals in sorted(table.iteritems()):
1889 for cmd, vals in sorted(table.iteritems()):
1890 cmd = cmd.split('|')[0]
1890 cmd = cmd.split('|')[0]
1891 opts = ', '.join([i[1] for i in vals[1]])
1891 opts = ', '.join([i[1] for i in vals[1]])
1892 ui.write('%s: %s\n' % (cmd, opts))
1892 ui.write('%s: %s\n' % (cmd, opts))
1893
1893
1894 @command('debugcomplete',
1894 @command('debugcomplete',
1895 [('o', 'options', None, _('show the command options'))],
1895 [('o', 'options', None, _('show the command options'))],
1896 _('[-o] CMD'),
1896 _('[-o] CMD'),
1897 helpcategory=command.CATEGORY_HELP,
1897 helpcategory=command.CATEGORY_HELP,
1898 norepo=True)
1898 norepo=True)
1899 def debugcomplete(ui, cmd='', **opts):
1899 def debugcomplete(ui, cmd='', **opts):
1900 """returns the completion list associated with the given command"""
1900 """returns the completion list associated with the given command"""
1901
1901
1902 if opts.get(r'options'):
1902 if opts.get(r'options'):
1903 options = []
1903 options = []
1904 otables = [globalopts]
1904 otables = [globalopts]
1905 if cmd:
1905 if cmd:
1906 aliases, entry = cmdutil.findcmd(cmd, table, False)
1906 aliases, entry = cmdutil.findcmd(cmd, table, False)
1907 otables.append(entry[1])
1907 otables.append(entry[1])
1908 for t in otables:
1908 for t in otables:
1909 for o in t:
1909 for o in t:
1910 if "(DEPRECATED)" in o[3]:
1910 if "(DEPRECATED)" in o[3]:
1911 continue
1911 continue
1912 if o[0]:
1912 if o[0]:
1913 options.append('-%s' % o[0])
1913 options.append('-%s' % o[0])
1914 options.append('--%s' % o[1])
1914 options.append('--%s' % o[1])
1915 ui.write("%s\n" % "\n".join(options))
1915 ui.write("%s\n" % "\n".join(options))
1916 return
1916 return
1917
1917
1918 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
1918 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
1919 if ui.verbose:
1919 if ui.verbose:
1920 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1920 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1921 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1921 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1922
1922
1923 @command('diff',
1923 @command('diff',
1924 [('r', 'rev', [], _('revision'), _('REV')),
1924 [('r', 'rev', [], _('revision'), _('REV')),
1925 ('c', 'change', '', _('change made by revision'), _('REV'))
1925 ('c', 'change', '', _('change made by revision'), _('REV'))
1926 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1926 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1927 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1927 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1928 helpcategory=command.CATEGORY_FILE_CONTENTS,
1928 helpcategory=command.CATEGORY_FILE_CONTENTS,
1929 helpbasic=True, inferrepo=True, intents={INTENT_READONLY})
1929 helpbasic=True, inferrepo=True, intents={INTENT_READONLY})
1930 def diff(ui, repo, *pats, **opts):
1930 def diff(ui, repo, *pats, **opts):
1931 """diff repository (or selected files)
1931 """diff repository (or selected files)
1932
1932
1933 Show differences between revisions for the specified files.
1933 Show differences between revisions for the specified files.
1934
1934
1935 Differences between files are shown using the unified diff format.
1935 Differences between files are shown using the unified diff format.
1936
1936
1937 .. note::
1937 .. note::
1938
1938
1939 :hg:`diff` may generate unexpected results for merges, as it will
1939 :hg:`diff` may generate unexpected results for merges, as it will
1940 default to comparing against the working directory's first
1940 default to comparing against the working directory's first
1941 parent changeset if no revisions are specified.
1941 parent changeset if no revisions are specified.
1942
1942
1943 When two revision arguments are given, then changes are shown
1943 When two revision arguments are given, then changes are shown
1944 between those revisions. If only one revision is specified then
1944 between those revisions. If only one revision is specified then
1945 that revision is compared to the working directory, and, when no
1945 that revision is compared to the working directory, and, when no
1946 revisions are specified, the working directory files are compared
1946 revisions are specified, the working directory files are compared
1947 to its first parent.
1947 to its first parent.
1948
1948
1949 Alternatively you can specify -c/--change with a revision to see
1949 Alternatively you can specify -c/--change with a revision to see
1950 the changes in that changeset relative to its first parent.
1950 the changes in that changeset relative to its first parent.
1951
1951
1952 Without the -a/--text option, diff will avoid generating diffs of
1952 Without the -a/--text option, diff will avoid generating diffs of
1953 files it detects as binary. With -a, diff will generate a diff
1953 files it detects as binary. With -a, diff will generate a diff
1954 anyway, probably with undesirable results.
1954 anyway, probably with undesirable results.
1955
1955
1956 Use the -g/--git option to generate diffs in the git extended diff
1956 Use the -g/--git option to generate diffs in the git extended diff
1957 format. For more information, read :hg:`help diffs`.
1957 format. For more information, read :hg:`help diffs`.
1958
1958
1959 .. container:: verbose
1959 .. container:: verbose
1960
1960
1961 Examples:
1961 Examples:
1962
1962
1963 - compare a file in the current working directory to its parent::
1963 - compare a file in the current working directory to its parent::
1964
1964
1965 hg diff foo.c
1965 hg diff foo.c
1966
1966
1967 - compare two historical versions of a directory, with rename info::
1967 - compare two historical versions of a directory, with rename info::
1968
1968
1969 hg diff --git -r 1.0:1.2 lib/
1969 hg diff --git -r 1.0:1.2 lib/
1970
1970
1971 - get change stats relative to the last change on some date::
1971 - get change stats relative to the last change on some date::
1972
1972
1973 hg diff --stat -r "date('may 2')"
1973 hg diff --stat -r "date('may 2')"
1974
1974
1975 - diff all newly-added files that contain a keyword::
1975 - diff all newly-added files that contain a keyword::
1976
1976
1977 hg diff "set:added() and grep(GNU)"
1977 hg diff "set:added() and grep(GNU)"
1978
1978
1979 - compare a revision and its parents::
1979 - compare a revision and its parents::
1980
1980
1981 hg diff -c 9353 # compare against first parent
1981 hg diff -c 9353 # compare against first parent
1982 hg diff -r 9353^:9353 # same using revset syntax
1982 hg diff -r 9353^:9353 # same using revset syntax
1983 hg diff -r 9353^2:9353 # compare against the second parent
1983 hg diff -r 9353^2:9353 # compare against the second parent
1984
1984
1985 Returns 0 on success.
1985 Returns 0 on success.
1986 """
1986 """
1987
1987
1988 opts = pycompat.byteskwargs(opts)
1988 opts = pycompat.byteskwargs(opts)
1989 revs = opts.get('rev')
1989 revs = opts.get('rev')
1990 change = opts.get('change')
1990 change = opts.get('change')
1991 stat = opts.get('stat')
1991 stat = opts.get('stat')
1992 reverse = opts.get('reverse')
1992 reverse = opts.get('reverse')
1993
1993
1994 if revs and change:
1994 if revs and change:
1995 msg = _('cannot specify --rev and --change at the same time')
1995 msg = _('cannot specify --rev and --change at the same time')
1996 raise error.Abort(msg)
1996 raise error.Abort(msg)
1997 elif change:
1997 elif change:
1998 repo = scmutil.unhidehashlikerevs(repo, [change], 'nowarn')
1998 repo = scmutil.unhidehashlikerevs(repo, [change], 'nowarn')
1999 ctx2 = scmutil.revsingle(repo, change, None)
1999 ctx2 = scmutil.revsingle(repo, change, None)
2000 ctx1 = ctx2.p1()
2000 ctx1 = ctx2.p1()
2001 else:
2001 else:
2002 repo = scmutil.unhidehashlikerevs(repo, revs, 'nowarn')
2002 repo = scmutil.unhidehashlikerevs(repo, revs, 'nowarn')
2003 ctx1, ctx2 = scmutil.revpair(repo, revs)
2003 ctx1, ctx2 = scmutil.revpair(repo, revs)
2004 node1, node2 = ctx1.node(), ctx2.node()
2004 node1, node2 = ctx1.node(), ctx2.node()
2005
2005
2006 if reverse:
2006 if reverse:
2007 node1, node2 = node2, node1
2007 node1, node2 = node2, node1
2008
2008
2009 diffopts = patch.diffallopts(ui, opts)
2009 diffopts = patch.diffallopts(ui, opts)
2010 m = scmutil.match(ctx2, pats, opts)
2010 m = scmutil.match(ctx2, pats, opts)
2011 m = repo.narrowmatch(m)
2011 m = repo.narrowmatch(m)
2012 ui.pager('diff')
2012 ui.pager('diff')
2013 logcmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2013 logcmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2014 listsubrepos=opts.get('subrepos'),
2014 listsubrepos=opts.get('subrepos'),
2015 root=opts.get('root'))
2015 root=opts.get('root'))
2016
2016
2017 @command('export',
2017 @command('export',
2018 [('B', 'bookmark', '',
2018 [('B', 'bookmark', '',
2019 _('export changes only reachable by given bookmark'), _('BOOKMARK')),
2019 _('export changes only reachable by given bookmark'), _('BOOKMARK')),
2020 ('o', 'output', '',
2020 ('o', 'output', '',
2021 _('print output to file with formatted name'), _('FORMAT')),
2021 _('print output to file with formatted name'), _('FORMAT')),
2022 ('', 'switch-parent', None, _('diff against the second parent')),
2022 ('', 'switch-parent', None, _('diff against the second parent')),
2023 ('r', 'rev', [], _('revisions to export'), _('REV')),
2023 ('r', 'rev', [], _('revisions to export'), _('REV')),
2024 ] + diffopts + formatteropts,
2024 ] + diffopts + formatteropts,
2025 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'),
2025 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'),
2026 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2026 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2027 helpbasic=True, intents={INTENT_READONLY})
2027 helpbasic=True, intents={INTENT_READONLY})
2028 def export(ui, repo, *changesets, **opts):
2028 def export(ui, repo, *changesets, **opts):
2029 """dump the header and diffs for one or more changesets
2029 """dump the header and diffs for one or more changesets
2030
2030
2031 Print the changeset header and diffs for one or more revisions.
2031 Print the changeset header and diffs for one or more revisions.
2032 If no revision is given, the parent of the working directory is used.
2032 If no revision is given, the parent of the working directory is used.
2033
2033
2034 The information shown in the changeset header is: author, date,
2034 The information shown in the changeset header is: author, date,
2035 branch name (if non-default), changeset hash, parent(s) and commit
2035 branch name (if non-default), changeset hash, parent(s) and commit
2036 comment.
2036 comment.
2037
2037
2038 .. note::
2038 .. note::
2039
2039
2040 :hg:`export` may generate unexpected diff output for merge
2040 :hg:`export` may generate unexpected diff output for merge
2041 changesets, as it will compare the merge changeset against its
2041 changesets, as it will compare the merge changeset against its
2042 first parent only.
2042 first parent only.
2043
2043
2044 Output may be to a file, in which case the name of the file is
2044 Output may be to a file, in which case the name of the file is
2045 given using a template string. See :hg:`help templates`. In addition
2045 given using a template string. See :hg:`help templates`. In addition
2046 to the common template keywords, the following formatting rules are
2046 to the common template keywords, the following formatting rules are
2047 supported:
2047 supported:
2048
2048
2049 :``%%``: literal "%" character
2049 :``%%``: literal "%" character
2050 :``%H``: changeset hash (40 hexadecimal digits)
2050 :``%H``: changeset hash (40 hexadecimal digits)
2051 :``%N``: number of patches being generated
2051 :``%N``: number of patches being generated
2052 :``%R``: changeset revision number
2052 :``%R``: changeset revision number
2053 :``%b``: basename of the exporting repository
2053 :``%b``: basename of the exporting repository
2054 :``%h``: short-form changeset hash (12 hexadecimal digits)
2054 :``%h``: short-form changeset hash (12 hexadecimal digits)
2055 :``%m``: first line of the commit message (only alphanumeric characters)
2055 :``%m``: first line of the commit message (only alphanumeric characters)
2056 :``%n``: zero-padded sequence number, starting at 1
2056 :``%n``: zero-padded sequence number, starting at 1
2057 :``%r``: zero-padded changeset revision number
2057 :``%r``: zero-padded changeset revision number
2058 :``\\``: literal "\\" character
2058 :``\\``: literal "\\" character
2059
2059
2060 Without the -a/--text option, export will avoid generating diffs
2060 Without the -a/--text option, export will avoid generating diffs
2061 of files it detects as binary. With -a, export will generate a
2061 of files it detects as binary. With -a, export will generate a
2062 diff anyway, probably with undesirable results.
2062 diff anyway, probably with undesirable results.
2063
2063
2064 With -B/--bookmark changesets reachable by the given bookmark are
2064 With -B/--bookmark changesets reachable by the given bookmark are
2065 selected.
2065 selected.
2066
2066
2067 Use the -g/--git option to generate diffs in the git extended diff
2067 Use the -g/--git option to generate diffs in the git extended diff
2068 format. See :hg:`help diffs` for more information.
2068 format. See :hg:`help diffs` for more information.
2069
2069
2070 With the --switch-parent option, the diff will be against the
2070 With the --switch-parent option, the diff will be against the
2071 second parent. It can be useful to review a merge.
2071 second parent. It can be useful to review a merge.
2072
2072
2073 .. container:: verbose
2073 .. container:: verbose
2074
2074
2075 Template:
2075 Template:
2076
2076
2077 The following keywords are supported in addition to the common template
2077 The following keywords are supported in addition to the common template
2078 keywords and functions. See also :hg:`help templates`.
2078 keywords and functions. See also :hg:`help templates`.
2079
2079
2080 :diff: String. Diff content.
2080 :diff: String. Diff content.
2081 :parents: List of strings. Parent nodes of the changeset.
2081 :parents: List of strings. Parent nodes of the changeset.
2082
2082
2083 Examples:
2083 Examples:
2084
2084
2085 - use export and import to transplant a bugfix to the current
2085 - use export and import to transplant a bugfix to the current
2086 branch::
2086 branch::
2087
2087
2088 hg export -r 9353 | hg import -
2088 hg export -r 9353 | hg import -
2089
2089
2090 - export all the changesets between two revisions to a file with
2090 - export all the changesets between two revisions to a file with
2091 rename information::
2091 rename information::
2092
2092
2093 hg export --git -r 123:150 > changes.txt
2093 hg export --git -r 123:150 > changes.txt
2094
2094
2095 - split outgoing changes into a series of patches with
2095 - split outgoing changes into a series of patches with
2096 descriptive names::
2096 descriptive names::
2097
2097
2098 hg export -r "outgoing()" -o "%n-%m.patch"
2098 hg export -r "outgoing()" -o "%n-%m.patch"
2099
2099
2100 Returns 0 on success.
2100 Returns 0 on success.
2101 """
2101 """
2102 opts = pycompat.byteskwargs(opts)
2102 opts = pycompat.byteskwargs(opts)
2103 bookmark = opts.get('bookmark')
2103 bookmark = opts.get('bookmark')
2104 changesets += tuple(opts.get('rev', []))
2104 changesets += tuple(opts.get('rev', []))
2105
2105
2106 if bookmark and changesets:
2106 if bookmark and changesets:
2107 raise error.Abort(_("-r and -B are mutually exclusive"))
2107 raise error.Abort(_("-r and -B are mutually exclusive"))
2108
2108
2109 if bookmark:
2109 if bookmark:
2110 if bookmark not in repo._bookmarks:
2110 if bookmark not in repo._bookmarks:
2111 raise error.Abort(_("bookmark '%s' not found") % bookmark)
2111 raise error.Abort(_("bookmark '%s' not found") % bookmark)
2112
2112
2113 revs = scmutil.bookmarkrevs(repo, bookmark)
2113 revs = scmutil.bookmarkrevs(repo, bookmark)
2114 else:
2114 else:
2115 if not changesets:
2115 if not changesets:
2116 changesets = ['.']
2116 changesets = ['.']
2117
2117
2118 repo = scmutil.unhidehashlikerevs(repo, changesets, 'nowarn')
2118 repo = scmutil.unhidehashlikerevs(repo, changesets, 'nowarn')
2119 revs = scmutil.revrange(repo, changesets)
2119 revs = scmutil.revrange(repo, changesets)
2120
2120
2121 if not revs:
2121 if not revs:
2122 raise error.Abort(_("export requires at least one changeset"))
2122 raise error.Abort(_("export requires at least one changeset"))
2123 if len(revs) > 1:
2123 if len(revs) > 1:
2124 ui.note(_('exporting patches:\n'))
2124 ui.note(_('exporting patches:\n'))
2125 else:
2125 else:
2126 ui.note(_('exporting patch:\n'))
2126 ui.note(_('exporting patch:\n'))
2127
2127
2128 fntemplate = opts.get('output')
2128 fntemplate = opts.get('output')
2129 if cmdutil.isstdiofilename(fntemplate):
2129 if cmdutil.isstdiofilename(fntemplate):
2130 fntemplate = ''
2130 fntemplate = ''
2131
2131
2132 if fntemplate:
2132 if fntemplate:
2133 fm = formatter.nullformatter(ui, 'export', opts)
2133 fm = formatter.nullformatter(ui, 'export', opts)
2134 else:
2134 else:
2135 ui.pager('export')
2135 ui.pager('export')
2136 fm = ui.formatter('export', opts)
2136 fm = ui.formatter('export', opts)
2137 with fm:
2137 with fm:
2138 cmdutil.export(repo, revs, fm, fntemplate=fntemplate,
2138 cmdutil.export(repo, revs, fm, fntemplate=fntemplate,
2139 switch_parent=opts.get('switch_parent'),
2139 switch_parent=opts.get('switch_parent'),
2140 opts=patch.diffallopts(ui, opts))
2140 opts=patch.diffallopts(ui, opts))
2141
2141
2142 @command('files',
2142 @command('files',
2143 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
2143 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
2144 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
2144 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
2145 ] + walkopts + formatteropts + subrepoopts,
2145 ] + walkopts + formatteropts + subrepoopts,
2146 _('[OPTION]... [FILE]...'),
2146 _('[OPTION]... [FILE]...'),
2147 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2147 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2148 intents={INTENT_READONLY})
2148 intents={INTENT_READONLY})
2149 def files(ui, repo, *pats, **opts):
2149 def files(ui, repo, *pats, **opts):
2150 """list tracked files
2150 """list tracked files
2151
2151
2152 Print files under Mercurial control in the working directory or
2152 Print files under Mercurial control in the working directory or
2153 specified revision for given files (excluding removed files).
2153 specified revision for given files (excluding removed files).
2154 Files can be specified as filenames or filesets.
2154 Files can be specified as filenames or filesets.
2155
2155
2156 If no files are given to match, this command prints the names
2156 If no files are given to match, this command prints the names
2157 of all files under Mercurial control.
2157 of all files under Mercurial control.
2158
2158
2159 .. container:: verbose
2159 .. container:: verbose
2160
2160
2161 Template:
2161 Template:
2162
2162
2163 The following keywords are supported in addition to the common template
2163 The following keywords are supported in addition to the common template
2164 keywords and functions. See also :hg:`help templates`.
2164 keywords and functions. See also :hg:`help templates`.
2165
2165
2166 :flags: String. Character denoting file's symlink and executable bits.
2166 :flags: String. Character denoting file's symlink and executable bits.
2167 :path: String. Repository-absolute path of the file.
2167 :path: String. Repository-absolute path of the file.
2168 :size: Integer. Size of the file in bytes.
2168 :size: Integer. Size of the file in bytes.
2169
2169
2170 Examples:
2170 Examples:
2171
2171
2172 - list all files under the current directory::
2172 - list all files under the current directory::
2173
2173
2174 hg files .
2174 hg files .
2175
2175
2176 - shows sizes and flags for current revision::
2176 - shows sizes and flags for current revision::
2177
2177
2178 hg files -vr .
2178 hg files -vr .
2179
2179
2180 - list all files named README::
2180 - list all files named README::
2181
2181
2182 hg files -I "**/README"
2182 hg files -I "**/README"
2183
2183
2184 - list all binary files::
2184 - list all binary files::
2185
2185
2186 hg files "set:binary()"
2186 hg files "set:binary()"
2187
2187
2188 - find files containing a regular expression::
2188 - find files containing a regular expression::
2189
2189
2190 hg files "set:grep('bob')"
2190 hg files "set:grep('bob')"
2191
2191
2192 - search tracked file contents with xargs and grep::
2192 - search tracked file contents with xargs and grep::
2193
2193
2194 hg files -0 | xargs -0 grep foo
2194 hg files -0 | xargs -0 grep foo
2195
2195
2196 See :hg:`help patterns` and :hg:`help filesets` for more information
2196 See :hg:`help patterns` and :hg:`help filesets` for more information
2197 on specifying file patterns.
2197 on specifying file patterns.
2198
2198
2199 Returns 0 if a match is found, 1 otherwise.
2199 Returns 0 if a match is found, 1 otherwise.
2200
2200
2201 """
2201 """
2202
2202
2203 opts = pycompat.byteskwargs(opts)
2203 opts = pycompat.byteskwargs(opts)
2204 rev = opts.get('rev')
2204 rev = opts.get('rev')
2205 if rev:
2205 if rev:
2206 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
2206 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
2207 ctx = scmutil.revsingle(repo, rev, None)
2207 ctx = scmutil.revsingle(repo, rev, None)
2208
2208
2209 end = '\n'
2209 end = '\n'
2210 if opts.get('print0'):
2210 if opts.get('print0'):
2211 end = '\0'
2211 end = '\0'
2212 fmt = '%s' + end
2212 fmt = '%s' + end
2213
2213
2214 m = scmutil.match(ctx, pats, opts)
2214 m = scmutil.match(ctx, pats, opts)
2215 ui.pager('files')
2215 ui.pager('files')
2216 with ui.formatter('files', opts) as fm:
2216 with ui.formatter('files', opts) as fm:
2217 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2217 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2218
2218
2219 @command(
2219 @command(
2220 'forget',
2220 'forget',
2221 [('i', 'interactive', None, _('use interactive mode')),
2221 [('i', 'interactive', None, _('use interactive mode')),
2222 ] + walkopts + dryrunopts,
2222 ] + walkopts + dryrunopts,
2223 _('[OPTION]... FILE...'),
2223 _('[OPTION]... FILE...'),
2224 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2224 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2225 helpbasic=True, inferrepo=True)
2225 helpbasic=True, inferrepo=True)
2226 def forget(ui, repo, *pats, **opts):
2226 def forget(ui, repo, *pats, **opts):
2227 """forget the specified files on the next commit
2227 """forget the specified files on the next commit
2228
2228
2229 Mark the specified files so they will no longer be tracked
2229 Mark the specified files so they will no longer be tracked
2230 after the next commit.
2230 after the next commit.
2231
2231
2232 This only removes files from the current branch, not from the
2232 This only removes files from the current branch, not from the
2233 entire project history, and it does not delete them from the
2233 entire project history, and it does not delete them from the
2234 working directory.
2234 working directory.
2235
2235
2236 To delete the file from the working directory, see :hg:`remove`.
2236 To delete the file from the working directory, see :hg:`remove`.
2237
2237
2238 To undo a forget before the next commit, see :hg:`add`.
2238 To undo a forget before the next commit, see :hg:`add`.
2239
2239
2240 .. container:: verbose
2240 .. container:: verbose
2241
2241
2242 Examples:
2242 Examples:
2243
2243
2244 - forget newly-added binary files::
2244 - forget newly-added binary files::
2245
2245
2246 hg forget "set:added() and binary()"
2246 hg forget "set:added() and binary()"
2247
2247
2248 - forget files that would be excluded by .hgignore::
2248 - forget files that would be excluded by .hgignore::
2249
2249
2250 hg forget "set:hgignore()"
2250 hg forget "set:hgignore()"
2251
2251
2252 Returns 0 on success.
2252 Returns 0 on success.
2253 """
2253 """
2254
2254
2255 opts = pycompat.byteskwargs(opts)
2255 opts = pycompat.byteskwargs(opts)
2256 if not pats:
2256 if not pats:
2257 raise error.Abort(_('no files specified'))
2257 raise error.Abort(_('no files specified'))
2258
2258
2259 m = scmutil.match(repo[None], pats, opts)
2259 m = scmutil.match(repo[None], pats, opts)
2260 dryrun, interactive = opts.get('dry_run'), opts.get('interactive')
2260 dryrun, interactive = opts.get('dry_run'), opts.get('interactive')
2261 rejected = cmdutil.forget(ui, repo, m, prefix="",
2261 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=True)
2262 rejected = cmdutil.forget(ui, repo, m, prefix="", uipathfn=uipathfn,
2262 explicitonly=False, dryrun=dryrun,
2263 explicitonly=False, dryrun=dryrun,
2263 interactive=interactive)[0]
2264 interactive=interactive)[0]
2264 return rejected and 1 or 0
2265 return rejected and 1 or 0
2265
2266
2266 @command(
2267 @command(
2267 'graft',
2268 'graft',
2268 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2269 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2269 ('', 'base', '',
2270 ('', 'base', '',
2270 _('base revision when doing the graft merge (ADVANCED)'), _('REV')),
2271 _('base revision when doing the graft merge (ADVANCED)'), _('REV')),
2271 ('c', 'continue', False, _('resume interrupted graft')),
2272 ('c', 'continue', False, _('resume interrupted graft')),
2272 ('', 'stop', False, _('stop interrupted graft')),
2273 ('', 'stop', False, _('stop interrupted graft')),
2273 ('', 'abort', False, _('abort interrupted graft')),
2274 ('', 'abort', False, _('abort interrupted graft')),
2274 ('e', 'edit', False, _('invoke editor on commit messages')),
2275 ('e', 'edit', False, _('invoke editor on commit messages')),
2275 ('', 'log', None, _('append graft info to log message')),
2276 ('', 'log', None, _('append graft info to log message')),
2276 ('', 'no-commit', None,
2277 ('', 'no-commit', None,
2277 _("don't commit, just apply the changes in working directory")),
2278 _("don't commit, just apply the changes in working directory")),
2278 ('f', 'force', False, _('force graft')),
2279 ('f', 'force', False, _('force graft')),
2279 ('D', 'currentdate', False,
2280 ('D', 'currentdate', False,
2280 _('record the current date as commit date')),
2281 _('record the current date as commit date')),
2281 ('U', 'currentuser', False,
2282 ('U', 'currentuser', False,
2282 _('record the current user as committer'))]
2283 _('record the current user as committer'))]
2283 + commitopts2 + mergetoolopts + dryrunopts,
2284 + commitopts2 + mergetoolopts + dryrunopts,
2284 _('[OPTION]... [-r REV]... REV...'),
2285 _('[OPTION]... [-r REV]... REV...'),
2285 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT)
2286 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT)
2286 def graft(ui, repo, *revs, **opts):
2287 def graft(ui, repo, *revs, **opts):
2287 '''copy changes from other branches onto the current branch
2288 '''copy changes from other branches onto the current branch
2288
2289
2289 This command uses Mercurial's merge logic to copy individual
2290 This command uses Mercurial's merge logic to copy individual
2290 changes from other branches without merging branches in the
2291 changes from other branches without merging branches in the
2291 history graph. This is sometimes known as 'backporting' or
2292 history graph. This is sometimes known as 'backporting' or
2292 'cherry-picking'. By default, graft will copy user, date, and
2293 'cherry-picking'. By default, graft will copy user, date, and
2293 description from the source changesets.
2294 description from the source changesets.
2294
2295
2295 Changesets that are ancestors of the current revision, that have
2296 Changesets that are ancestors of the current revision, that have
2296 already been grafted, or that are merges will be skipped.
2297 already been grafted, or that are merges will be skipped.
2297
2298
2298 If --log is specified, log messages will have a comment appended
2299 If --log is specified, log messages will have a comment appended
2299 of the form::
2300 of the form::
2300
2301
2301 (grafted from CHANGESETHASH)
2302 (grafted from CHANGESETHASH)
2302
2303
2303 If --force is specified, revisions will be grafted even if they
2304 If --force is specified, revisions will be grafted even if they
2304 are already ancestors of, or have been grafted to, the destination.
2305 are already ancestors of, or have been grafted to, the destination.
2305 This is useful when the revisions have since been backed out.
2306 This is useful when the revisions have since been backed out.
2306
2307
2307 If a graft merge results in conflicts, the graft process is
2308 If a graft merge results in conflicts, the graft process is
2308 interrupted so that the current merge can be manually resolved.
2309 interrupted so that the current merge can be manually resolved.
2309 Once all conflicts are addressed, the graft process can be
2310 Once all conflicts are addressed, the graft process can be
2310 continued with the -c/--continue option.
2311 continued with the -c/--continue option.
2311
2312
2312 The -c/--continue option reapplies all the earlier options.
2313 The -c/--continue option reapplies all the earlier options.
2313
2314
2314 .. container:: verbose
2315 .. container:: verbose
2315
2316
2316 The --base option exposes more of how graft internally uses merge with a
2317 The --base option exposes more of how graft internally uses merge with a
2317 custom base revision. --base can be used to specify another ancestor than
2318 custom base revision. --base can be used to specify another ancestor than
2318 the first and only parent.
2319 the first and only parent.
2319
2320
2320 The command::
2321 The command::
2321
2322
2322 hg graft -r 345 --base 234
2323 hg graft -r 345 --base 234
2323
2324
2324 is thus pretty much the same as::
2325 is thus pretty much the same as::
2325
2326
2326 hg diff -r 234 -r 345 | hg import
2327 hg diff -r 234 -r 345 | hg import
2327
2328
2328 but using merge to resolve conflicts and track moved files.
2329 but using merge to resolve conflicts and track moved files.
2329
2330
2330 The result of a merge can thus be backported as a single commit by
2331 The result of a merge can thus be backported as a single commit by
2331 specifying one of the merge parents as base, and thus effectively
2332 specifying one of the merge parents as base, and thus effectively
2332 grafting the changes from the other side.
2333 grafting the changes from the other side.
2333
2334
2334 It is also possible to collapse multiple changesets and clean up history
2335 It is also possible to collapse multiple changesets and clean up history
2335 by specifying another ancestor as base, much like rebase --collapse
2336 by specifying another ancestor as base, much like rebase --collapse
2336 --keep.
2337 --keep.
2337
2338
2338 The commit message can be tweaked after the fact using commit --amend .
2339 The commit message can be tweaked after the fact using commit --amend .
2339
2340
2340 For using non-ancestors as the base to backout changes, see the backout
2341 For using non-ancestors as the base to backout changes, see the backout
2341 command and the hidden --parent option.
2342 command and the hidden --parent option.
2342
2343
2343 .. container:: verbose
2344 .. container:: verbose
2344
2345
2345 Examples:
2346 Examples:
2346
2347
2347 - copy a single change to the stable branch and edit its description::
2348 - copy a single change to the stable branch and edit its description::
2348
2349
2349 hg update stable
2350 hg update stable
2350 hg graft --edit 9393
2351 hg graft --edit 9393
2351
2352
2352 - graft a range of changesets with one exception, updating dates::
2353 - graft a range of changesets with one exception, updating dates::
2353
2354
2354 hg graft -D "2085::2093 and not 2091"
2355 hg graft -D "2085::2093 and not 2091"
2355
2356
2356 - continue a graft after resolving conflicts::
2357 - continue a graft after resolving conflicts::
2357
2358
2358 hg graft -c
2359 hg graft -c
2359
2360
2360 - show the source of a grafted changeset::
2361 - show the source of a grafted changeset::
2361
2362
2362 hg log --debug -r .
2363 hg log --debug -r .
2363
2364
2364 - show revisions sorted by date::
2365 - show revisions sorted by date::
2365
2366
2366 hg log -r "sort(all(), date)"
2367 hg log -r "sort(all(), date)"
2367
2368
2368 - backport the result of a merge as a single commit::
2369 - backport the result of a merge as a single commit::
2369
2370
2370 hg graft -r 123 --base 123^
2371 hg graft -r 123 --base 123^
2371
2372
2372 - land a feature branch as one changeset::
2373 - land a feature branch as one changeset::
2373
2374
2374 hg up -cr default
2375 hg up -cr default
2375 hg graft -r featureX --base "ancestor('featureX', 'default')"
2376 hg graft -r featureX --base "ancestor('featureX', 'default')"
2376
2377
2377 See :hg:`help revisions` for more about specifying revisions.
2378 See :hg:`help revisions` for more about specifying revisions.
2378
2379
2379 Returns 0 on successful completion.
2380 Returns 0 on successful completion.
2380 '''
2381 '''
2381 with repo.wlock():
2382 with repo.wlock():
2382 return _dograft(ui, repo, *revs, **opts)
2383 return _dograft(ui, repo, *revs, **opts)
2383
2384
2384 def _dograft(ui, repo, *revs, **opts):
2385 def _dograft(ui, repo, *revs, **opts):
2385 opts = pycompat.byteskwargs(opts)
2386 opts = pycompat.byteskwargs(opts)
2386 if revs and opts.get('rev'):
2387 if revs and opts.get('rev'):
2387 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2388 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2388 'revision ordering!\n'))
2389 'revision ordering!\n'))
2389
2390
2390 revs = list(revs)
2391 revs = list(revs)
2391 revs.extend(opts.get('rev'))
2392 revs.extend(opts.get('rev'))
2392 basectx = None
2393 basectx = None
2393 if opts.get('base'):
2394 if opts.get('base'):
2394 basectx = scmutil.revsingle(repo, opts['base'], None)
2395 basectx = scmutil.revsingle(repo, opts['base'], None)
2395 # a dict of data to be stored in state file
2396 # a dict of data to be stored in state file
2396 statedata = {}
2397 statedata = {}
2397 # list of new nodes created by ongoing graft
2398 # list of new nodes created by ongoing graft
2398 statedata['newnodes'] = []
2399 statedata['newnodes'] = []
2399
2400
2400 if opts.get('user') and opts.get('currentuser'):
2401 if opts.get('user') and opts.get('currentuser'):
2401 raise error.Abort(_('--user and --currentuser are mutually exclusive'))
2402 raise error.Abort(_('--user and --currentuser are mutually exclusive'))
2402 if opts.get('date') and opts.get('currentdate'):
2403 if opts.get('date') and opts.get('currentdate'):
2403 raise error.Abort(_('--date and --currentdate are mutually exclusive'))
2404 raise error.Abort(_('--date and --currentdate are mutually exclusive'))
2404 if not opts.get('user') and opts.get('currentuser'):
2405 if not opts.get('user') and opts.get('currentuser'):
2405 opts['user'] = ui.username()
2406 opts['user'] = ui.username()
2406 if not opts.get('date') and opts.get('currentdate'):
2407 if not opts.get('date') and opts.get('currentdate'):
2407 opts['date'] = "%d %d" % dateutil.makedate()
2408 opts['date'] = "%d %d" % dateutil.makedate()
2408
2409
2409 editor = cmdutil.getcommiteditor(editform='graft',
2410 editor = cmdutil.getcommiteditor(editform='graft',
2410 **pycompat.strkwargs(opts))
2411 **pycompat.strkwargs(opts))
2411
2412
2412 cont = False
2413 cont = False
2413 if opts.get('no_commit'):
2414 if opts.get('no_commit'):
2414 if opts.get('edit'):
2415 if opts.get('edit'):
2415 raise error.Abort(_("cannot specify --no-commit and "
2416 raise error.Abort(_("cannot specify --no-commit and "
2416 "--edit together"))
2417 "--edit together"))
2417 if opts.get('currentuser'):
2418 if opts.get('currentuser'):
2418 raise error.Abort(_("cannot specify --no-commit and "
2419 raise error.Abort(_("cannot specify --no-commit and "
2419 "--currentuser together"))
2420 "--currentuser together"))
2420 if opts.get('currentdate'):
2421 if opts.get('currentdate'):
2421 raise error.Abort(_("cannot specify --no-commit and "
2422 raise error.Abort(_("cannot specify --no-commit and "
2422 "--currentdate together"))
2423 "--currentdate together"))
2423 if opts.get('log'):
2424 if opts.get('log'):
2424 raise error.Abort(_("cannot specify --no-commit and "
2425 raise error.Abort(_("cannot specify --no-commit and "
2425 "--log together"))
2426 "--log together"))
2426
2427
2427 graftstate = statemod.cmdstate(repo, 'graftstate')
2428 graftstate = statemod.cmdstate(repo, 'graftstate')
2428
2429
2429 if opts.get('stop'):
2430 if opts.get('stop'):
2430 if opts.get('continue'):
2431 if opts.get('continue'):
2431 raise error.Abort(_("cannot use '--continue' and "
2432 raise error.Abort(_("cannot use '--continue' and "
2432 "'--stop' together"))
2433 "'--stop' together"))
2433 if opts.get('abort'):
2434 if opts.get('abort'):
2434 raise error.Abort(_("cannot use '--abort' and '--stop' together"))
2435 raise error.Abort(_("cannot use '--abort' and '--stop' together"))
2435
2436
2436 if any((opts.get('edit'), opts.get('log'), opts.get('user'),
2437 if any((opts.get('edit'), opts.get('log'), opts.get('user'),
2437 opts.get('date'), opts.get('currentdate'),
2438 opts.get('date'), opts.get('currentdate'),
2438 opts.get('currentuser'), opts.get('rev'))):
2439 opts.get('currentuser'), opts.get('rev'))):
2439 raise error.Abort(_("cannot specify any other flag with '--stop'"))
2440 raise error.Abort(_("cannot specify any other flag with '--stop'"))
2440 return _stopgraft(ui, repo, graftstate)
2441 return _stopgraft(ui, repo, graftstate)
2441 elif opts.get('abort'):
2442 elif opts.get('abort'):
2442 if opts.get('continue'):
2443 if opts.get('continue'):
2443 raise error.Abort(_("cannot use '--continue' and "
2444 raise error.Abort(_("cannot use '--continue' and "
2444 "'--abort' together"))
2445 "'--abort' together"))
2445 if any((opts.get('edit'), opts.get('log'), opts.get('user'),
2446 if any((opts.get('edit'), opts.get('log'), opts.get('user'),
2446 opts.get('date'), opts.get('currentdate'),
2447 opts.get('date'), opts.get('currentdate'),
2447 opts.get('currentuser'), opts.get('rev'))):
2448 opts.get('currentuser'), opts.get('rev'))):
2448 raise error.Abort(_("cannot specify any other flag with '--abort'"))
2449 raise error.Abort(_("cannot specify any other flag with '--abort'"))
2449
2450
2450 return _abortgraft(ui, repo, graftstate)
2451 return _abortgraft(ui, repo, graftstate)
2451 elif opts.get('continue'):
2452 elif opts.get('continue'):
2452 cont = True
2453 cont = True
2453 if revs:
2454 if revs:
2454 raise error.Abort(_("can't specify --continue and revisions"))
2455 raise error.Abort(_("can't specify --continue and revisions"))
2455 # read in unfinished revisions
2456 # read in unfinished revisions
2456 if graftstate.exists():
2457 if graftstate.exists():
2457 statedata = _readgraftstate(repo, graftstate)
2458 statedata = _readgraftstate(repo, graftstate)
2458 if statedata.get('date'):
2459 if statedata.get('date'):
2459 opts['date'] = statedata['date']
2460 opts['date'] = statedata['date']
2460 if statedata.get('user'):
2461 if statedata.get('user'):
2461 opts['user'] = statedata['user']
2462 opts['user'] = statedata['user']
2462 if statedata.get('log'):
2463 if statedata.get('log'):
2463 opts['log'] = True
2464 opts['log'] = True
2464 if statedata.get('no_commit'):
2465 if statedata.get('no_commit'):
2465 opts['no_commit'] = statedata.get('no_commit')
2466 opts['no_commit'] = statedata.get('no_commit')
2466 nodes = statedata['nodes']
2467 nodes = statedata['nodes']
2467 revs = [repo[node].rev() for node in nodes]
2468 revs = [repo[node].rev() for node in nodes]
2468 else:
2469 else:
2469 cmdutil.wrongtooltocontinue(repo, _('graft'))
2470 cmdutil.wrongtooltocontinue(repo, _('graft'))
2470 else:
2471 else:
2471 if not revs:
2472 if not revs:
2472 raise error.Abort(_('no revisions specified'))
2473 raise error.Abort(_('no revisions specified'))
2473 cmdutil.checkunfinished(repo)
2474 cmdutil.checkunfinished(repo)
2474 cmdutil.bailifchanged(repo)
2475 cmdutil.bailifchanged(repo)
2475 revs = scmutil.revrange(repo, revs)
2476 revs = scmutil.revrange(repo, revs)
2476
2477
2477 skipped = set()
2478 skipped = set()
2478 if basectx is None:
2479 if basectx is None:
2479 # check for merges
2480 # check for merges
2480 for rev in repo.revs('%ld and merge()', revs):
2481 for rev in repo.revs('%ld and merge()', revs):
2481 ui.warn(_('skipping ungraftable merge revision %d\n') % rev)
2482 ui.warn(_('skipping ungraftable merge revision %d\n') % rev)
2482 skipped.add(rev)
2483 skipped.add(rev)
2483 revs = [r for r in revs if r not in skipped]
2484 revs = [r for r in revs if r not in skipped]
2484 if not revs:
2485 if not revs:
2485 return -1
2486 return -1
2486 if basectx is not None and len(revs) != 1:
2487 if basectx is not None and len(revs) != 1:
2487 raise error.Abort(_('only one revision allowed with --base '))
2488 raise error.Abort(_('only one revision allowed with --base '))
2488
2489
2489 # Don't check in the --continue case, in effect retaining --force across
2490 # Don't check in the --continue case, in effect retaining --force across
2490 # --continues. That's because without --force, any revisions we decided to
2491 # --continues. That's because without --force, any revisions we decided to
2491 # skip would have been filtered out here, so they wouldn't have made their
2492 # skip would have been filtered out here, so they wouldn't have made their
2492 # way to the graftstate. With --force, any revisions we would have otherwise
2493 # way to the graftstate. With --force, any revisions we would have otherwise
2493 # skipped would not have been filtered out, and if they hadn't been applied
2494 # skipped would not have been filtered out, and if they hadn't been applied
2494 # already, they'd have been in the graftstate.
2495 # already, they'd have been in the graftstate.
2495 if not (cont or opts.get('force')) and basectx is None:
2496 if not (cont or opts.get('force')) and basectx is None:
2496 # check for ancestors of dest branch
2497 # check for ancestors of dest branch
2497 crev = repo['.'].rev()
2498 crev = repo['.'].rev()
2498 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2499 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2499 # XXX make this lazy in the future
2500 # XXX make this lazy in the future
2500 # don't mutate while iterating, create a copy
2501 # don't mutate while iterating, create a copy
2501 for rev in list(revs):
2502 for rev in list(revs):
2502 if rev in ancestors:
2503 if rev in ancestors:
2503 ui.warn(_('skipping ancestor revision %d:%s\n') %
2504 ui.warn(_('skipping ancestor revision %d:%s\n') %
2504 (rev, repo[rev]))
2505 (rev, repo[rev]))
2505 # XXX remove on list is slow
2506 # XXX remove on list is slow
2506 revs.remove(rev)
2507 revs.remove(rev)
2507 if not revs:
2508 if not revs:
2508 return -1
2509 return -1
2509
2510
2510 # analyze revs for earlier grafts
2511 # analyze revs for earlier grafts
2511 ids = {}
2512 ids = {}
2512 for ctx in repo.set("%ld", revs):
2513 for ctx in repo.set("%ld", revs):
2513 ids[ctx.hex()] = ctx.rev()
2514 ids[ctx.hex()] = ctx.rev()
2514 n = ctx.extra().get('source')
2515 n = ctx.extra().get('source')
2515 if n:
2516 if n:
2516 ids[n] = ctx.rev()
2517 ids[n] = ctx.rev()
2517
2518
2518 # check ancestors for earlier grafts
2519 # check ancestors for earlier grafts
2519 ui.debug('scanning for duplicate grafts\n')
2520 ui.debug('scanning for duplicate grafts\n')
2520
2521
2521 # The only changesets we can be sure doesn't contain grafts of any
2522 # The only changesets we can be sure doesn't contain grafts of any
2522 # revs, are the ones that are common ancestors of *all* revs:
2523 # revs, are the ones that are common ancestors of *all* revs:
2523 for rev in repo.revs('only(%d,ancestor(%ld))', crev, revs):
2524 for rev in repo.revs('only(%d,ancestor(%ld))', crev, revs):
2524 ctx = repo[rev]
2525 ctx = repo[rev]
2525 n = ctx.extra().get('source')
2526 n = ctx.extra().get('source')
2526 if n in ids:
2527 if n in ids:
2527 try:
2528 try:
2528 r = repo[n].rev()
2529 r = repo[n].rev()
2529 except error.RepoLookupError:
2530 except error.RepoLookupError:
2530 r = None
2531 r = None
2531 if r in revs:
2532 if r in revs:
2532 ui.warn(_('skipping revision %d:%s '
2533 ui.warn(_('skipping revision %d:%s '
2533 '(already grafted to %d:%s)\n')
2534 '(already grafted to %d:%s)\n')
2534 % (r, repo[r], rev, ctx))
2535 % (r, repo[r], rev, ctx))
2535 revs.remove(r)
2536 revs.remove(r)
2536 elif ids[n] in revs:
2537 elif ids[n] in revs:
2537 if r is None:
2538 if r is None:
2538 ui.warn(_('skipping already grafted revision %d:%s '
2539 ui.warn(_('skipping already grafted revision %d:%s '
2539 '(%d:%s also has unknown origin %s)\n')
2540 '(%d:%s also has unknown origin %s)\n')
2540 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2541 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2541 else:
2542 else:
2542 ui.warn(_('skipping already grafted revision %d:%s '
2543 ui.warn(_('skipping already grafted revision %d:%s '
2543 '(%d:%s also has origin %d:%s)\n')
2544 '(%d:%s also has origin %d:%s)\n')
2544 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2545 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2545 revs.remove(ids[n])
2546 revs.remove(ids[n])
2546 elif ctx.hex() in ids:
2547 elif ctx.hex() in ids:
2547 r = ids[ctx.hex()]
2548 r = ids[ctx.hex()]
2548 if r in revs:
2549 if r in revs:
2549 ui.warn(_('skipping already grafted revision %d:%s '
2550 ui.warn(_('skipping already grafted revision %d:%s '
2550 '(was grafted from %d:%s)\n') %
2551 '(was grafted from %d:%s)\n') %
2551 (r, repo[r], rev, ctx))
2552 (r, repo[r], rev, ctx))
2552 revs.remove(r)
2553 revs.remove(r)
2553 if not revs:
2554 if not revs:
2554 return -1
2555 return -1
2555
2556
2556 if opts.get('no_commit'):
2557 if opts.get('no_commit'):
2557 statedata['no_commit'] = True
2558 statedata['no_commit'] = True
2558 for pos, ctx in enumerate(repo.set("%ld", revs)):
2559 for pos, ctx in enumerate(repo.set("%ld", revs)):
2559 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2560 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2560 ctx.description().split('\n', 1)[0])
2561 ctx.description().split('\n', 1)[0])
2561 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2562 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2562 if names:
2563 if names:
2563 desc += ' (%s)' % ' '.join(names)
2564 desc += ' (%s)' % ' '.join(names)
2564 ui.status(_('grafting %s\n') % desc)
2565 ui.status(_('grafting %s\n') % desc)
2565 if opts.get('dry_run'):
2566 if opts.get('dry_run'):
2566 continue
2567 continue
2567
2568
2568 source = ctx.extra().get('source')
2569 source = ctx.extra().get('source')
2569 extra = {}
2570 extra = {}
2570 if source:
2571 if source:
2571 extra['source'] = source
2572 extra['source'] = source
2572 extra['intermediate-source'] = ctx.hex()
2573 extra['intermediate-source'] = ctx.hex()
2573 else:
2574 else:
2574 extra['source'] = ctx.hex()
2575 extra['source'] = ctx.hex()
2575 user = ctx.user()
2576 user = ctx.user()
2576 if opts.get('user'):
2577 if opts.get('user'):
2577 user = opts['user']
2578 user = opts['user']
2578 statedata['user'] = user
2579 statedata['user'] = user
2579 date = ctx.date()
2580 date = ctx.date()
2580 if opts.get('date'):
2581 if opts.get('date'):
2581 date = opts['date']
2582 date = opts['date']
2582 statedata['date'] = date
2583 statedata['date'] = date
2583 message = ctx.description()
2584 message = ctx.description()
2584 if opts.get('log'):
2585 if opts.get('log'):
2585 message += '\n(grafted from %s)' % ctx.hex()
2586 message += '\n(grafted from %s)' % ctx.hex()
2586 statedata['log'] = True
2587 statedata['log'] = True
2587
2588
2588 # we don't merge the first commit when continuing
2589 # we don't merge the first commit when continuing
2589 if not cont:
2590 if not cont:
2590 # perform the graft merge with p1(rev) as 'ancestor'
2591 # perform the graft merge with p1(rev) as 'ancestor'
2591 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
2592 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
2592 base = ctx.p1() if basectx is None else basectx
2593 base = ctx.p1() if basectx is None else basectx
2593 with ui.configoverride(overrides, 'graft'):
2594 with ui.configoverride(overrides, 'graft'):
2594 stats = mergemod.graft(repo, ctx, base, ['local', 'graft'])
2595 stats = mergemod.graft(repo, ctx, base, ['local', 'graft'])
2595 # report any conflicts
2596 # report any conflicts
2596 if stats.unresolvedcount > 0:
2597 if stats.unresolvedcount > 0:
2597 # write out state for --continue
2598 # write out state for --continue
2598 nodes = [repo[rev].hex() for rev in revs[pos:]]
2599 nodes = [repo[rev].hex() for rev in revs[pos:]]
2599 statedata['nodes'] = nodes
2600 statedata['nodes'] = nodes
2600 stateversion = 1
2601 stateversion = 1
2601 graftstate.save(stateversion, statedata)
2602 graftstate.save(stateversion, statedata)
2602 hint = _("use 'hg resolve' and 'hg graft --continue'")
2603 hint = _("use 'hg resolve' and 'hg graft --continue'")
2603 raise error.Abort(
2604 raise error.Abort(
2604 _("unresolved conflicts, can't continue"),
2605 _("unresolved conflicts, can't continue"),
2605 hint=hint)
2606 hint=hint)
2606 else:
2607 else:
2607 cont = False
2608 cont = False
2608
2609
2609 # commit if --no-commit is false
2610 # commit if --no-commit is false
2610 if not opts.get('no_commit'):
2611 if not opts.get('no_commit'):
2611 node = repo.commit(text=message, user=user, date=date, extra=extra,
2612 node = repo.commit(text=message, user=user, date=date, extra=extra,
2612 editor=editor)
2613 editor=editor)
2613 if node is None:
2614 if node is None:
2614 ui.warn(
2615 ui.warn(
2615 _('note: graft of %d:%s created no changes to commit\n') %
2616 _('note: graft of %d:%s created no changes to commit\n') %
2616 (ctx.rev(), ctx))
2617 (ctx.rev(), ctx))
2617 # checking that newnodes exist because old state files won't have it
2618 # checking that newnodes exist because old state files won't have it
2618 elif statedata.get('newnodes') is not None:
2619 elif statedata.get('newnodes') is not None:
2619 statedata['newnodes'].append(node)
2620 statedata['newnodes'].append(node)
2620
2621
2621 # remove state when we complete successfully
2622 # remove state when we complete successfully
2622 if not opts.get('dry_run'):
2623 if not opts.get('dry_run'):
2623 graftstate.delete()
2624 graftstate.delete()
2624
2625
2625 return 0
2626 return 0
2626
2627
2627 def _abortgraft(ui, repo, graftstate):
2628 def _abortgraft(ui, repo, graftstate):
2628 """abort the interrupted graft and rollbacks to the state before interrupted
2629 """abort the interrupted graft and rollbacks to the state before interrupted
2629 graft"""
2630 graft"""
2630 if not graftstate.exists():
2631 if not graftstate.exists():
2631 raise error.Abort(_("no interrupted graft to abort"))
2632 raise error.Abort(_("no interrupted graft to abort"))
2632 statedata = _readgraftstate(repo, graftstate)
2633 statedata = _readgraftstate(repo, graftstate)
2633 newnodes = statedata.get('newnodes')
2634 newnodes = statedata.get('newnodes')
2634 if newnodes is None:
2635 if newnodes is None:
2635 # and old graft state which does not have all the data required to abort
2636 # and old graft state which does not have all the data required to abort
2636 # the graft
2637 # the graft
2637 raise error.Abort(_("cannot abort using an old graftstate"))
2638 raise error.Abort(_("cannot abort using an old graftstate"))
2638
2639
2639 # changeset from which graft operation was started
2640 # changeset from which graft operation was started
2640 if len(newnodes) > 0:
2641 if len(newnodes) > 0:
2641 startctx = repo[newnodes[0]].p1()
2642 startctx = repo[newnodes[0]].p1()
2642 else:
2643 else:
2643 startctx = repo['.']
2644 startctx = repo['.']
2644 # whether to strip or not
2645 # whether to strip or not
2645 cleanup = False
2646 cleanup = False
2646 if newnodes:
2647 if newnodes:
2647 newnodes = [repo[r].rev() for r in newnodes]
2648 newnodes = [repo[r].rev() for r in newnodes]
2648 cleanup = True
2649 cleanup = True
2649 # checking that none of the newnodes turned public or is public
2650 # checking that none of the newnodes turned public or is public
2650 immutable = [c for c in newnodes if not repo[c].mutable()]
2651 immutable = [c for c in newnodes if not repo[c].mutable()]
2651 if immutable:
2652 if immutable:
2652 repo.ui.warn(_("cannot clean up public changesets %s\n")
2653 repo.ui.warn(_("cannot clean up public changesets %s\n")
2653 % ', '.join(bytes(repo[r]) for r in immutable),
2654 % ', '.join(bytes(repo[r]) for r in immutable),
2654 hint=_("see 'hg help phases' for details"))
2655 hint=_("see 'hg help phases' for details"))
2655 cleanup = False
2656 cleanup = False
2656
2657
2657 # checking that no new nodes are created on top of grafted revs
2658 # checking that no new nodes are created on top of grafted revs
2658 desc = set(repo.changelog.descendants(newnodes))
2659 desc = set(repo.changelog.descendants(newnodes))
2659 if desc - set(newnodes):
2660 if desc - set(newnodes):
2660 repo.ui.warn(_("new changesets detected on destination "
2661 repo.ui.warn(_("new changesets detected on destination "
2661 "branch, can't strip\n"))
2662 "branch, can't strip\n"))
2662 cleanup = False
2663 cleanup = False
2663
2664
2664 if cleanup:
2665 if cleanup:
2665 with repo.wlock(), repo.lock():
2666 with repo.wlock(), repo.lock():
2666 hg.updaterepo(repo, startctx.node(), overwrite=True)
2667 hg.updaterepo(repo, startctx.node(), overwrite=True)
2667 # stripping the new nodes created
2668 # stripping the new nodes created
2668 strippoints = [c.node() for c in repo.set("roots(%ld)",
2669 strippoints = [c.node() for c in repo.set("roots(%ld)",
2669 newnodes)]
2670 newnodes)]
2670 repair.strip(repo.ui, repo, strippoints, backup=False)
2671 repair.strip(repo.ui, repo, strippoints, backup=False)
2671
2672
2672 if not cleanup:
2673 if not cleanup:
2673 # we don't update to the startnode if we can't strip
2674 # we don't update to the startnode if we can't strip
2674 startctx = repo['.']
2675 startctx = repo['.']
2675 hg.updaterepo(repo, startctx.node(), overwrite=True)
2676 hg.updaterepo(repo, startctx.node(), overwrite=True)
2676
2677
2677 ui.status(_("graft aborted\n"))
2678 ui.status(_("graft aborted\n"))
2678 ui.status(_("working directory is now at %s\n") % startctx.hex()[:12])
2679 ui.status(_("working directory is now at %s\n") % startctx.hex()[:12])
2679 graftstate.delete()
2680 graftstate.delete()
2680 return 0
2681 return 0
2681
2682
2682 def _readgraftstate(repo, graftstate):
2683 def _readgraftstate(repo, graftstate):
2683 """read the graft state file and return a dict of the data stored in it"""
2684 """read the graft state file and return a dict of the data stored in it"""
2684 try:
2685 try:
2685 return graftstate.read()
2686 return graftstate.read()
2686 except error.CorruptedState:
2687 except error.CorruptedState:
2687 nodes = repo.vfs.read('graftstate').splitlines()
2688 nodes = repo.vfs.read('graftstate').splitlines()
2688 return {'nodes': nodes}
2689 return {'nodes': nodes}
2689
2690
2690 def _stopgraft(ui, repo, graftstate):
2691 def _stopgraft(ui, repo, graftstate):
2691 """stop the interrupted graft"""
2692 """stop the interrupted graft"""
2692 if not graftstate.exists():
2693 if not graftstate.exists():
2693 raise error.Abort(_("no interrupted graft found"))
2694 raise error.Abort(_("no interrupted graft found"))
2694 pctx = repo['.']
2695 pctx = repo['.']
2695 hg.updaterepo(repo, pctx.node(), overwrite=True)
2696 hg.updaterepo(repo, pctx.node(), overwrite=True)
2696 graftstate.delete()
2697 graftstate.delete()
2697 ui.status(_("stopped the interrupted graft\n"))
2698 ui.status(_("stopped the interrupted graft\n"))
2698 ui.status(_("working directory is now at %s\n") % pctx.hex()[:12])
2699 ui.status(_("working directory is now at %s\n") % pctx.hex()[:12])
2699 return 0
2700 return 0
2700
2701
2701 @command('grep',
2702 @command('grep',
2702 [('0', 'print0', None, _('end fields with NUL')),
2703 [('0', 'print0', None, _('end fields with NUL')),
2703 ('', 'all', None, _('print all revisions that match (DEPRECATED) ')),
2704 ('', 'all', None, _('print all revisions that match (DEPRECATED) ')),
2704 ('', 'diff', None, _('print all revisions when the term was introduced '
2705 ('', 'diff', None, _('print all revisions when the term was introduced '
2705 'or removed')),
2706 'or removed')),
2706 ('a', 'text', None, _('treat all files as text')),
2707 ('a', 'text', None, _('treat all files as text')),
2707 ('f', 'follow', None,
2708 ('f', 'follow', None,
2708 _('follow changeset history,'
2709 _('follow changeset history,'
2709 ' or file history across copies and renames')),
2710 ' or file history across copies and renames')),
2710 ('i', 'ignore-case', None, _('ignore case when matching')),
2711 ('i', 'ignore-case', None, _('ignore case when matching')),
2711 ('l', 'files-with-matches', None,
2712 ('l', 'files-with-matches', None,
2712 _('print only filenames and revisions that match')),
2713 _('print only filenames and revisions that match')),
2713 ('n', 'line-number', None, _('print matching line numbers')),
2714 ('n', 'line-number', None, _('print matching line numbers')),
2714 ('r', 'rev', [],
2715 ('r', 'rev', [],
2715 _('only search files changed within revision range'), _('REV')),
2716 _('only search files changed within revision range'), _('REV')),
2716 ('', 'all-files', None,
2717 ('', 'all-files', None,
2717 _('include all files in the changeset while grepping (EXPERIMENTAL)')),
2718 _('include all files in the changeset while grepping (EXPERIMENTAL)')),
2718 ('u', 'user', None, _('list the author (long with -v)')),
2719 ('u', 'user', None, _('list the author (long with -v)')),
2719 ('d', 'date', None, _('list the date (short with -q)')),
2720 ('d', 'date', None, _('list the date (short with -q)')),
2720 ] + formatteropts + walkopts,
2721 ] + formatteropts + walkopts,
2721 _('[OPTION]... PATTERN [FILE]...'),
2722 _('[OPTION]... PATTERN [FILE]...'),
2722 helpcategory=command.CATEGORY_FILE_CONTENTS,
2723 helpcategory=command.CATEGORY_FILE_CONTENTS,
2723 inferrepo=True,
2724 inferrepo=True,
2724 intents={INTENT_READONLY})
2725 intents={INTENT_READONLY})
2725 def grep(ui, repo, pattern, *pats, **opts):
2726 def grep(ui, repo, pattern, *pats, **opts):
2726 """search revision history for a pattern in specified files
2727 """search revision history for a pattern in specified files
2727
2728
2728 Search revision history for a regular expression in the specified
2729 Search revision history for a regular expression in the specified
2729 files or the entire project.
2730 files or the entire project.
2730
2731
2731 By default, grep prints the most recent revision number for each
2732 By default, grep prints the most recent revision number for each
2732 file in which it finds a match. To get it to print every revision
2733 file in which it finds a match. To get it to print every revision
2733 that contains a change in match status ("-" for a match that becomes
2734 that contains a change in match status ("-" for a match that becomes
2734 a non-match, or "+" for a non-match that becomes a match), use the
2735 a non-match, or "+" for a non-match that becomes a match), use the
2735 --diff flag.
2736 --diff flag.
2736
2737
2737 PATTERN can be any Python (roughly Perl-compatible) regular
2738 PATTERN can be any Python (roughly Perl-compatible) regular
2738 expression.
2739 expression.
2739
2740
2740 If no FILEs are specified (and -f/--follow isn't set), all files in
2741 If no FILEs are specified (and -f/--follow isn't set), all files in
2741 the repository are searched, including those that don't exist in the
2742 the repository are searched, including those that don't exist in the
2742 current branch or have been deleted in a prior changeset.
2743 current branch or have been deleted in a prior changeset.
2743
2744
2744 .. container:: verbose
2745 .. container:: verbose
2745
2746
2746 Template:
2747 Template:
2747
2748
2748 The following keywords are supported in addition to the common template
2749 The following keywords are supported in addition to the common template
2749 keywords and functions. See also :hg:`help templates`.
2750 keywords and functions. See also :hg:`help templates`.
2750
2751
2751 :change: String. Character denoting insertion ``+`` or removal ``-``.
2752 :change: String. Character denoting insertion ``+`` or removal ``-``.
2752 Available if ``--diff`` is specified.
2753 Available if ``--diff`` is specified.
2753 :lineno: Integer. Line number of the match.
2754 :lineno: Integer. Line number of the match.
2754 :path: String. Repository-absolute path of the file.
2755 :path: String. Repository-absolute path of the file.
2755 :texts: List of text chunks.
2756 :texts: List of text chunks.
2756
2757
2757 And each entry of ``{texts}`` provides the following sub-keywords.
2758 And each entry of ``{texts}`` provides the following sub-keywords.
2758
2759
2759 :matched: Boolean. True if the chunk matches the specified pattern.
2760 :matched: Boolean. True if the chunk matches the specified pattern.
2760 :text: String. Chunk content.
2761 :text: String. Chunk content.
2761
2762
2762 See :hg:`help templates.operators` for the list expansion syntax.
2763 See :hg:`help templates.operators` for the list expansion syntax.
2763
2764
2764 Returns 0 if a match is found, 1 otherwise.
2765 Returns 0 if a match is found, 1 otherwise.
2765 """
2766 """
2766 opts = pycompat.byteskwargs(opts)
2767 opts = pycompat.byteskwargs(opts)
2767 diff = opts.get('all') or opts.get('diff')
2768 diff = opts.get('all') or opts.get('diff')
2768 all_files = opts.get('all_files')
2769 all_files = opts.get('all_files')
2769 if diff and opts.get('all_files'):
2770 if diff and opts.get('all_files'):
2770 raise error.Abort(_('--diff and --all-files are mutually exclusive'))
2771 raise error.Abort(_('--diff and --all-files are mutually exclusive'))
2771 # TODO: remove "not opts.get('rev')" if --all-files -rMULTIREV gets working
2772 # TODO: remove "not opts.get('rev')" if --all-files -rMULTIREV gets working
2772 if opts.get('all_files') is None and not opts.get('rev') and not diff:
2773 if opts.get('all_files') is None and not opts.get('rev') and not diff:
2773 # experimental config: commands.grep.all-files
2774 # experimental config: commands.grep.all-files
2774 opts['all_files'] = ui.configbool('commands', 'grep.all-files')
2775 opts['all_files'] = ui.configbool('commands', 'grep.all-files')
2775 plaingrep = opts.get('all_files') and not opts.get('rev')
2776 plaingrep = opts.get('all_files') and not opts.get('rev')
2776 if plaingrep:
2777 if plaingrep:
2777 opts['rev'] = ['wdir()']
2778 opts['rev'] = ['wdir()']
2778
2779
2779 reflags = re.M
2780 reflags = re.M
2780 if opts.get('ignore_case'):
2781 if opts.get('ignore_case'):
2781 reflags |= re.I
2782 reflags |= re.I
2782 try:
2783 try:
2783 regexp = util.re.compile(pattern, reflags)
2784 regexp = util.re.compile(pattern, reflags)
2784 except re.error as inst:
2785 except re.error as inst:
2785 ui.warn(_("grep: invalid match pattern: %s\n") % pycompat.bytestr(inst))
2786 ui.warn(_("grep: invalid match pattern: %s\n") % pycompat.bytestr(inst))
2786 return 1
2787 return 1
2787 sep, eol = ':', '\n'
2788 sep, eol = ':', '\n'
2788 if opts.get('print0'):
2789 if opts.get('print0'):
2789 sep = eol = '\0'
2790 sep = eol = '\0'
2790
2791
2791 getfile = util.lrucachefunc(repo.file)
2792 getfile = util.lrucachefunc(repo.file)
2792
2793
2793 def matchlines(body):
2794 def matchlines(body):
2794 begin = 0
2795 begin = 0
2795 linenum = 0
2796 linenum = 0
2796 while begin < len(body):
2797 while begin < len(body):
2797 match = regexp.search(body, begin)
2798 match = regexp.search(body, begin)
2798 if not match:
2799 if not match:
2799 break
2800 break
2800 mstart, mend = match.span()
2801 mstart, mend = match.span()
2801 linenum += body.count('\n', begin, mstart) + 1
2802 linenum += body.count('\n', begin, mstart) + 1
2802 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2803 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2803 begin = body.find('\n', mend) + 1 or len(body) + 1
2804 begin = body.find('\n', mend) + 1 or len(body) + 1
2804 lend = begin - 1
2805 lend = begin - 1
2805 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2806 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2806
2807
2807 class linestate(object):
2808 class linestate(object):
2808 def __init__(self, line, linenum, colstart, colend):
2809 def __init__(self, line, linenum, colstart, colend):
2809 self.line = line
2810 self.line = line
2810 self.linenum = linenum
2811 self.linenum = linenum
2811 self.colstart = colstart
2812 self.colstart = colstart
2812 self.colend = colend
2813 self.colend = colend
2813
2814
2814 def __hash__(self):
2815 def __hash__(self):
2815 return hash((self.linenum, self.line))
2816 return hash((self.linenum, self.line))
2816
2817
2817 def __eq__(self, other):
2818 def __eq__(self, other):
2818 return self.line == other.line
2819 return self.line == other.line
2819
2820
2820 def findpos(self):
2821 def findpos(self):
2821 """Iterate all (start, end) indices of matches"""
2822 """Iterate all (start, end) indices of matches"""
2822 yield self.colstart, self.colend
2823 yield self.colstart, self.colend
2823 p = self.colend
2824 p = self.colend
2824 while p < len(self.line):
2825 while p < len(self.line):
2825 m = regexp.search(self.line, p)
2826 m = regexp.search(self.line, p)
2826 if not m:
2827 if not m:
2827 break
2828 break
2828 yield m.span()
2829 yield m.span()
2829 p = m.end()
2830 p = m.end()
2830
2831
2831 matches = {}
2832 matches = {}
2832 copies = {}
2833 copies = {}
2833 def grepbody(fn, rev, body):
2834 def grepbody(fn, rev, body):
2834 matches[rev].setdefault(fn, [])
2835 matches[rev].setdefault(fn, [])
2835 m = matches[rev][fn]
2836 m = matches[rev][fn]
2836 for lnum, cstart, cend, line in matchlines(body):
2837 for lnum, cstart, cend, line in matchlines(body):
2837 s = linestate(line, lnum, cstart, cend)
2838 s = linestate(line, lnum, cstart, cend)
2838 m.append(s)
2839 m.append(s)
2839
2840
2840 def difflinestates(a, b):
2841 def difflinestates(a, b):
2841 sm = difflib.SequenceMatcher(None, a, b)
2842 sm = difflib.SequenceMatcher(None, a, b)
2842 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2843 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2843 if tag == r'insert':
2844 if tag == r'insert':
2844 for i in pycompat.xrange(blo, bhi):
2845 for i in pycompat.xrange(blo, bhi):
2845 yield ('+', b[i])
2846 yield ('+', b[i])
2846 elif tag == r'delete':
2847 elif tag == r'delete':
2847 for i in pycompat.xrange(alo, ahi):
2848 for i in pycompat.xrange(alo, ahi):
2848 yield ('-', a[i])
2849 yield ('-', a[i])
2849 elif tag == r'replace':
2850 elif tag == r'replace':
2850 for i in pycompat.xrange(alo, ahi):
2851 for i in pycompat.xrange(alo, ahi):
2851 yield ('-', a[i])
2852 yield ('-', a[i])
2852 for i in pycompat.xrange(blo, bhi):
2853 for i in pycompat.xrange(blo, bhi):
2853 yield ('+', b[i])
2854 yield ('+', b[i])
2854
2855
2855 uipathfn = scmutil.getuipathfn(repo)
2856 uipathfn = scmutil.getuipathfn(repo)
2856 def display(fm, fn, ctx, pstates, states):
2857 def display(fm, fn, ctx, pstates, states):
2857 rev = scmutil.intrev(ctx)
2858 rev = scmutil.intrev(ctx)
2858 if fm.isplain():
2859 if fm.isplain():
2859 formatuser = ui.shortuser
2860 formatuser = ui.shortuser
2860 else:
2861 else:
2861 formatuser = pycompat.bytestr
2862 formatuser = pycompat.bytestr
2862 if ui.quiet:
2863 if ui.quiet:
2863 datefmt = '%Y-%m-%d'
2864 datefmt = '%Y-%m-%d'
2864 else:
2865 else:
2865 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2866 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2866 found = False
2867 found = False
2867 @util.cachefunc
2868 @util.cachefunc
2868 def binary():
2869 def binary():
2869 flog = getfile(fn)
2870 flog = getfile(fn)
2870 try:
2871 try:
2871 return stringutil.binary(flog.read(ctx.filenode(fn)))
2872 return stringutil.binary(flog.read(ctx.filenode(fn)))
2872 except error.WdirUnsupported:
2873 except error.WdirUnsupported:
2873 return ctx[fn].isbinary()
2874 return ctx[fn].isbinary()
2874
2875
2875 fieldnamemap = {'linenumber': 'lineno'}
2876 fieldnamemap = {'linenumber': 'lineno'}
2876 if diff:
2877 if diff:
2877 iter = difflinestates(pstates, states)
2878 iter = difflinestates(pstates, states)
2878 else:
2879 else:
2879 iter = [('', l) for l in states]
2880 iter = [('', l) for l in states]
2880 for change, l in iter:
2881 for change, l in iter:
2881 fm.startitem()
2882 fm.startitem()
2882 fm.context(ctx=ctx)
2883 fm.context(ctx=ctx)
2883 fm.data(node=fm.hexfunc(scmutil.binnode(ctx)), path=fn)
2884 fm.data(node=fm.hexfunc(scmutil.binnode(ctx)), path=fn)
2884 fm.plain(uipathfn(fn), label='grep.filename')
2885 fm.plain(uipathfn(fn), label='grep.filename')
2885
2886
2886 cols = [
2887 cols = [
2887 ('rev', '%d', rev, not plaingrep),
2888 ('rev', '%d', rev, not plaingrep),
2888 ('linenumber', '%d', l.linenum, opts.get('line_number')),
2889 ('linenumber', '%d', l.linenum, opts.get('line_number')),
2889 ]
2890 ]
2890 if diff:
2891 if diff:
2891 cols.append(('change', '%s', change, True))
2892 cols.append(('change', '%s', change, True))
2892 cols.extend([
2893 cols.extend([
2893 ('user', '%s', formatuser(ctx.user()), opts.get('user')),
2894 ('user', '%s', formatuser(ctx.user()), opts.get('user')),
2894 ('date', '%s', fm.formatdate(ctx.date(), datefmt),
2895 ('date', '%s', fm.formatdate(ctx.date(), datefmt),
2895 opts.get('date')),
2896 opts.get('date')),
2896 ])
2897 ])
2897 for name, fmt, data, cond in cols:
2898 for name, fmt, data, cond in cols:
2898 if cond:
2899 if cond:
2899 fm.plain(sep, label='grep.sep')
2900 fm.plain(sep, label='grep.sep')
2900 field = fieldnamemap.get(name, name)
2901 field = fieldnamemap.get(name, name)
2901 fm.condwrite(cond, field, fmt, data, label='grep.%s' % name)
2902 fm.condwrite(cond, field, fmt, data, label='grep.%s' % name)
2902 if not opts.get('files_with_matches'):
2903 if not opts.get('files_with_matches'):
2903 fm.plain(sep, label='grep.sep')
2904 fm.plain(sep, label='grep.sep')
2904 if not opts.get('text') and binary():
2905 if not opts.get('text') and binary():
2905 fm.plain(_(" Binary file matches"))
2906 fm.plain(_(" Binary file matches"))
2906 else:
2907 else:
2907 displaymatches(fm.nested('texts', tmpl='{text}'), l)
2908 displaymatches(fm.nested('texts', tmpl='{text}'), l)
2908 fm.plain(eol)
2909 fm.plain(eol)
2909 found = True
2910 found = True
2910 if opts.get('files_with_matches'):
2911 if opts.get('files_with_matches'):
2911 break
2912 break
2912 return found
2913 return found
2913
2914
2914 def displaymatches(fm, l):
2915 def displaymatches(fm, l):
2915 p = 0
2916 p = 0
2916 for s, e in l.findpos():
2917 for s, e in l.findpos():
2917 if p < s:
2918 if p < s:
2918 fm.startitem()
2919 fm.startitem()
2919 fm.write('text', '%s', l.line[p:s])
2920 fm.write('text', '%s', l.line[p:s])
2920 fm.data(matched=False)
2921 fm.data(matched=False)
2921 fm.startitem()
2922 fm.startitem()
2922 fm.write('text', '%s', l.line[s:e], label='grep.match')
2923 fm.write('text', '%s', l.line[s:e], label='grep.match')
2923 fm.data(matched=True)
2924 fm.data(matched=True)
2924 p = e
2925 p = e
2925 if p < len(l.line):
2926 if p < len(l.line):
2926 fm.startitem()
2927 fm.startitem()
2927 fm.write('text', '%s', l.line[p:])
2928 fm.write('text', '%s', l.line[p:])
2928 fm.data(matched=False)
2929 fm.data(matched=False)
2929 fm.end()
2930 fm.end()
2930
2931
2931 skip = set()
2932 skip = set()
2932 revfiles = {}
2933 revfiles = {}
2933 match = scmutil.match(repo[None], pats, opts)
2934 match = scmutil.match(repo[None], pats, opts)
2934 found = False
2935 found = False
2935 follow = opts.get('follow')
2936 follow = opts.get('follow')
2936
2937
2937 def prep(ctx, fns):
2938 def prep(ctx, fns):
2938 rev = ctx.rev()
2939 rev = ctx.rev()
2939 pctx = ctx.p1()
2940 pctx = ctx.p1()
2940 parent = pctx.rev()
2941 parent = pctx.rev()
2941 matches.setdefault(rev, {})
2942 matches.setdefault(rev, {})
2942 matches.setdefault(parent, {})
2943 matches.setdefault(parent, {})
2943 files = revfiles.setdefault(rev, [])
2944 files = revfiles.setdefault(rev, [])
2944 for fn in fns:
2945 for fn in fns:
2945 flog = getfile(fn)
2946 flog = getfile(fn)
2946 try:
2947 try:
2947 fnode = ctx.filenode(fn)
2948 fnode = ctx.filenode(fn)
2948 except error.LookupError:
2949 except error.LookupError:
2949 continue
2950 continue
2950 copy = None
2951 copy = None
2951 if follow:
2952 if follow:
2952 try:
2953 try:
2953 copied = flog.renamed(fnode)
2954 copied = flog.renamed(fnode)
2954 except error.WdirUnsupported:
2955 except error.WdirUnsupported:
2955 copied = ctx[fn].renamed()
2956 copied = ctx[fn].renamed()
2956 copy = copied and copied[0]
2957 copy = copied and copied[0]
2957 if copy:
2958 if copy:
2958 copies.setdefault(rev, {})[fn] = copy
2959 copies.setdefault(rev, {})[fn] = copy
2959 if fn in skip:
2960 if fn in skip:
2960 skip.add(copy)
2961 skip.add(copy)
2961 if fn in skip:
2962 if fn in skip:
2962 continue
2963 continue
2963 files.append(fn)
2964 files.append(fn)
2964
2965
2965 if fn not in matches[rev]:
2966 if fn not in matches[rev]:
2966 try:
2967 try:
2967 content = flog.read(fnode)
2968 content = flog.read(fnode)
2968 except error.WdirUnsupported:
2969 except error.WdirUnsupported:
2969 content = ctx[fn].data()
2970 content = ctx[fn].data()
2970 grepbody(fn, rev, content)
2971 grepbody(fn, rev, content)
2971
2972
2972 pfn = copy or fn
2973 pfn = copy or fn
2973 if pfn not in matches[parent]:
2974 if pfn not in matches[parent]:
2974 try:
2975 try:
2975 fnode = pctx.filenode(pfn)
2976 fnode = pctx.filenode(pfn)
2976 grepbody(pfn, parent, flog.read(fnode))
2977 grepbody(pfn, parent, flog.read(fnode))
2977 except error.LookupError:
2978 except error.LookupError:
2978 pass
2979 pass
2979
2980
2980 ui.pager('grep')
2981 ui.pager('grep')
2981 fm = ui.formatter('grep', opts)
2982 fm = ui.formatter('grep', opts)
2982 for ctx in cmdutil.walkchangerevs(repo, match, opts, prep):
2983 for ctx in cmdutil.walkchangerevs(repo, match, opts, prep):
2983 rev = ctx.rev()
2984 rev = ctx.rev()
2984 parent = ctx.p1().rev()
2985 parent = ctx.p1().rev()
2985 for fn in sorted(revfiles.get(rev, [])):
2986 for fn in sorted(revfiles.get(rev, [])):
2986 states = matches[rev][fn]
2987 states = matches[rev][fn]
2987 copy = copies.get(rev, {}).get(fn)
2988 copy = copies.get(rev, {}).get(fn)
2988 if fn in skip:
2989 if fn in skip:
2989 if copy:
2990 if copy:
2990 skip.add(copy)
2991 skip.add(copy)
2991 continue
2992 continue
2992 pstates = matches.get(parent, {}).get(copy or fn, [])
2993 pstates = matches.get(parent, {}).get(copy or fn, [])
2993 if pstates or states:
2994 if pstates or states:
2994 r = display(fm, fn, ctx, pstates, states)
2995 r = display(fm, fn, ctx, pstates, states)
2995 found = found or r
2996 found = found or r
2996 if r and not diff and not all_files:
2997 if r and not diff and not all_files:
2997 skip.add(fn)
2998 skip.add(fn)
2998 if copy:
2999 if copy:
2999 skip.add(copy)
3000 skip.add(copy)
3000 del revfiles[rev]
3001 del revfiles[rev]
3001 # We will keep the matches dict for the duration of the window
3002 # We will keep the matches dict for the duration of the window
3002 # clear the matches dict once the window is over
3003 # clear the matches dict once the window is over
3003 if not revfiles:
3004 if not revfiles:
3004 matches.clear()
3005 matches.clear()
3005 fm.end()
3006 fm.end()
3006
3007
3007 return not found
3008 return not found
3008
3009
3009 @command('heads',
3010 @command('heads',
3010 [('r', 'rev', '',
3011 [('r', 'rev', '',
3011 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3012 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3012 ('t', 'topo', False, _('show topological heads only')),
3013 ('t', 'topo', False, _('show topological heads only')),
3013 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3014 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3014 ('c', 'closed', False, _('show normal and closed branch heads')),
3015 ('c', 'closed', False, _('show normal and closed branch heads')),
3015 ] + templateopts,
3016 ] + templateopts,
3016 _('[-ct] [-r STARTREV] [REV]...'),
3017 _('[-ct] [-r STARTREV] [REV]...'),
3017 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3018 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3018 intents={INTENT_READONLY})
3019 intents={INTENT_READONLY})
3019 def heads(ui, repo, *branchrevs, **opts):
3020 def heads(ui, repo, *branchrevs, **opts):
3020 """show branch heads
3021 """show branch heads
3021
3022
3022 With no arguments, show all open branch heads in the repository.
3023 With no arguments, show all open branch heads in the repository.
3023 Branch heads are changesets that have no descendants on the
3024 Branch heads are changesets that have no descendants on the
3024 same branch. They are where development generally takes place and
3025 same branch. They are where development generally takes place and
3025 are the usual targets for update and merge operations.
3026 are the usual targets for update and merge operations.
3026
3027
3027 If one or more REVs are given, only open branch heads on the
3028 If one or more REVs are given, only open branch heads on the
3028 branches associated with the specified changesets are shown. This
3029 branches associated with the specified changesets are shown. This
3029 means that you can use :hg:`heads .` to see the heads on the
3030 means that you can use :hg:`heads .` to see the heads on the
3030 currently checked-out branch.
3031 currently checked-out branch.
3031
3032
3032 If -c/--closed is specified, also show branch heads marked closed
3033 If -c/--closed is specified, also show branch heads marked closed
3033 (see :hg:`commit --close-branch`).
3034 (see :hg:`commit --close-branch`).
3034
3035
3035 If STARTREV is specified, only those heads that are descendants of
3036 If STARTREV is specified, only those heads that are descendants of
3036 STARTREV will be displayed.
3037 STARTREV will be displayed.
3037
3038
3038 If -t/--topo is specified, named branch mechanics will be ignored and only
3039 If -t/--topo is specified, named branch mechanics will be ignored and only
3039 topological heads (changesets with no children) will be shown.
3040 topological heads (changesets with no children) will be shown.
3040
3041
3041 Returns 0 if matching heads are found, 1 if not.
3042 Returns 0 if matching heads are found, 1 if not.
3042 """
3043 """
3043
3044
3044 opts = pycompat.byteskwargs(opts)
3045 opts = pycompat.byteskwargs(opts)
3045 start = None
3046 start = None
3046 rev = opts.get('rev')
3047 rev = opts.get('rev')
3047 if rev:
3048 if rev:
3048 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
3049 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
3049 start = scmutil.revsingle(repo, rev, None).node()
3050 start = scmutil.revsingle(repo, rev, None).node()
3050
3051
3051 if opts.get('topo'):
3052 if opts.get('topo'):
3052 heads = [repo[h] for h in repo.heads(start)]
3053 heads = [repo[h] for h in repo.heads(start)]
3053 else:
3054 else:
3054 heads = []
3055 heads = []
3055 for branch in repo.branchmap():
3056 for branch in repo.branchmap():
3056 heads += repo.branchheads(branch, start, opts.get('closed'))
3057 heads += repo.branchheads(branch, start, opts.get('closed'))
3057 heads = [repo[h] for h in heads]
3058 heads = [repo[h] for h in heads]
3058
3059
3059 if branchrevs:
3060 if branchrevs:
3060 branches = set(repo[r].branch()
3061 branches = set(repo[r].branch()
3061 for r in scmutil.revrange(repo, branchrevs))
3062 for r in scmutil.revrange(repo, branchrevs))
3062 heads = [h for h in heads if h.branch() in branches]
3063 heads = [h for h in heads if h.branch() in branches]
3063
3064
3064 if opts.get('active') and branchrevs:
3065 if opts.get('active') and branchrevs:
3065 dagheads = repo.heads(start)
3066 dagheads = repo.heads(start)
3066 heads = [h for h in heads if h.node() in dagheads]
3067 heads = [h for h in heads if h.node() in dagheads]
3067
3068
3068 if branchrevs:
3069 if branchrevs:
3069 haveheads = set(h.branch() for h in heads)
3070 haveheads = set(h.branch() for h in heads)
3070 if branches - haveheads:
3071 if branches - haveheads:
3071 headless = ', '.join(b for b in branches - haveheads)
3072 headless = ', '.join(b for b in branches - haveheads)
3072 msg = _('no open branch heads found on branches %s')
3073 msg = _('no open branch heads found on branches %s')
3073 if opts.get('rev'):
3074 if opts.get('rev'):
3074 msg += _(' (started at %s)') % opts['rev']
3075 msg += _(' (started at %s)') % opts['rev']
3075 ui.warn((msg + '\n') % headless)
3076 ui.warn((msg + '\n') % headless)
3076
3077
3077 if not heads:
3078 if not heads:
3078 return 1
3079 return 1
3079
3080
3080 ui.pager('heads')
3081 ui.pager('heads')
3081 heads = sorted(heads, key=lambda x: -x.rev())
3082 heads = sorted(heads, key=lambda x: -x.rev())
3082 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3083 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3083 for ctx in heads:
3084 for ctx in heads:
3084 displayer.show(ctx)
3085 displayer.show(ctx)
3085 displayer.close()
3086 displayer.close()
3086
3087
3087 @command('help',
3088 @command('help',
3088 [('e', 'extension', None, _('show only help for extensions')),
3089 [('e', 'extension', None, _('show only help for extensions')),
3089 ('c', 'command', None, _('show only help for commands')),
3090 ('c', 'command', None, _('show only help for commands')),
3090 ('k', 'keyword', None, _('show topics matching keyword')),
3091 ('k', 'keyword', None, _('show topics matching keyword')),
3091 ('s', 'system', [],
3092 ('s', 'system', [],
3092 _('show help for specific platform(s)'), _('PLATFORM')),
3093 _('show help for specific platform(s)'), _('PLATFORM')),
3093 ],
3094 ],
3094 _('[-eck] [-s PLATFORM] [TOPIC]'),
3095 _('[-eck] [-s PLATFORM] [TOPIC]'),
3095 helpcategory=command.CATEGORY_HELP,
3096 helpcategory=command.CATEGORY_HELP,
3096 norepo=True,
3097 norepo=True,
3097 intents={INTENT_READONLY})
3098 intents={INTENT_READONLY})
3098 def help_(ui, name=None, **opts):
3099 def help_(ui, name=None, **opts):
3099 """show help for a given topic or a help overview
3100 """show help for a given topic or a help overview
3100
3101
3101 With no arguments, print a list of commands with short help messages.
3102 With no arguments, print a list of commands with short help messages.
3102
3103
3103 Given a topic, extension, or command name, print help for that
3104 Given a topic, extension, or command name, print help for that
3104 topic.
3105 topic.
3105
3106
3106 Returns 0 if successful.
3107 Returns 0 if successful.
3107 """
3108 """
3108
3109
3109 keep = opts.get(r'system') or []
3110 keep = opts.get(r'system') or []
3110 if len(keep) == 0:
3111 if len(keep) == 0:
3111 if pycompat.sysplatform.startswith('win'):
3112 if pycompat.sysplatform.startswith('win'):
3112 keep.append('windows')
3113 keep.append('windows')
3113 elif pycompat.sysplatform == 'OpenVMS':
3114 elif pycompat.sysplatform == 'OpenVMS':
3114 keep.append('vms')
3115 keep.append('vms')
3115 elif pycompat.sysplatform == 'plan9':
3116 elif pycompat.sysplatform == 'plan9':
3116 keep.append('plan9')
3117 keep.append('plan9')
3117 else:
3118 else:
3118 keep.append('unix')
3119 keep.append('unix')
3119 keep.append(pycompat.sysplatform.lower())
3120 keep.append(pycompat.sysplatform.lower())
3120 if ui.verbose:
3121 if ui.verbose:
3121 keep.append('verbose')
3122 keep.append('verbose')
3122
3123
3123 commands = sys.modules[__name__]
3124 commands = sys.modules[__name__]
3124 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
3125 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
3125 ui.pager('help')
3126 ui.pager('help')
3126 ui.write(formatted)
3127 ui.write(formatted)
3127
3128
3128
3129
3129 @command('identify|id',
3130 @command('identify|id',
3130 [('r', 'rev', '',
3131 [('r', 'rev', '',
3131 _('identify the specified revision'), _('REV')),
3132 _('identify the specified revision'), _('REV')),
3132 ('n', 'num', None, _('show local revision number')),
3133 ('n', 'num', None, _('show local revision number')),
3133 ('i', 'id', None, _('show global revision id')),
3134 ('i', 'id', None, _('show global revision id')),
3134 ('b', 'branch', None, _('show branch')),
3135 ('b', 'branch', None, _('show branch')),
3135 ('t', 'tags', None, _('show tags')),
3136 ('t', 'tags', None, _('show tags')),
3136 ('B', 'bookmarks', None, _('show bookmarks')),
3137 ('B', 'bookmarks', None, _('show bookmarks')),
3137 ] + remoteopts + formatteropts,
3138 ] + remoteopts + formatteropts,
3138 _('[-nibtB] [-r REV] [SOURCE]'),
3139 _('[-nibtB] [-r REV] [SOURCE]'),
3139 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3140 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3140 optionalrepo=True,
3141 optionalrepo=True,
3141 intents={INTENT_READONLY})
3142 intents={INTENT_READONLY})
3142 def identify(ui, repo, source=None, rev=None,
3143 def identify(ui, repo, source=None, rev=None,
3143 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3144 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3144 """identify the working directory or specified revision
3145 """identify the working directory or specified revision
3145
3146
3146 Print a summary identifying the repository state at REV using one or
3147 Print a summary identifying the repository state at REV using one or
3147 two parent hash identifiers, followed by a "+" if the working
3148 two parent hash identifiers, followed by a "+" if the working
3148 directory has uncommitted changes, the branch name (if not default),
3149 directory has uncommitted changes, the branch name (if not default),
3149 a list of tags, and a list of bookmarks.
3150 a list of tags, and a list of bookmarks.
3150
3151
3151 When REV is not given, print a summary of the current state of the
3152 When REV is not given, print a summary of the current state of the
3152 repository including the working directory. Specify -r. to get information
3153 repository including the working directory. Specify -r. to get information
3153 of the working directory parent without scanning uncommitted changes.
3154 of the working directory parent without scanning uncommitted changes.
3154
3155
3155 Specifying a path to a repository root or Mercurial bundle will
3156 Specifying a path to a repository root or Mercurial bundle will
3156 cause lookup to operate on that repository/bundle.
3157 cause lookup to operate on that repository/bundle.
3157
3158
3158 .. container:: verbose
3159 .. container:: verbose
3159
3160
3160 Template:
3161 Template:
3161
3162
3162 The following keywords are supported in addition to the common template
3163 The following keywords are supported in addition to the common template
3163 keywords and functions. See also :hg:`help templates`.
3164 keywords and functions. See also :hg:`help templates`.
3164
3165
3165 :dirty: String. Character ``+`` denoting if the working directory has
3166 :dirty: String. Character ``+`` denoting if the working directory has
3166 uncommitted changes.
3167 uncommitted changes.
3167 :id: String. One or two nodes, optionally followed by ``+``.
3168 :id: String. One or two nodes, optionally followed by ``+``.
3168 :parents: List of strings. Parent nodes of the changeset.
3169 :parents: List of strings. Parent nodes of the changeset.
3169
3170
3170 Examples:
3171 Examples:
3171
3172
3172 - generate a build identifier for the working directory::
3173 - generate a build identifier for the working directory::
3173
3174
3174 hg id --id > build-id.dat
3175 hg id --id > build-id.dat
3175
3176
3176 - find the revision corresponding to a tag::
3177 - find the revision corresponding to a tag::
3177
3178
3178 hg id -n -r 1.3
3179 hg id -n -r 1.3
3179
3180
3180 - check the most recent revision of a remote repository::
3181 - check the most recent revision of a remote repository::
3181
3182
3182 hg id -r tip https://www.mercurial-scm.org/repo/hg/
3183 hg id -r tip https://www.mercurial-scm.org/repo/hg/
3183
3184
3184 See :hg:`log` for generating more information about specific revisions,
3185 See :hg:`log` for generating more information about specific revisions,
3185 including full hash identifiers.
3186 including full hash identifiers.
3186
3187
3187 Returns 0 if successful.
3188 Returns 0 if successful.
3188 """
3189 """
3189
3190
3190 opts = pycompat.byteskwargs(opts)
3191 opts = pycompat.byteskwargs(opts)
3191 if not repo and not source:
3192 if not repo and not source:
3192 raise error.Abort(_("there is no Mercurial repository here "
3193 raise error.Abort(_("there is no Mercurial repository here "
3193 "(.hg not found)"))
3194 "(.hg not found)"))
3194
3195
3195 default = not (num or id or branch or tags or bookmarks)
3196 default = not (num or id or branch or tags or bookmarks)
3196 output = []
3197 output = []
3197 revs = []
3198 revs = []
3198
3199
3199 if source:
3200 if source:
3200 source, branches = hg.parseurl(ui.expandpath(source))
3201 source, branches = hg.parseurl(ui.expandpath(source))
3201 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3202 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3202 repo = peer.local()
3203 repo = peer.local()
3203 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3204 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3204
3205
3205 fm = ui.formatter('identify', opts)
3206 fm = ui.formatter('identify', opts)
3206 fm.startitem()
3207 fm.startitem()
3207
3208
3208 if not repo:
3209 if not repo:
3209 if num or branch or tags:
3210 if num or branch or tags:
3210 raise error.Abort(
3211 raise error.Abort(
3211 _("can't query remote revision number, branch, or tags"))
3212 _("can't query remote revision number, branch, or tags"))
3212 if not rev and revs:
3213 if not rev and revs:
3213 rev = revs[0]
3214 rev = revs[0]
3214 if not rev:
3215 if not rev:
3215 rev = "tip"
3216 rev = "tip"
3216
3217
3217 remoterev = peer.lookup(rev)
3218 remoterev = peer.lookup(rev)
3218 hexrev = fm.hexfunc(remoterev)
3219 hexrev = fm.hexfunc(remoterev)
3219 if default or id:
3220 if default or id:
3220 output = [hexrev]
3221 output = [hexrev]
3221 fm.data(id=hexrev)
3222 fm.data(id=hexrev)
3222
3223
3223 @util.cachefunc
3224 @util.cachefunc
3224 def getbms():
3225 def getbms():
3225 bms = []
3226 bms = []
3226
3227
3227 if 'bookmarks' in peer.listkeys('namespaces'):
3228 if 'bookmarks' in peer.listkeys('namespaces'):
3228 hexremoterev = hex(remoterev)
3229 hexremoterev = hex(remoterev)
3229 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3230 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3230 if bmr == hexremoterev]
3231 if bmr == hexremoterev]
3231
3232
3232 return sorted(bms)
3233 return sorted(bms)
3233
3234
3234 if fm.isplain():
3235 if fm.isplain():
3235 if bookmarks:
3236 if bookmarks:
3236 output.extend(getbms())
3237 output.extend(getbms())
3237 elif default and not ui.quiet:
3238 elif default and not ui.quiet:
3238 # multiple bookmarks for a single parent separated by '/'
3239 # multiple bookmarks for a single parent separated by '/'
3239 bm = '/'.join(getbms())
3240 bm = '/'.join(getbms())
3240 if bm:
3241 if bm:
3241 output.append(bm)
3242 output.append(bm)
3242 else:
3243 else:
3243 fm.data(node=hex(remoterev))
3244 fm.data(node=hex(remoterev))
3244 if bookmarks or 'bookmarks' in fm.datahint():
3245 if bookmarks or 'bookmarks' in fm.datahint():
3245 fm.data(bookmarks=fm.formatlist(getbms(), name='bookmark'))
3246 fm.data(bookmarks=fm.formatlist(getbms(), name='bookmark'))
3246 else:
3247 else:
3247 if rev:
3248 if rev:
3248 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
3249 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
3249 ctx = scmutil.revsingle(repo, rev, None)
3250 ctx = scmutil.revsingle(repo, rev, None)
3250
3251
3251 if ctx.rev() is None:
3252 if ctx.rev() is None:
3252 ctx = repo[None]
3253 ctx = repo[None]
3253 parents = ctx.parents()
3254 parents = ctx.parents()
3254 taglist = []
3255 taglist = []
3255 for p in parents:
3256 for p in parents:
3256 taglist.extend(p.tags())
3257 taglist.extend(p.tags())
3257
3258
3258 dirty = ""
3259 dirty = ""
3259 if ctx.dirty(missing=True, merge=False, branch=False):
3260 if ctx.dirty(missing=True, merge=False, branch=False):
3260 dirty = '+'
3261 dirty = '+'
3261 fm.data(dirty=dirty)
3262 fm.data(dirty=dirty)
3262
3263
3263 hexoutput = [fm.hexfunc(p.node()) for p in parents]
3264 hexoutput = [fm.hexfunc(p.node()) for p in parents]
3264 if default or id:
3265 if default or id:
3265 output = ["%s%s" % ('+'.join(hexoutput), dirty)]
3266 output = ["%s%s" % ('+'.join(hexoutput), dirty)]
3266 fm.data(id="%s%s" % ('+'.join(hexoutput), dirty))
3267 fm.data(id="%s%s" % ('+'.join(hexoutput), dirty))
3267
3268
3268 if num:
3269 if num:
3269 numoutput = ["%d" % p.rev() for p in parents]
3270 numoutput = ["%d" % p.rev() for p in parents]
3270 output.append("%s%s" % ('+'.join(numoutput), dirty))
3271 output.append("%s%s" % ('+'.join(numoutput), dirty))
3271
3272
3272 fm.data(parents=fm.formatlist([fm.hexfunc(p.node())
3273 fm.data(parents=fm.formatlist([fm.hexfunc(p.node())
3273 for p in parents], name='node'))
3274 for p in parents], name='node'))
3274 else:
3275 else:
3275 hexoutput = fm.hexfunc(ctx.node())
3276 hexoutput = fm.hexfunc(ctx.node())
3276 if default or id:
3277 if default or id:
3277 output = [hexoutput]
3278 output = [hexoutput]
3278 fm.data(id=hexoutput)
3279 fm.data(id=hexoutput)
3279
3280
3280 if num:
3281 if num:
3281 output.append(pycompat.bytestr(ctx.rev()))
3282 output.append(pycompat.bytestr(ctx.rev()))
3282 taglist = ctx.tags()
3283 taglist = ctx.tags()
3283
3284
3284 if default and not ui.quiet:
3285 if default and not ui.quiet:
3285 b = ctx.branch()
3286 b = ctx.branch()
3286 if b != 'default':
3287 if b != 'default':
3287 output.append("(%s)" % b)
3288 output.append("(%s)" % b)
3288
3289
3289 # multiple tags for a single parent separated by '/'
3290 # multiple tags for a single parent separated by '/'
3290 t = '/'.join(taglist)
3291 t = '/'.join(taglist)
3291 if t:
3292 if t:
3292 output.append(t)
3293 output.append(t)
3293
3294
3294 # multiple bookmarks for a single parent separated by '/'
3295 # multiple bookmarks for a single parent separated by '/'
3295 bm = '/'.join(ctx.bookmarks())
3296 bm = '/'.join(ctx.bookmarks())
3296 if bm:
3297 if bm:
3297 output.append(bm)
3298 output.append(bm)
3298 else:
3299 else:
3299 if branch:
3300 if branch:
3300 output.append(ctx.branch())
3301 output.append(ctx.branch())
3301
3302
3302 if tags:
3303 if tags:
3303 output.extend(taglist)
3304 output.extend(taglist)
3304
3305
3305 if bookmarks:
3306 if bookmarks:
3306 output.extend(ctx.bookmarks())
3307 output.extend(ctx.bookmarks())
3307
3308
3308 fm.data(node=ctx.hex())
3309 fm.data(node=ctx.hex())
3309 fm.data(branch=ctx.branch())
3310 fm.data(branch=ctx.branch())
3310 fm.data(tags=fm.formatlist(taglist, name='tag', sep=':'))
3311 fm.data(tags=fm.formatlist(taglist, name='tag', sep=':'))
3311 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name='bookmark'))
3312 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name='bookmark'))
3312 fm.context(ctx=ctx)
3313 fm.context(ctx=ctx)
3313
3314
3314 fm.plain("%s\n" % ' '.join(output))
3315 fm.plain("%s\n" % ' '.join(output))
3315 fm.end()
3316 fm.end()
3316
3317
3317 @command('import|patch',
3318 @command('import|patch',
3318 [('p', 'strip', 1,
3319 [('p', 'strip', 1,
3319 _('directory strip option for patch. This has the same '
3320 _('directory strip option for patch. This has the same '
3320 'meaning as the corresponding patch option'), _('NUM')),
3321 'meaning as the corresponding patch option'), _('NUM')),
3321 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3322 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3322 ('e', 'edit', False, _('invoke editor on commit messages')),
3323 ('e', 'edit', False, _('invoke editor on commit messages')),
3323 ('f', 'force', None,
3324 ('f', 'force', None,
3324 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
3325 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
3325 ('', 'no-commit', None,
3326 ('', 'no-commit', None,
3326 _("don't commit, just update the working directory")),
3327 _("don't commit, just update the working directory")),
3327 ('', 'bypass', None,
3328 ('', 'bypass', None,
3328 _("apply patch without touching the working directory")),
3329 _("apply patch without touching the working directory")),
3329 ('', 'partial', None,
3330 ('', 'partial', None,
3330 _('commit even if some hunks fail')),
3331 _('commit even if some hunks fail')),
3331 ('', 'exact', None,
3332 ('', 'exact', None,
3332 _('abort if patch would apply lossily')),
3333 _('abort if patch would apply lossily')),
3333 ('', 'prefix', '',
3334 ('', 'prefix', '',
3334 _('apply patch to subdirectory'), _('DIR')),
3335 _('apply patch to subdirectory'), _('DIR')),
3335 ('', 'import-branch', None,
3336 ('', 'import-branch', None,
3336 _('use any branch information in patch (implied by --exact)'))] +
3337 _('use any branch information in patch (implied by --exact)'))] +
3337 commitopts + commitopts2 + similarityopts,
3338 commitopts + commitopts2 + similarityopts,
3338 _('[OPTION]... PATCH...'),
3339 _('[OPTION]... PATCH...'),
3339 helpcategory=command.CATEGORY_IMPORT_EXPORT)
3340 helpcategory=command.CATEGORY_IMPORT_EXPORT)
3340 def import_(ui, repo, patch1=None, *patches, **opts):
3341 def import_(ui, repo, patch1=None, *patches, **opts):
3341 """import an ordered set of patches
3342 """import an ordered set of patches
3342
3343
3343 Import a list of patches and commit them individually (unless
3344 Import a list of patches and commit them individually (unless
3344 --no-commit is specified).
3345 --no-commit is specified).
3345
3346
3346 To read a patch from standard input (stdin), use "-" as the patch
3347 To read a patch from standard input (stdin), use "-" as the patch
3347 name. If a URL is specified, the patch will be downloaded from
3348 name. If a URL is specified, the patch will be downloaded from
3348 there.
3349 there.
3349
3350
3350 Import first applies changes to the working directory (unless
3351 Import first applies changes to the working directory (unless
3351 --bypass is specified), import will abort if there are outstanding
3352 --bypass is specified), import will abort if there are outstanding
3352 changes.
3353 changes.
3353
3354
3354 Use --bypass to apply and commit patches directly to the
3355 Use --bypass to apply and commit patches directly to the
3355 repository, without affecting the working directory. Without
3356 repository, without affecting the working directory. Without
3356 --exact, patches will be applied on top of the working directory
3357 --exact, patches will be applied on top of the working directory
3357 parent revision.
3358 parent revision.
3358
3359
3359 You can import a patch straight from a mail message. Even patches
3360 You can import a patch straight from a mail message. Even patches
3360 as attachments work (to use the body part, it must have type
3361 as attachments work (to use the body part, it must have type
3361 text/plain or text/x-patch). From and Subject headers of email
3362 text/plain or text/x-patch). From and Subject headers of email
3362 message are used as default committer and commit message. All
3363 message are used as default committer and commit message. All
3363 text/plain body parts before first diff are added to the commit
3364 text/plain body parts before first diff are added to the commit
3364 message.
3365 message.
3365
3366
3366 If the imported patch was generated by :hg:`export`, user and
3367 If the imported patch was generated by :hg:`export`, user and
3367 description from patch override values from message headers and
3368 description from patch override values from message headers and
3368 body. Values given on command line with -m/--message and -u/--user
3369 body. Values given on command line with -m/--message and -u/--user
3369 override these.
3370 override these.
3370
3371
3371 If --exact is specified, import will set the working directory to
3372 If --exact is specified, import will set the working directory to
3372 the parent of each patch before applying it, and will abort if the
3373 the parent of each patch before applying it, and will abort if the
3373 resulting changeset has a different ID than the one recorded in
3374 resulting changeset has a different ID than the one recorded in
3374 the patch. This will guard against various ways that portable
3375 the patch. This will guard against various ways that portable
3375 patch formats and mail systems might fail to transfer Mercurial
3376 patch formats and mail systems might fail to transfer Mercurial
3376 data or metadata. See :hg:`bundle` for lossless transmission.
3377 data or metadata. See :hg:`bundle` for lossless transmission.
3377
3378
3378 Use --partial to ensure a changeset will be created from the patch
3379 Use --partial to ensure a changeset will be created from the patch
3379 even if some hunks fail to apply. Hunks that fail to apply will be
3380 even if some hunks fail to apply. Hunks that fail to apply will be
3380 written to a <target-file>.rej file. Conflicts can then be resolved
3381 written to a <target-file>.rej file. Conflicts can then be resolved
3381 by hand before :hg:`commit --amend` is run to update the created
3382 by hand before :hg:`commit --amend` is run to update the created
3382 changeset. This flag exists to let people import patches that
3383 changeset. This flag exists to let people import patches that
3383 partially apply without losing the associated metadata (author,
3384 partially apply without losing the associated metadata (author,
3384 date, description, ...).
3385 date, description, ...).
3385
3386
3386 .. note::
3387 .. note::
3387
3388
3388 When no hunks apply cleanly, :hg:`import --partial` will create
3389 When no hunks apply cleanly, :hg:`import --partial` will create
3389 an empty changeset, importing only the patch metadata.
3390 an empty changeset, importing only the patch metadata.
3390
3391
3391 With -s/--similarity, hg will attempt to discover renames and
3392 With -s/--similarity, hg will attempt to discover renames and
3392 copies in the patch in the same way as :hg:`addremove`.
3393 copies in the patch in the same way as :hg:`addremove`.
3393
3394
3394 It is possible to use external patch programs to perform the patch
3395 It is possible to use external patch programs to perform the patch
3395 by setting the ``ui.patch`` configuration option. For the default
3396 by setting the ``ui.patch`` configuration option. For the default
3396 internal tool, the fuzz can also be configured via ``patch.fuzz``.
3397 internal tool, the fuzz can also be configured via ``patch.fuzz``.
3397 See :hg:`help config` for more information about configuration
3398 See :hg:`help config` for more information about configuration
3398 files and how to use these options.
3399 files and how to use these options.
3399
3400
3400 See :hg:`help dates` for a list of formats valid for -d/--date.
3401 See :hg:`help dates` for a list of formats valid for -d/--date.
3401
3402
3402 .. container:: verbose
3403 .. container:: verbose
3403
3404
3404 Examples:
3405 Examples:
3405
3406
3406 - import a traditional patch from a website and detect renames::
3407 - import a traditional patch from a website and detect renames::
3407
3408
3408 hg import -s 80 http://example.com/bugfix.patch
3409 hg import -s 80 http://example.com/bugfix.patch
3409
3410
3410 - import a changeset from an hgweb server::
3411 - import a changeset from an hgweb server::
3411
3412
3412 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
3413 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
3413
3414
3414 - import all the patches in an Unix-style mbox::
3415 - import all the patches in an Unix-style mbox::
3415
3416
3416 hg import incoming-patches.mbox
3417 hg import incoming-patches.mbox
3417
3418
3418 - import patches from stdin::
3419 - import patches from stdin::
3419
3420
3420 hg import -
3421 hg import -
3421
3422
3422 - attempt to exactly restore an exported changeset (not always
3423 - attempt to exactly restore an exported changeset (not always
3423 possible)::
3424 possible)::
3424
3425
3425 hg import --exact proposed-fix.patch
3426 hg import --exact proposed-fix.patch
3426
3427
3427 - use an external tool to apply a patch which is too fuzzy for
3428 - use an external tool to apply a patch which is too fuzzy for
3428 the default internal tool.
3429 the default internal tool.
3429
3430
3430 hg import --config ui.patch="patch --merge" fuzzy.patch
3431 hg import --config ui.patch="patch --merge" fuzzy.patch
3431
3432
3432 - change the default fuzzing from 2 to a less strict 7
3433 - change the default fuzzing from 2 to a less strict 7
3433
3434
3434 hg import --config ui.fuzz=7 fuzz.patch
3435 hg import --config ui.fuzz=7 fuzz.patch
3435
3436
3436 Returns 0 on success, 1 on partial success (see --partial).
3437 Returns 0 on success, 1 on partial success (see --partial).
3437 """
3438 """
3438
3439
3439 opts = pycompat.byteskwargs(opts)
3440 opts = pycompat.byteskwargs(opts)
3440 if not patch1:
3441 if not patch1:
3441 raise error.Abort(_('need at least one patch to import'))
3442 raise error.Abort(_('need at least one patch to import'))
3442
3443
3443 patches = (patch1,) + patches
3444 patches = (patch1,) + patches
3444
3445
3445 date = opts.get('date')
3446 date = opts.get('date')
3446 if date:
3447 if date:
3447 opts['date'] = dateutil.parsedate(date)
3448 opts['date'] = dateutil.parsedate(date)
3448
3449
3449 exact = opts.get('exact')
3450 exact = opts.get('exact')
3450 update = not opts.get('bypass')
3451 update = not opts.get('bypass')
3451 if not update and opts.get('no_commit'):
3452 if not update and opts.get('no_commit'):
3452 raise error.Abort(_('cannot use --no-commit with --bypass'))
3453 raise error.Abort(_('cannot use --no-commit with --bypass'))
3453 try:
3454 try:
3454 sim = float(opts.get('similarity') or 0)
3455 sim = float(opts.get('similarity') or 0)
3455 except ValueError:
3456 except ValueError:
3456 raise error.Abort(_('similarity must be a number'))
3457 raise error.Abort(_('similarity must be a number'))
3457 if sim < 0 or sim > 100:
3458 if sim < 0 or sim > 100:
3458 raise error.Abort(_('similarity must be between 0 and 100'))
3459 raise error.Abort(_('similarity must be between 0 and 100'))
3459 if sim and not update:
3460 if sim and not update:
3460 raise error.Abort(_('cannot use --similarity with --bypass'))
3461 raise error.Abort(_('cannot use --similarity with --bypass'))
3461 if exact:
3462 if exact:
3462 if opts.get('edit'):
3463 if opts.get('edit'):
3463 raise error.Abort(_('cannot use --exact with --edit'))
3464 raise error.Abort(_('cannot use --exact with --edit'))
3464 if opts.get('prefix'):
3465 if opts.get('prefix'):
3465 raise error.Abort(_('cannot use --exact with --prefix'))
3466 raise error.Abort(_('cannot use --exact with --prefix'))
3466
3467
3467 base = opts["base"]
3468 base = opts["base"]
3468 msgs = []
3469 msgs = []
3469 ret = 0
3470 ret = 0
3470
3471
3471 with repo.wlock():
3472 with repo.wlock():
3472 if update:
3473 if update:
3473 cmdutil.checkunfinished(repo)
3474 cmdutil.checkunfinished(repo)
3474 if (exact or not opts.get('force')):
3475 if (exact or not opts.get('force')):
3475 cmdutil.bailifchanged(repo)
3476 cmdutil.bailifchanged(repo)
3476
3477
3477 if not opts.get('no_commit'):
3478 if not opts.get('no_commit'):
3478 lock = repo.lock
3479 lock = repo.lock
3479 tr = lambda: repo.transaction('import')
3480 tr = lambda: repo.transaction('import')
3480 dsguard = util.nullcontextmanager
3481 dsguard = util.nullcontextmanager
3481 else:
3482 else:
3482 lock = util.nullcontextmanager
3483 lock = util.nullcontextmanager
3483 tr = util.nullcontextmanager
3484 tr = util.nullcontextmanager
3484 dsguard = lambda: dirstateguard.dirstateguard(repo, 'import')
3485 dsguard = lambda: dirstateguard.dirstateguard(repo, 'import')
3485 with lock(), tr(), dsguard():
3486 with lock(), tr(), dsguard():
3486 parents = repo[None].parents()
3487 parents = repo[None].parents()
3487 for patchurl in patches:
3488 for patchurl in patches:
3488 if patchurl == '-':
3489 if patchurl == '-':
3489 ui.status(_('applying patch from stdin\n'))
3490 ui.status(_('applying patch from stdin\n'))
3490 patchfile = ui.fin
3491 patchfile = ui.fin
3491 patchurl = 'stdin' # for error message
3492 patchurl = 'stdin' # for error message
3492 else:
3493 else:
3493 patchurl = os.path.join(base, patchurl)
3494 patchurl = os.path.join(base, patchurl)
3494 ui.status(_('applying %s\n') % patchurl)
3495 ui.status(_('applying %s\n') % patchurl)
3495 patchfile = hg.openpath(ui, patchurl)
3496 patchfile = hg.openpath(ui, patchurl)
3496
3497
3497 haspatch = False
3498 haspatch = False
3498 for hunk in patch.split(patchfile):
3499 for hunk in patch.split(patchfile):
3499 with patch.extract(ui, hunk) as patchdata:
3500 with patch.extract(ui, hunk) as patchdata:
3500 msg, node, rej = cmdutil.tryimportone(ui, repo,
3501 msg, node, rej = cmdutil.tryimportone(ui, repo,
3501 patchdata,
3502 patchdata,
3502 parents, opts,
3503 parents, opts,
3503 msgs, hg.clean)
3504 msgs, hg.clean)
3504 if msg:
3505 if msg:
3505 haspatch = True
3506 haspatch = True
3506 ui.note(msg + '\n')
3507 ui.note(msg + '\n')
3507 if update or exact:
3508 if update or exact:
3508 parents = repo[None].parents()
3509 parents = repo[None].parents()
3509 else:
3510 else:
3510 parents = [repo[node]]
3511 parents = [repo[node]]
3511 if rej:
3512 if rej:
3512 ui.write_err(_("patch applied partially\n"))
3513 ui.write_err(_("patch applied partially\n"))
3513 ui.write_err(_("(fix the .rej files and run "
3514 ui.write_err(_("(fix the .rej files and run "
3514 "`hg commit --amend`)\n"))
3515 "`hg commit --amend`)\n"))
3515 ret = 1
3516 ret = 1
3516 break
3517 break
3517
3518
3518 if not haspatch:
3519 if not haspatch:
3519 raise error.Abort(_('%s: no diffs found') % patchurl)
3520 raise error.Abort(_('%s: no diffs found') % patchurl)
3520
3521
3521 if msgs:
3522 if msgs:
3522 repo.savecommitmessage('\n* * *\n'.join(msgs))
3523 repo.savecommitmessage('\n* * *\n'.join(msgs))
3523 return ret
3524 return ret
3524
3525
3525 @command('incoming|in',
3526 @command('incoming|in',
3526 [('f', 'force', None,
3527 [('f', 'force', None,
3527 _('run even if remote repository is unrelated')),
3528 _('run even if remote repository is unrelated')),
3528 ('n', 'newest-first', None, _('show newest record first')),
3529 ('n', 'newest-first', None, _('show newest record first')),
3529 ('', 'bundle', '',
3530 ('', 'bundle', '',
3530 _('file to store the bundles into'), _('FILE')),
3531 _('file to store the bundles into'), _('FILE')),
3531 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3532 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3532 ('B', 'bookmarks', False, _("compare bookmarks")),
3533 ('B', 'bookmarks', False, _("compare bookmarks")),
3533 ('b', 'branch', [],
3534 ('b', 'branch', [],
3534 _('a specific branch you would like to pull'), _('BRANCH')),
3535 _('a specific branch you would like to pull'), _('BRANCH')),
3535 ] + logopts + remoteopts + subrepoopts,
3536 ] + logopts + remoteopts + subrepoopts,
3536 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'),
3537 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'),
3537 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT)
3538 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT)
3538 def incoming(ui, repo, source="default", **opts):
3539 def incoming(ui, repo, source="default", **opts):
3539 """show new changesets found in source
3540 """show new changesets found in source
3540
3541
3541 Show new changesets found in the specified path/URL or the default
3542 Show new changesets found in the specified path/URL or the default
3542 pull location. These are the changesets that would have been pulled
3543 pull location. These are the changesets that would have been pulled
3543 by :hg:`pull` at the time you issued this command.
3544 by :hg:`pull` at the time you issued this command.
3544
3545
3545 See pull for valid source format details.
3546 See pull for valid source format details.
3546
3547
3547 .. container:: verbose
3548 .. container:: verbose
3548
3549
3549 With -B/--bookmarks, the result of bookmark comparison between
3550 With -B/--bookmarks, the result of bookmark comparison between
3550 local and remote repositories is displayed. With -v/--verbose,
3551 local and remote repositories is displayed. With -v/--verbose,
3551 status is also displayed for each bookmark like below::
3552 status is also displayed for each bookmark like below::
3552
3553
3553 BM1 01234567890a added
3554 BM1 01234567890a added
3554 BM2 1234567890ab advanced
3555 BM2 1234567890ab advanced
3555 BM3 234567890abc diverged
3556 BM3 234567890abc diverged
3556 BM4 34567890abcd changed
3557 BM4 34567890abcd changed
3557
3558
3558 The action taken locally when pulling depends on the
3559 The action taken locally when pulling depends on the
3559 status of each bookmark:
3560 status of each bookmark:
3560
3561
3561 :``added``: pull will create it
3562 :``added``: pull will create it
3562 :``advanced``: pull will update it
3563 :``advanced``: pull will update it
3563 :``diverged``: pull will create a divergent bookmark
3564 :``diverged``: pull will create a divergent bookmark
3564 :``changed``: result depends on remote changesets
3565 :``changed``: result depends on remote changesets
3565
3566
3566 From the point of view of pulling behavior, bookmark
3567 From the point of view of pulling behavior, bookmark
3567 existing only in the remote repository are treated as ``added``,
3568 existing only in the remote repository are treated as ``added``,
3568 even if it is in fact locally deleted.
3569 even if it is in fact locally deleted.
3569
3570
3570 .. container:: verbose
3571 .. container:: verbose
3571
3572
3572 For remote repository, using --bundle avoids downloading the
3573 For remote repository, using --bundle avoids downloading the
3573 changesets twice if the incoming is followed by a pull.
3574 changesets twice if the incoming is followed by a pull.
3574
3575
3575 Examples:
3576 Examples:
3576
3577
3577 - show incoming changes with patches and full description::
3578 - show incoming changes with patches and full description::
3578
3579
3579 hg incoming -vp
3580 hg incoming -vp
3580
3581
3581 - show incoming changes excluding merges, store a bundle::
3582 - show incoming changes excluding merges, store a bundle::
3582
3583
3583 hg in -vpM --bundle incoming.hg
3584 hg in -vpM --bundle incoming.hg
3584 hg pull incoming.hg
3585 hg pull incoming.hg
3585
3586
3586 - briefly list changes inside a bundle::
3587 - briefly list changes inside a bundle::
3587
3588
3588 hg in changes.hg -T "{desc|firstline}\\n"
3589 hg in changes.hg -T "{desc|firstline}\\n"
3589
3590
3590 Returns 0 if there are incoming changes, 1 otherwise.
3591 Returns 0 if there are incoming changes, 1 otherwise.
3591 """
3592 """
3592 opts = pycompat.byteskwargs(opts)
3593 opts = pycompat.byteskwargs(opts)
3593 if opts.get('graph'):
3594 if opts.get('graph'):
3594 logcmdutil.checkunsupportedgraphflags([], opts)
3595 logcmdutil.checkunsupportedgraphflags([], opts)
3595 def display(other, chlist, displayer):
3596 def display(other, chlist, displayer):
3596 revdag = logcmdutil.graphrevs(other, chlist, opts)
3597 revdag = logcmdutil.graphrevs(other, chlist, opts)
3597 logcmdutil.displaygraph(ui, repo, revdag, displayer,
3598 logcmdutil.displaygraph(ui, repo, revdag, displayer,
3598 graphmod.asciiedges)
3599 graphmod.asciiedges)
3599
3600
3600 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3601 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3601 return 0
3602 return 0
3602
3603
3603 if opts.get('bundle') and opts.get('subrepos'):
3604 if opts.get('bundle') and opts.get('subrepos'):
3604 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3605 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3605
3606
3606 if opts.get('bookmarks'):
3607 if opts.get('bookmarks'):
3607 source, branches = hg.parseurl(ui.expandpath(source),
3608 source, branches = hg.parseurl(ui.expandpath(source),
3608 opts.get('branch'))
3609 opts.get('branch'))
3609 other = hg.peer(repo, opts, source)
3610 other = hg.peer(repo, opts, source)
3610 if 'bookmarks' not in other.listkeys('namespaces'):
3611 if 'bookmarks' not in other.listkeys('namespaces'):
3611 ui.warn(_("remote doesn't support bookmarks\n"))
3612 ui.warn(_("remote doesn't support bookmarks\n"))
3612 return 0
3613 return 0
3613 ui.pager('incoming')
3614 ui.pager('incoming')
3614 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3615 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3615 return bookmarks.incoming(ui, repo, other)
3616 return bookmarks.incoming(ui, repo, other)
3616
3617
3617 repo._subtoppath = ui.expandpath(source)
3618 repo._subtoppath = ui.expandpath(source)
3618 try:
3619 try:
3619 return hg.incoming(ui, repo, source, opts)
3620 return hg.incoming(ui, repo, source, opts)
3620 finally:
3621 finally:
3621 del repo._subtoppath
3622 del repo._subtoppath
3622
3623
3623
3624
3624 @command('init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3625 @command('init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3625 helpcategory=command.CATEGORY_REPO_CREATION,
3626 helpcategory=command.CATEGORY_REPO_CREATION,
3626 helpbasic=True, norepo=True)
3627 helpbasic=True, norepo=True)
3627 def init(ui, dest=".", **opts):
3628 def init(ui, dest=".", **opts):
3628 """create a new repository in the given directory
3629 """create a new repository in the given directory
3629
3630
3630 Initialize a new repository in the given directory. If the given
3631 Initialize a new repository in the given directory. If the given
3631 directory does not exist, it will be created.
3632 directory does not exist, it will be created.
3632
3633
3633 If no directory is given, the current directory is used.
3634 If no directory is given, the current directory is used.
3634
3635
3635 It is possible to specify an ``ssh://`` URL as the destination.
3636 It is possible to specify an ``ssh://`` URL as the destination.
3636 See :hg:`help urls` for more information.
3637 See :hg:`help urls` for more information.
3637
3638
3638 Returns 0 on success.
3639 Returns 0 on success.
3639 """
3640 """
3640 opts = pycompat.byteskwargs(opts)
3641 opts = pycompat.byteskwargs(opts)
3641 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3642 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3642
3643
3643 @command('locate',
3644 @command('locate',
3644 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3645 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3645 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3646 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3646 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3647 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3647 ] + walkopts,
3648 ] + walkopts,
3648 _('[OPTION]... [PATTERN]...'),
3649 _('[OPTION]... [PATTERN]...'),
3649 helpcategory=command.CATEGORY_WORKING_DIRECTORY)
3650 helpcategory=command.CATEGORY_WORKING_DIRECTORY)
3650 def locate(ui, repo, *pats, **opts):
3651 def locate(ui, repo, *pats, **opts):
3651 """locate files matching specific patterns (DEPRECATED)
3652 """locate files matching specific patterns (DEPRECATED)
3652
3653
3653 Print files under Mercurial control in the working directory whose
3654 Print files under Mercurial control in the working directory whose
3654 names match the given patterns.
3655 names match the given patterns.
3655
3656
3656 By default, this command searches all directories in the working
3657 By default, this command searches all directories in the working
3657 directory. To search just the current directory and its
3658 directory. To search just the current directory and its
3658 subdirectories, use "--include .".
3659 subdirectories, use "--include .".
3659
3660
3660 If no patterns are given to match, this command prints the names
3661 If no patterns are given to match, this command prints the names
3661 of all files under Mercurial control in the working directory.
3662 of all files under Mercurial control in the working directory.
3662
3663
3663 If you want to feed the output of this command into the "xargs"
3664 If you want to feed the output of this command into the "xargs"
3664 command, use the -0 option to both this command and "xargs". This
3665 command, use the -0 option to both this command and "xargs". This
3665 will avoid the problem of "xargs" treating single filenames that
3666 will avoid the problem of "xargs" treating single filenames that
3666 contain whitespace as multiple filenames.
3667 contain whitespace as multiple filenames.
3667
3668
3668 See :hg:`help files` for a more versatile command.
3669 See :hg:`help files` for a more versatile command.
3669
3670
3670 Returns 0 if a match is found, 1 otherwise.
3671 Returns 0 if a match is found, 1 otherwise.
3671 """
3672 """
3672 opts = pycompat.byteskwargs(opts)
3673 opts = pycompat.byteskwargs(opts)
3673 if opts.get('print0'):
3674 if opts.get('print0'):
3674 end = '\0'
3675 end = '\0'
3675 else:
3676 else:
3676 end = '\n'
3677 end = '\n'
3677 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3678 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3678
3679
3679 ret = 1
3680 ret = 1
3680 m = scmutil.match(ctx, pats, opts, default='relglob',
3681 m = scmutil.match(ctx, pats, opts, default='relglob',
3681 badfn=lambda x, y: False)
3682 badfn=lambda x, y: False)
3682
3683
3683 ui.pager('locate')
3684 ui.pager('locate')
3684 if ctx.rev() is None:
3685 if ctx.rev() is None:
3685 # When run on the working copy, "locate" includes removed files, so
3686 # When run on the working copy, "locate" includes removed files, so
3686 # we get the list of files from the dirstate.
3687 # we get the list of files from the dirstate.
3687 filesgen = sorted(repo.dirstate.matches(m))
3688 filesgen = sorted(repo.dirstate.matches(m))
3688 else:
3689 else:
3689 filesgen = ctx.matches(m)
3690 filesgen = ctx.matches(m)
3690 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats))
3691 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats))
3691 for abs in filesgen:
3692 for abs in filesgen:
3692 if opts.get('fullpath'):
3693 if opts.get('fullpath'):
3693 ui.write(repo.wjoin(abs), end)
3694 ui.write(repo.wjoin(abs), end)
3694 else:
3695 else:
3695 ui.write(uipathfn(abs), end)
3696 ui.write(uipathfn(abs), end)
3696 ret = 0
3697 ret = 0
3697
3698
3698 return ret
3699 return ret
3699
3700
3700 @command('log|history',
3701 @command('log|history',
3701 [('f', 'follow', None,
3702 [('f', 'follow', None,
3702 _('follow changeset history, or file history across copies and renames')),
3703 _('follow changeset history, or file history across copies and renames')),
3703 ('', 'follow-first', None,
3704 ('', 'follow-first', None,
3704 _('only follow the first parent of merge changesets (DEPRECATED)')),
3705 _('only follow the first parent of merge changesets (DEPRECATED)')),
3705 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3706 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3706 ('C', 'copies', None, _('show copied files')),
3707 ('C', 'copies', None, _('show copied files')),
3707 ('k', 'keyword', [],
3708 ('k', 'keyword', [],
3708 _('do case-insensitive search for a given text'), _('TEXT')),
3709 _('do case-insensitive search for a given text'), _('TEXT')),
3709 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3710 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3710 ('L', 'line-range', [],
3711 ('L', 'line-range', [],
3711 _('follow line range of specified file (EXPERIMENTAL)'),
3712 _('follow line range of specified file (EXPERIMENTAL)'),
3712 _('FILE,RANGE')),
3713 _('FILE,RANGE')),
3713 ('', 'removed', None, _('include revisions where files were removed')),
3714 ('', 'removed', None, _('include revisions where files were removed')),
3714 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3715 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3715 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3716 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3716 ('', 'only-branch', [],
3717 ('', 'only-branch', [],
3717 _('show only changesets within the given named branch (DEPRECATED)'),
3718 _('show only changesets within the given named branch (DEPRECATED)'),
3718 _('BRANCH')),
3719 _('BRANCH')),
3719 ('b', 'branch', [],
3720 ('b', 'branch', [],
3720 _('show changesets within the given named branch'), _('BRANCH')),
3721 _('show changesets within the given named branch'), _('BRANCH')),
3721 ('P', 'prune', [],
3722 ('P', 'prune', [],
3722 _('do not display revision or any of its ancestors'), _('REV')),
3723 _('do not display revision or any of its ancestors'), _('REV')),
3723 ] + logopts + walkopts,
3724 ] + logopts + walkopts,
3724 _('[OPTION]... [FILE]'),
3725 _('[OPTION]... [FILE]'),
3725 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3726 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3726 helpbasic=True, inferrepo=True,
3727 helpbasic=True, inferrepo=True,
3727 intents={INTENT_READONLY})
3728 intents={INTENT_READONLY})
3728 def log(ui, repo, *pats, **opts):
3729 def log(ui, repo, *pats, **opts):
3729 """show revision history of entire repository or files
3730 """show revision history of entire repository or files
3730
3731
3731 Print the revision history of the specified files or the entire
3732 Print the revision history of the specified files or the entire
3732 project.
3733 project.
3733
3734
3734 If no revision range is specified, the default is ``tip:0`` unless
3735 If no revision range is specified, the default is ``tip:0`` unless
3735 --follow is set, in which case the working directory parent is
3736 --follow is set, in which case the working directory parent is
3736 used as the starting revision.
3737 used as the starting revision.
3737
3738
3738 File history is shown without following rename or copy history of
3739 File history is shown without following rename or copy history of
3739 files. Use -f/--follow with a filename to follow history across
3740 files. Use -f/--follow with a filename to follow history across
3740 renames and copies. --follow without a filename will only show
3741 renames and copies. --follow without a filename will only show
3741 ancestors of the starting revision.
3742 ancestors of the starting revision.
3742
3743
3743 By default this command prints revision number and changeset id,
3744 By default this command prints revision number and changeset id,
3744 tags, non-trivial parents, user, date and time, and a summary for
3745 tags, non-trivial parents, user, date and time, and a summary for
3745 each commit. When the -v/--verbose switch is used, the list of
3746 each commit. When the -v/--verbose switch is used, the list of
3746 changed files and full commit message are shown.
3747 changed files and full commit message are shown.
3747
3748
3748 With --graph the revisions are shown as an ASCII art DAG with the most
3749 With --graph the revisions are shown as an ASCII art DAG with the most
3749 recent changeset at the top.
3750 recent changeset at the top.
3750 'o' is a changeset, '@' is a working directory parent, '_' closes a branch,
3751 'o' is a changeset, '@' is a working directory parent, '_' closes a branch,
3751 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
3752 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
3752 changeset from the lines below is a parent of the 'o' merge on the same
3753 changeset from the lines below is a parent of the 'o' merge on the same
3753 line.
3754 line.
3754 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
3755 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
3755 of a '|' indicates one or more revisions in a path are omitted.
3756 of a '|' indicates one or more revisions in a path are omitted.
3756
3757
3757 .. container:: verbose
3758 .. container:: verbose
3758
3759
3759 Use -L/--line-range FILE,M:N options to follow the history of lines
3760 Use -L/--line-range FILE,M:N options to follow the history of lines
3760 from M to N in FILE. With -p/--patch only diff hunks affecting
3761 from M to N in FILE. With -p/--patch only diff hunks affecting
3761 specified line range will be shown. This option requires --follow;
3762 specified line range will be shown. This option requires --follow;
3762 it can be specified multiple times. Currently, this option is not
3763 it can be specified multiple times. Currently, this option is not
3763 compatible with --graph. This option is experimental.
3764 compatible with --graph. This option is experimental.
3764
3765
3765 .. note::
3766 .. note::
3766
3767
3767 :hg:`log --patch` may generate unexpected diff output for merge
3768 :hg:`log --patch` may generate unexpected diff output for merge
3768 changesets, as it will only compare the merge changeset against
3769 changesets, as it will only compare the merge changeset against
3769 its first parent. Also, only files different from BOTH parents
3770 its first parent. Also, only files different from BOTH parents
3770 will appear in files:.
3771 will appear in files:.
3771
3772
3772 .. note::
3773 .. note::
3773
3774
3774 For performance reasons, :hg:`log FILE` may omit duplicate changes
3775 For performance reasons, :hg:`log FILE` may omit duplicate changes
3775 made on branches and will not show removals or mode changes. To
3776 made on branches and will not show removals or mode changes. To
3776 see all such changes, use the --removed switch.
3777 see all such changes, use the --removed switch.
3777
3778
3778 .. container:: verbose
3779 .. container:: verbose
3779
3780
3780 .. note::
3781 .. note::
3781
3782
3782 The history resulting from -L/--line-range options depends on diff
3783 The history resulting from -L/--line-range options depends on diff
3783 options; for instance if white-spaces are ignored, respective changes
3784 options; for instance if white-spaces are ignored, respective changes
3784 with only white-spaces in specified line range will not be listed.
3785 with only white-spaces in specified line range will not be listed.
3785
3786
3786 .. container:: verbose
3787 .. container:: verbose
3787
3788
3788 Some examples:
3789 Some examples:
3789
3790
3790 - changesets with full descriptions and file lists::
3791 - changesets with full descriptions and file lists::
3791
3792
3792 hg log -v
3793 hg log -v
3793
3794
3794 - changesets ancestral to the working directory::
3795 - changesets ancestral to the working directory::
3795
3796
3796 hg log -f
3797 hg log -f
3797
3798
3798 - last 10 commits on the current branch::
3799 - last 10 commits on the current branch::
3799
3800
3800 hg log -l 10 -b .
3801 hg log -l 10 -b .
3801
3802
3802 - changesets showing all modifications of a file, including removals::
3803 - changesets showing all modifications of a file, including removals::
3803
3804
3804 hg log --removed file.c
3805 hg log --removed file.c
3805
3806
3806 - all changesets that touch a directory, with diffs, excluding merges::
3807 - all changesets that touch a directory, with diffs, excluding merges::
3807
3808
3808 hg log -Mp lib/
3809 hg log -Mp lib/
3809
3810
3810 - all revision numbers that match a keyword::
3811 - all revision numbers that match a keyword::
3811
3812
3812 hg log -k bug --template "{rev}\\n"
3813 hg log -k bug --template "{rev}\\n"
3813
3814
3814 - the full hash identifier of the working directory parent::
3815 - the full hash identifier of the working directory parent::
3815
3816
3816 hg log -r . --template "{node}\\n"
3817 hg log -r . --template "{node}\\n"
3817
3818
3818 - list available log templates::
3819 - list available log templates::
3819
3820
3820 hg log -T list
3821 hg log -T list
3821
3822
3822 - check if a given changeset is included in a tagged release::
3823 - check if a given changeset is included in a tagged release::
3823
3824
3824 hg log -r "a21ccf and ancestor(1.9)"
3825 hg log -r "a21ccf and ancestor(1.9)"
3825
3826
3826 - find all changesets by some user in a date range::
3827 - find all changesets by some user in a date range::
3827
3828
3828 hg log -k alice -d "may 2008 to jul 2008"
3829 hg log -k alice -d "may 2008 to jul 2008"
3829
3830
3830 - summary of all changesets after the last tag::
3831 - summary of all changesets after the last tag::
3831
3832
3832 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3833 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3833
3834
3834 - changesets touching lines 13 to 23 for file.c::
3835 - changesets touching lines 13 to 23 for file.c::
3835
3836
3836 hg log -L file.c,13:23
3837 hg log -L file.c,13:23
3837
3838
3838 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
3839 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
3839 main.c with patch::
3840 main.c with patch::
3840
3841
3841 hg log -L file.c,13:23 -L main.c,2:6 -p
3842 hg log -L file.c,13:23 -L main.c,2:6 -p
3842
3843
3843 See :hg:`help dates` for a list of formats valid for -d/--date.
3844 See :hg:`help dates` for a list of formats valid for -d/--date.
3844
3845
3845 See :hg:`help revisions` for more about specifying and ordering
3846 See :hg:`help revisions` for more about specifying and ordering
3846 revisions.
3847 revisions.
3847
3848
3848 See :hg:`help templates` for more about pre-packaged styles and
3849 See :hg:`help templates` for more about pre-packaged styles and
3849 specifying custom templates. The default template used by the log
3850 specifying custom templates. The default template used by the log
3850 command can be customized via the ``ui.logtemplate`` configuration
3851 command can be customized via the ``ui.logtemplate`` configuration
3851 setting.
3852 setting.
3852
3853
3853 Returns 0 on success.
3854 Returns 0 on success.
3854
3855
3855 """
3856 """
3856 opts = pycompat.byteskwargs(opts)
3857 opts = pycompat.byteskwargs(opts)
3857 linerange = opts.get('line_range')
3858 linerange = opts.get('line_range')
3858
3859
3859 if linerange and not opts.get('follow'):
3860 if linerange and not opts.get('follow'):
3860 raise error.Abort(_('--line-range requires --follow'))
3861 raise error.Abort(_('--line-range requires --follow'))
3861
3862
3862 if linerange and pats:
3863 if linerange and pats:
3863 # TODO: take pats as patterns with no line-range filter
3864 # TODO: take pats as patterns with no line-range filter
3864 raise error.Abort(
3865 raise error.Abort(
3865 _('FILE arguments are not compatible with --line-range option')
3866 _('FILE arguments are not compatible with --line-range option')
3866 )
3867 )
3867
3868
3868 repo = scmutil.unhidehashlikerevs(repo, opts.get('rev'), 'nowarn')
3869 repo = scmutil.unhidehashlikerevs(repo, opts.get('rev'), 'nowarn')
3869 revs, differ = logcmdutil.getrevs(repo, pats, opts)
3870 revs, differ = logcmdutil.getrevs(repo, pats, opts)
3870 if linerange:
3871 if linerange:
3871 # TODO: should follow file history from logcmdutil._initialrevs(),
3872 # TODO: should follow file history from logcmdutil._initialrevs(),
3872 # then filter the result by logcmdutil._makerevset() and --limit
3873 # then filter the result by logcmdutil._makerevset() and --limit
3873 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
3874 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
3874
3875
3875 getrenamed = None
3876 getrenamed = None
3876 if opts.get('copies'):
3877 if opts.get('copies'):
3877 endrev = None
3878 endrev = None
3878 if revs:
3879 if revs:
3879 endrev = revs.max() + 1
3880 endrev = revs.max() + 1
3880 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3881 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3881
3882
3882 ui.pager('log')
3883 ui.pager('log')
3883 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, differ,
3884 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, differ,
3884 buffered=True)
3885 buffered=True)
3885 if opts.get('graph'):
3886 if opts.get('graph'):
3886 displayfn = logcmdutil.displaygraphrevs
3887 displayfn = logcmdutil.displaygraphrevs
3887 else:
3888 else:
3888 displayfn = logcmdutil.displayrevs
3889 displayfn = logcmdutil.displayrevs
3889 displayfn(ui, repo, revs, displayer, getrenamed)
3890 displayfn(ui, repo, revs, displayer, getrenamed)
3890
3891
3891 @command('manifest',
3892 @command('manifest',
3892 [('r', 'rev', '', _('revision to display'), _('REV')),
3893 [('r', 'rev', '', _('revision to display'), _('REV')),
3893 ('', 'all', False, _("list files from all revisions"))]
3894 ('', 'all', False, _("list files from all revisions"))]
3894 + formatteropts,
3895 + formatteropts,
3895 _('[-r REV]'),
3896 _('[-r REV]'),
3896 helpcategory=command.CATEGORY_MAINTENANCE,
3897 helpcategory=command.CATEGORY_MAINTENANCE,
3897 intents={INTENT_READONLY})
3898 intents={INTENT_READONLY})
3898 def manifest(ui, repo, node=None, rev=None, **opts):
3899 def manifest(ui, repo, node=None, rev=None, **opts):
3899 """output the current or given revision of the project manifest
3900 """output the current or given revision of the project manifest
3900
3901
3901 Print a list of version controlled files for the given revision.
3902 Print a list of version controlled files for the given revision.
3902 If no revision is given, the first parent of the working directory
3903 If no revision is given, the first parent of the working directory
3903 is used, or the null revision if no revision is checked out.
3904 is used, or the null revision if no revision is checked out.
3904
3905
3905 With -v, print file permissions, symlink and executable bits.
3906 With -v, print file permissions, symlink and executable bits.
3906 With --debug, print file revision hashes.
3907 With --debug, print file revision hashes.
3907
3908
3908 If option --all is specified, the list of all files from all revisions
3909 If option --all is specified, the list of all files from all revisions
3909 is printed. This includes deleted and renamed files.
3910 is printed. This includes deleted and renamed files.
3910
3911
3911 Returns 0 on success.
3912 Returns 0 on success.
3912 """
3913 """
3913 opts = pycompat.byteskwargs(opts)
3914 opts = pycompat.byteskwargs(opts)
3914 fm = ui.formatter('manifest', opts)
3915 fm = ui.formatter('manifest', opts)
3915
3916
3916 if opts.get('all'):
3917 if opts.get('all'):
3917 if rev or node:
3918 if rev or node:
3918 raise error.Abort(_("can't specify a revision with --all"))
3919 raise error.Abort(_("can't specify a revision with --all"))
3919
3920
3920 res = set()
3921 res = set()
3921 for rev in repo:
3922 for rev in repo:
3922 ctx = repo[rev]
3923 ctx = repo[rev]
3923 res |= set(ctx.files())
3924 res |= set(ctx.files())
3924
3925
3925 ui.pager('manifest')
3926 ui.pager('manifest')
3926 for f in sorted(res):
3927 for f in sorted(res):
3927 fm.startitem()
3928 fm.startitem()
3928 fm.write("path", '%s\n', f)
3929 fm.write("path", '%s\n', f)
3929 fm.end()
3930 fm.end()
3930 return
3931 return
3931
3932
3932 if rev and node:
3933 if rev and node:
3933 raise error.Abort(_("please specify just one revision"))
3934 raise error.Abort(_("please specify just one revision"))
3934
3935
3935 if not node:
3936 if not node:
3936 node = rev
3937 node = rev
3937
3938
3938 char = {'l': '@', 'x': '*', '': '', 't': 'd'}
3939 char = {'l': '@', 'x': '*', '': '', 't': 'd'}
3939 mode = {'l': '644', 'x': '755', '': '644', 't': '755'}
3940 mode = {'l': '644', 'x': '755', '': '644', 't': '755'}
3940 if node:
3941 if node:
3941 repo = scmutil.unhidehashlikerevs(repo, [node], 'nowarn')
3942 repo = scmutil.unhidehashlikerevs(repo, [node], 'nowarn')
3942 ctx = scmutil.revsingle(repo, node)
3943 ctx = scmutil.revsingle(repo, node)
3943 mf = ctx.manifest()
3944 mf = ctx.manifest()
3944 ui.pager('manifest')
3945 ui.pager('manifest')
3945 for f in ctx:
3946 for f in ctx:
3946 fm.startitem()
3947 fm.startitem()
3947 fm.context(ctx=ctx)
3948 fm.context(ctx=ctx)
3948 fl = ctx[f].flags()
3949 fl = ctx[f].flags()
3949 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3950 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3950 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3951 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3951 fm.write('path', '%s\n', f)
3952 fm.write('path', '%s\n', f)
3952 fm.end()
3953 fm.end()
3953
3954
3954 @command('merge',
3955 @command('merge',
3955 [('f', 'force', None,
3956 [('f', 'force', None,
3956 _('force a merge including outstanding changes (DEPRECATED)')),
3957 _('force a merge including outstanding changes (DEPRECATED)')),
3957 ('r', 'rev', '', _('revision to merge'), _('REV')),
3958 ('r', 'rev', '', _('revision to merge'), _('REV')),
3958 ('P', 'preview', None,
3959 ('P', 'preview', None,
3959 _('review revisions to merge (no merge is performed)')),
3960 _('review revisions to merge (no merge is performed)')),
3960 ('', 'abort', None, _('abort the ongoing merge')),
3961 ('', 'abort', None, _('abort the ongoing merge')),
3961 ] + mergetoolopts,
3962 ] + mergetoolopts,
3962 _('[-P] [[-r] REV]'),
3963 _('[-P] [[-r] REV]'),
3963 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT, helpbasic=True)
3964 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT, helpbasic=True)
3964 def merge(ui, repo, node=None, **opts):
3965 def merge(ui, repo, node=None, **opts):
3965 """merge another revision into working directory
3966 """merge another revision into working directory
3966
3967
3967 The current working directory is updated with all changes made in
3968 The current working directory is updated with all changes made in
3968 the requested revision since the last common predecessor revision.
3969 the requested revision since the last common predecessor revision.
3969
3970
3970 Files that changed between either parent are marked as changed for
3971 Files that changed between either parent are marked as changed for
3971 the next commit and a commit must be performed before any further
3972 the next commit and a commit must be performed before any further
3972 updates to the repository are allowed. The next commit will have
3973 updates to the repository are allowed. The next commit will have
3973 two parents.
3974 two parents.
3974
3975
3975 ``--tool`` can be used to specify the merge tool used for file
3976 ``--tool`` can be used to specify the merge tool used for file
3976 merges. It overrides the HGMERGE environment variable and your
3977 merges. It overrides the HGMERGE environment variable and your
3977 configuration files. See :hg:`help merge-tools` for options.
3978 configuration files. See :hg:`help merge-tools` for options.
3978
3979
3979 If no revision is specified, the working directory's parent is a
3980 If no revision is specified, the working directory's parent is a
3980 head revision, and the current branch contains exactly one other
3981 head revision, and the current branch contains exactly one other
3981 head, the other head is merged with by default. Otherwise, an
3982 head, the other head is merged with by default. Otherwise, an
3982 explicit revision with which to merge with must be provided.
3983 explicit revision with which to merge with must be provided.
3983
3984
3984 See :hg:`help resolve` for information on handling file conflicts.
3985 See :hg:`help resolve` for information on handling file conflicts.
3985
3986
3986 To undo an uncommitted merge, use :hg:`merge --abort` which
3987 To undo an uncommitted merge, use :hg:`merge --abort` which
3987 will check out a clean copy of the original merge parent, losing
3988 will check out a clean copy of the original merge parent, losing
3988 all changes.
3989 all changes.
3989
3990
3990 Returns 0 on success, 1 if there are unresolved files.
3991 Returns 0 on success, 1 if there are unresolved files.
3991 """
3992 """
3992
3993
3993 opts = pycompat.byteskwargs(opts)
3994 opts = pycompat.byteskwargs(opts)
3994 abort = opts.get('abort')
3995 abort = opts.get('abort')
3995 if abort and repo.dirstate.p2() == nullid:
3996 if abort and repo.dirstate.p2() == nullid:
3996 cmdutil.wrongtooltocontinue(repo, _('merge'))
3997 cmdutil.wrongtooltocontinue(repo, _('merge'))
3997 if abort:
3998 if abort:
3998 if node:
3999 if node:
3999 raise error.Abort(_("cannot specify a node with --abort"))
4000 raise error.Abort(_("cannot specify a node with --abort"))
4000 if opts.get('rev'):
4001 if opts.get('rev'):
4001 raise error.Abort(_("cannot specify both --rev and --abort"))
4002 raise error.Abort(_("cannot specify both --rev and --abort"))
4002 if opts.get('preview'):
4003 if opts.get('preview'):
4003 raise error.Abort(_("cannot specify --preview with --abort"))
4004 raise error.Abort(_("cannot specify --preview with --abort"))
4004 if opts.get('rev') and node:
4005 if opts.get('rev') and node:
4005 raise error.Abort(_("please specify just one revision"))
4006 raise error.Abort(_("please specify just one revision"))
4006 if not node:
4007 if not node:
4007 node = opts.get('rev')
4008 node = opts.get('rev')
4008
4009
4009 if node:
4010 if node:
4010 node = scmutil.revsingle(repo, node).node()
4011 node = scmutil.revsingle(repo, node).node()
4011
4012
4012 if not node and not abort:
4013 if not node and not abort:
4013 node = repo[destutil.destmerge(repo)].node()
4014 node = repo[destutil.destmerge(repo)].node()
4014
4015
4015 if opts.get('preview'):
4016 if opts.get('preview'):
4016 # find nodes that are ancestors of p2 but not of p1
4017 # find nodes that are ancestors of p2 but not of p1
4017 p1 = repo.lookup('.')
4018 p1 = repo.lookup('.')
4018 p2 = node
4019 p2 = node
4019 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4020 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4020
4021
4021 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4022 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4022 for node in nodes:
4023 for node in nodes:
4023 displayer.show(repo[node])
4024 displayer.show(repo[node])
4024 displayer.close()
4025 displayer.close()
4025 return 0
4026 return 0
4026
4027
4027 # ui.forcemerge is an internal variable, do not document
4028 # ui.forcemerge is an internal variable, do not document
4028 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
4029 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
4029 with ui.configoverride(overrides, 'merge'):
4030 with ui.configoverride(overrides, 'merge'):
4030 force = opts.get('force')
4031 force = opts.get('force')
4031 labels = ['working copy', 'merge rev']
4032 labels = ['working copy', 'merge rev']
4032 return hg.merge(repo, node, force=force, mergeforce=force,
4033 return hg.merge(repo, node, force=force, mergeforce=force,
4033 labels=labels, abort=abort)
4034 labels=labels, abort=abort)
4034
4035
4035 @command('outgoing|out',
4036 @command('outgoing|out',
4036 [('f', 'force', None, _('run even when the destination is unrelated')),
4037 [('f', 'force', None, _('run even when the destination is unrelated')),
4037 ('r', 'rev', [],
4038 ('r', 'rev', [],
4038 _('a changeset intended to be included in the destination'), _('REV')),
4039 _('a changeset intended to be included in the destination'), _('REV')),
4039 ('n', 'newest-first', None, _('show newest record first')),
4040 ('n', 'newest-first', None, _('show newest record first')),
4040 ('B', 'bookmarks', False, _('compare bookmarks')),
4041 ('B', 'bookmarks', False, _('compare bookmarks')),
4041 ('b', 'branch', [], _('a specific branch you would like to push'),
4042 ('b', 'branch', [], _('a specific branch you would like to push'),
4042 _('BRANCH')),
4043 _('BRANCH')),
4043 ] + logopts + remoteopts + subrepoopts,
4044 ] + logopts + remoteopts + subrepoopts,
4044 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'),
4045 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'),
4045 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT)
4046 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT)
4046 def outgoing(ui, repo, dest=None, **opts):
4047 def outgoing(ui, repo, dest=None, **opts):
4047 """show changesets not found in the destination
4048 """show changesets not found in the destination
4048
4049
4049 Show changesets not found in the specified destination repository
4050 Show changesets not found in the specified destination repository
4050 or the default push location. These are the changesets that would
4051 or the default push location. These are the changesets that would
4051 be pushed if a push was requested.
4052 be pushed if a push was requested.
4052
4053
4053 See pull for details of valid destination formats.
4054 See pull for details of valid destination formats.
4054
4055
4055 .. container:: verbose
4056 .. container:: verbose
4056
4057
4057 With -B/--bookmarks, the result of bookmark comparison between
4058 With -B/--bookmarks, the result of bookmark comparison between
4058 local and remote repositories is displayed. With -v/--verbose,
4059 local and remote repositories is displayed. With -v/--verbose,
4059 status is also displayed for each bookmark like below::
4060 status is also displayed for each bookmark like below::
4060
4061
4061 BM1 01234567890a added
4062 BM1 01234567890a added
4062 BM2 deleted
4063 BM2 deleted
4063 BM3 234567890abc advanced
4064 BM3 234567890abc advanced
4064 BM4 34567890abcd diverged
4065 BM4 34567890abcd diverged
4065 BM5 4567890abcde changed
4066 BM5 4567890abcde changed
4066
4067
4067 The action taken when pushing depends on the
4068 The action taken when pushing depends on the
4068 status of each bookmark:
4069 status of each bookmark:
4069
4070
4070 :``added``: push with ``-B`` will create it
4071 :``added``: push with ``-B`` will create it
4071 :``deleted``: push with ``-B`` will delete it
4072 :``deleted``: push with ``-B`` will delete it
4072 :``advanced``: push will update it
4073 :``advanced``: push will update it
4073 :``diverged``: push with ``-B`` will update it
4074 :``diverged``: push with ``-B`` will update it
4074 :``changed``: push with ``-B`` will update it
4075 :``changed``: push with ``-B`` will update it
4075
4076
4076 From the point of view of pushing behavior, bookmarks
4077 From the point of view of pushing behavior, bookmarks
4077 existing only in the remote repository are treated as
4078 existing only in the remote repository are treated as
4078 ``deleted``, even if it is in fact added remotely.
4079 ``deleted``, even if it is in fact added remotely.
4079
4080
4080 Returns 0 if there are outgoing changes, 1 otherwise.
4081 Returns 0 if there are outgoing changes, 1 otherwise.
4081 """
4082 """
4082 # hg._outgoing() needs to re-resolve the path in order to handle #branch
4083 # hg._outgoing() needs to re-resolve the path in order to handle #branch
4083 # style URLs, so don't overwrite dest.
4084 # style URLs, so don't overwrite dest.
4084 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4085 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4085 if not path:
4086 if not path:
4086 raise error.Abort(_('default repository not configured!'),
4087 raise error.Abort(_('default repository not configured!'),
4087 hint=_("see 'hg help config.paths'"))
4088 hint=_("see 'hg help config.paths'"))
4088
4089
4089 opts = pycompat.byteskwargs(opts)
4090 opts = pycompat.byteskwargs(opts)
4090 if opts.get('graph'):
4091 if opts.get('graph'):
4091 logcmdutil.checkunsupportedgraphflags([], opts)
4092 logcmdutil.checkunsupportedgraphflags([], opts)
4092 o, other = hg._outgoing(ui, repo, dest, opts)
4093 o, other = hg._outgoing(ui, repo, dest, opts)
4093 if not o:
4094 if not o:
4094 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4095 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4095 return
4096 return
4096
4097
4097 revdag = logcmdutil.graphrevs(repo, o, opts)
4098 revdag = logcmdutil.graphrevs(repo, o, opts)
4098 ui.pager('outgoing')
4099 ui.pager('outgoing')
4099 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, buffered=True)
4100 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, buffered=True)
4100 logcmdutil.displaygraph(ui, repo, revdag, displayer,
4101 logcmdutil.displaygraph(ui, repo, revdag, displayer,
4101 graphmod.asciiedges)
4102 graphmod.asciiedges)
4102 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4103 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4103 return 0
4104 return 0
4104
4105
4105 if opts.get('bookmarks'):
4106 if opts.get('bookmarks'):
4106 dest = path.pushloc or path.loc
4107 dest = path.pushloc or path.loc
4107 other = hg.peer(repo, opts, dest)
4108 other = hg.peer(repo, opts, dest)
4108 if 'bookmarks' not in other.listkeys('namespaces'):
4109 if 'bookmarks' not in other.listkeys('namespaces'):
4109 ui.warn(_("remote doesn't support bookmarks\n"))
4110 ui.warn(_("remote doesn't support bookmarks\n"))
4110 return 0
4111 return 0
4111 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4112 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4112 ui.pager('outgoing')
4113 ui.pager('outgoing')
4113 return bookmarks.outgoing(ui, repo, other)
4114 return bookmarks.outgoing(ui, repo, other)
4114
4115
4115 repo._subtoppath = path.pushloc or path.loc
4116 repo._subtoppath = path.pushloc or path.loc
4116 try:
4117 try:
4117 return hg.outgoing(ui, repo, dest, opts)
4118 return hg.outgoing(ui, repo, dest, opts)
4118 finally:
4119 finally:
4119 del repo._subtoppath
4120 del repo._subtoppath
4120
4121
4121 @command('parents',
4122 @command('parents',
4122 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4123 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4123 ] + templateopts,
4124 ] + templateopts,
4124 _('[-r REV] [FILE]'),
4125 _('[-r REV] [FILE]'),
4125 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4126 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4126 inferrepo=True)
4127 inferrepo=True)
4127 def parents(ui, repo, file_=None, **opts):
4128 def parents(ui, repo, file_=None, **opts):
4128 """show the parents of the working directory or revision (DEPRECATED)
4129 """show the parents of the working directory or revision (DEPRECATED)
4129
4130
4130 Print the working directory's parent revisions. If a revision is
4131 Print the working directory's parent revisions. If a revision is
4131 given via -r/--rev, the parent of that revision will be printed.
4132 given via -r/--rev, the parent of that revision will be printed.
4132 If a file argument is given, the revision in which the file was
4133 If a file argument is given, the revision in which the file was
4133 last changed (before the working directory revision or the
4134 last changed (before the working directory revision or the
4134 argument to --rev if given) is printed.
4135 argument to --rev if given) is printed.
4135
4136
4136 This command is equivalent to::
4137 This command is equivalent to::
4137
4138
4138 hg log -r "p1()+p2()" or
4139 hg log -r "p1()+p2()" or
4139 hg log -r "p1(REV)+p2(REV)" or
4140 hg log -r "p1(REV)+p2(REV)" or
4140 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
4141 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
4141 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
4142 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
4142
4143
4143 See :hg:`summary` and :hg:`help revsets` for related information.
4144 See :hg:`summary` and :hg:`help revsets` for related information.
4144
4145
4145 Returns 0 on success.
4146 Returns 0 on success.
4146 """
4147 """
4147
4148
4148 opts = pycompat.byteskwargs(opts)
4149 opts = pycompat.byteskwargs(opts)
4149 rev = opts.get('rev')
4150 rev = opts.get('rev')
4150 if rev:
4151 if rev:
4151 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
4152 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
4152 ctx = scmutil.revsingle(repo, rev, None)
4153 ctx = scmutil.revsingle(repo, rev, None)
4153
4154
4154 if file_:
4155 if file_:
4155 m = scmutil.match(ctx, (file_,), opts)
4156 m = scmutil.match(ctx, (file_,), opts)
4156 if m.anypats() or len(m.files()) != 1:
4157 if m.anypats() or len(m.files()) != 1:
4157 raise error.Abort(_('can only specify an explicit filename'))
4158 raise error.Abort(_('can only specify an explicit filename'))
4158 file_ = m.files()[0]
4159 file_ = m.files()[0]
4159 filenodes = []
4160 filenodes = []
4160 for cp in ctx.parents():
4161 for cp in ctx.parents():
4161 if not cp:
4162 if not cp:
4162 continue
4163 continue
4163 try:
4164 try:
4164 filenodes.append(cp.filenode(file_))
4165 filenodes.append(cp.filenode(file_))
4165 except error.LookupError:
4166 except error.LookupError:
4166 pass
4167 pass
4167 if not filenodes:
4168 if not filenodes:
4168 raise error.Abort(_("'%s' not found in manifest!") % file_)
4169 raise error.Abort(_("'%s' not found in manifest!") % file_)
4169 p = []
4170 p = []
4170 for fn in filenodes:
4171 for fn in filenodes:
4171 fctx = repo.filectx(file_, fileid=fn)
4172 fctx = repo.filectx(file_, fileid=fn)
4172 p.append(fctx.node())
4173 p.append(fctx.node())
4173 else:
4174 else:
4174 p = [cp.node() for cp in ctx.parents()]
4175 p = [cp.node() for cp in ctx.parents()]
4175
4176
4176 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4177 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4177 for n in p:
4178 for n in p:
4178 if n != nullid:
4179 if n != nullid:
4179 displayer.show(repo[n])
4180 displayer.show(repo[n])
4180 displayer.close()
4181 displayer.close()
4181
4182
4182 @command('paths', formatteropts, _('[NAME]'),
4183 @command('paths', formatteropts, _('[NAME]'),
4183 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4184 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4184 optionalrepo=True, intents={INTENT_READONLY})
4185 optionalrepo=True, intents={INTENT_READONLY})
4185 def paths(ui, repo, search=None, **opts):
4186 def paths(ui, repo, search=None, **opts):
4186 """show aliases for remote repositories
4187 """show aliases for remote repositories
4187
4188
4188 Show definition of symbolic path name NAME. If no name is given,
4189 Show definition of symbolic path name NAME. If no name is given,
4189 show definition of all available names.
4190 show definition of all available names.
4190
4191
4191 Option -q/--quiet suppresses all output when searching for NAME
4192 Option -q/--quiet suppresses all output when searching for NAME
4192 and shows only the path names when listing all definitions.
4193 and shows only the path names when listing all definitions.
4193
4194
4194 Path names are defined in the [paths] section of your
4195 Path names are defined in the [paths] section of your
4195 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4196 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4196 repository, ``.hg/hgrc`` is used, too.
4197 repository, ``.hg/hgrc`` is used, too.
4197
4198
4198 The path names ``default`` and ``default-push`` have a special
4199 The path names ``default`` and ``default-push`` have a special
4199 meaning. When performing a push or pull operation, they are used
4200 meaning. When performing a push or pull operation, they are used
4200 as fallbacks if no location is specified on the command-line.
4201 as fallbacks if no location is specified on the command-line.
4201 When ``default-push`` is set, it will be used for push and
4202 When ``default-push`` is set, it will be used for push and
4202 ``default`` will be used for pull; otherwise ``default`` is used
4203 ``default`` will be used for pull; otherwise ``default`` is used
4203 as the fallback for both. When cloning a repository, the clone
4204 as the fallback for both. When cloning a repository, the clone
4204 source is written as ``default`` in ``.hg/hgrc``.
4205 source is written as ``default`` in ``.hg/hgrc``.
4205
4206
4206 .. note::
4207 .. note::
4207
4208
4208 ``default`` and ``default-push`` apply to all inbound (e.g.
4209 ``default`` and ``default-push`` apply to all inbound (e.g.
4209 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
4210 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
4210 and :hg:`bundle`) operations.
4211 and :hg:`bundle`) operations.
4211
4212
4212 See :hg:`help urls` for more information.
4213 See :hg:`help urls` for more information.
4213
4214
4214 .. container:: verbose
4215 .. container:: verbose
4215
4216
4216 Template:
4217 Template:
4217
4218
4218 The following keywords are supported. See also :hg:`help templates`.
4219 The following keywords are supported. See also :hg:`help templates`.
4219
4220
4220 :name: String. Symbolic name of the path alias.
4221 :name: String. Symbolic name of the path alias.
4221 :pushurl: String. URL for push operations.
4222 :pushurl: String. URL for push operations.
4222 :url: String. URL or directory path for the other operations.
4223 :url: String. URL or directory path for the other operations.
4223
4224
4224 Returns 0 on success.
4225 Returns 0 on success.
4225 """
4226 """
4226
4227
4227 opts = pycompat.byteskwargs(opts)
4228 opts = pycompat.byteskwargs(opts)
4228 ui.pager('paths')
4229 ui.pager('paths')
4229 if search:
4230 if search:
4230 pathitems = [(name, path) for name, path in ui.paths.iteritems()
4231 pathitems = [(name, path) for name, path in ui.paths.iteritems()
4231 if name == search]
4232 if name == search]
4232 else:
4233 else:
4233 pathitems = sorted(ui.paths.iteritems())
4234 pathitems = sorted(ui.paths.iteritems())
4234
4235
4235 fm = ui.formatter('paths', opts)
4236 fm = ui.formatter('paths', opts)
4236 if fm.isplain():
4237 if fm.isplain():
4237 hidepassword = util.hidepassword
4238 hidepassword = util.hidepassword
4238 else:
4239 else:
4239 hidepassword = bytes
4240 hidepassword = bytes
4240 if ui.quiet:
4241 if ui.quiet:
4241 namefmt = '%s\n'
4242 namefmt = '%s\n'
4242 else:
4243 else:
4243 namefmt = '%s = '
4244 namefmt = '%s = '
4244 showsubopts = not search and not ui.quiet
4245 showsubopts = not search and not ui.quiet
4245
4246
4246 for name, path in pathitems:
4247 for name, path in pathitems:
4247 fm.startitem()
4248 fm.startitem()
4248 fm.condwrite(not search, 'name', namefmt, name)
4249 fm.condwrite(not search, 'name', namefmt, name)
4249 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
4250 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
4250 for subopt, value in sorted(path.suboptions.items()):
4251 for subopt, value in sorted(path.suboptions.items()):
4251 assert subopt not in ('name', 'url')
4252 assert subopt not in ('name', 'url')
4252 if showsubopts:
4253 if showsubopts:
4253 fm.plain('%s:%s = ' % (name, subopt))
4254 fm.plain('%s:%s = ' % (name, subopt))
4254 fm.condwrite(showsubopts, subopt, '%s\n', value)
4255 fm.condwrite(showsubopts, subopt, '%s\n', value)
4255
4256
4256 fm.end()
4257 fm.end()
4257
4258
4258 if search and not pathitems:
4259 if search and not pathitems:
4259 if not ui.quiet:
4260 if not ui.quiet:
4260 ui.warn(_("not found!\n"))
4261 ui.warn(_("not found!\n"))
4261 return 1
4262 return 1
4262 else:
4263 else:
4263 return 0
4264 return 0
4264
4265
4265 @command('phase',
4266 @command('phase',
4266 [('p', 'public', False, _('set changeset phase to public')),
4267 [('p', 'public', False, _('set changeset phase to public')),
4267 ('d', 'draft', False, _('set changeset phase to draft')),
4268 ('d', 'draft', False, _('set changeset phase to draft')),
4268 ('s', 'secret', False, _('set changeset phase to secret')),
4269 ('s', 'secret', False, _('set changeset phase to secret')),
4269 ('f', 'force', False, _('allow to move boundary backward')),
4270 ('f', 'force', False, _('allow to move boundary backward')),
4270 ('r', 'rev', [], _('target revision'), _('REV')),
4271 ('r', 'rev', [], _('target revision'), _('REV')),
4271 ],
4272 ],
4272 _('[-p|-d|-s] [-f] [-r] [REV...]'),
4273 _('[-p|-d|-s] [-f] [-r] [REV...]'),
4273 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION)
4274 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION)
4274 def phase(ui, repo, *revs, **opts):
4275 def phase(ui, repo, *revs, **opts):
4275 """set or show the current phase name
4276 """set or show the current phase name
4276
4277
4277 With no argument, show the phase name of the current revision(s).
4278 With no argument, show the phase name of the current revision(s).
4278
4279
4279 With one of -p/--public, -d/--draft or -s/--secret, change the
4280 With one of -p/--public, -d/--draft or -s/--secret, change the
4280 phase value of the specified revisions.
4281 phase value of the specified revisions.
4281
4282
4282 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
4283 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
4283 lower phase to a higher phase. Phases are ordered as follows::
4284 lower phase to a higher phase. Phases are ordered as follows::
4284
4285
4285 public < draft < secret
4286 public < draft < secret
4286
4287
4287 Returns 0 on success, 1 if some phases could not be changed.
4288 Returns 0 on success, 1 if some phases could not be changed.
4288
4289
4289 (For more information about the phases concept, see :hg:`help phases`.)
4290 (For more information about the phases concept, see :hg:`help phases`.)
4290 """
4291 """
4291 opts = pycompat.byteskwargs(opts)
4292 opts = pycompat.byteskwargs(opts)
4292 # search for a unique phase argument
4293 # search for a unique phase argument
4293 targetphase = None
4294 targetphase = None
4294 for idx, name in enumerate(phases.cmdphasenames):
4295 for idx, name in enumerate(phases.cmdphasenames):
4295 if opts[name]:
4296 if opts[name]:
4296 if targetphase is not None:
4297 if targetphase is not None:
4297 raise error.Abort(_('only one phase can be specified'))
4298 raise error.Abort(_('only one phase can be specified'))
4298 targetphase = idx
4299 targetphase = idx
4299
4300
4300 # look for specified revision
4301 # look for specified revision
4301 revs = list(revs)
4302 revs = list(revs)
4302 revs.extend(opts['rev'])
4303 revs.extend(opts['rev'])
4303 if not revs:
4304 if not revs:
4304 # display both parents as the second parent phase can influence
4305 # display both parents as the second parent phase can influence
4305 # the phase of a merge commit
4306 # the phase of a merge commit
4306 revs = [c.rev() for c in repo[None].parents()]
4307 revs = [c.rev() for c in repo[None].parents()]
4307
4308
4308 revs = scmutil.revrange(repo, revs)
4309 revs = scmutil.revrange(repo, revs)
4309
4310
4310 ret = 0
4311 ret = 0
4311 if targetphase is None:
4312 if targetphase is None:
4312 # display
4313 # display
4313 for r in revs:
4314 for r in revs:
4314 ctx = repo[r]
4315 ctx = repo[r]
4315 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4316 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4316 else:
4317 else:
4317 with repo.lock(), repo.transaction("phase") as tr:
4318 with repo.lock(), repo.transaction("phase") as tr:
4318 # set phase
4319 # set phase
4319 if not revs:
4320 if not revs:
4320 raise error.Abort(_('empty revision set'))
4321 raise error.Abort(_('empty revision set'))
4321 nodes = [repo[r].node() for r in revs]
4322 nodes = [repo[r].node() for r in revs]
4322 # moving revision from public to draft may hide them
4323 # moving revision from public to draft may hide them
4323 # We have to check result on an unfiltered repository
4324 # We have to check result on an unfiltered repository
4324 unfi = repo.unfiltered()
4325 unfi = repo.unfiltered()
4325 getphase = unfi._phasecache.phase
4326 getphase = unfi._phasecache.phase
4326 olddata = [getphase(unfi, r) for r in unfi]
4327 olddata = [getphase(unfi, r) for r in unfi]
4327 phases.advanceboundary(repo, tr, targetphase, nodes)
4328 phases.advanceboundary(repo, tr, targetphase, nodes)
4328 if opts['force']:
4329 if opts['force']:
4329 phases.retractboundary(repo, tr, targetphase, nodes)
4330 phases.retractboundary(repo, tr, targetphase, nodes)
4330 getphase = unfi._phasecache.phase
4331 getphase = unfi._phasecache.phase
4331 newdata = [getphase(unfi, r) for r in unfi]
4332 newdata = [getphase(unfi, r) for r in unfi]
4332 changes = sum(newdata[r] != olddata[r] for r in unfi)
4333 changes = sum(newdata[r] != olddata[r] for r in unfi)
4333 cl = unfi.changelog
4334 cl = unfi.changelog
4334 rejected = [n for n in nodes
4335 rejected = [n for n in nodes
4335 if newdata[cl.rev(n)] < targetphase]
4336 if newdata[cl.rev(n)] < targetphase]
4336 if rejected:
4337 if rejected:
4337 ui.warn(_('cannot move %i changesets to a higher '
4338 ui.warn(_('cannot move %i changesets to a higher '
4338 'phase, use --force\n') % len(rejected))
4339 'phase, use --force\n') % len(rejected))
4339 ret = 1
4340 ret = 1
4340 if changes:
4341 if changes:
4341 msg = _('phase changed for %i changesets\n') % changes
4342 msg = _('phase changed for %i changesets\n') % changes
4342 if ret:
4343 if ret:
4343 ui.status(msg)
4344 ui.status(msg)
4344 else:
4345 else:
4345 ui.note(msg)
4346 ui.note(msg)
4346 else:
4347 else:
4347 ui.warn(_('no phases changed\n'))
4348 ui.warn(_('no phases changed\n'))
4348 return ret
4349 return ret
4349
4350
4350 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
4351 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
4351 """Run after a changegroup has been added via pull/unbundle
4352 """Run after a changegroup has been added via pull/unbundle
4352
4353
4353 This takes arguments below:
4354 This takes arguments below:
4354
4355
4355 :modheads: change of heads by pull/unbundle
4356 :modheads: change of heads by pull/unbundle
4356 :optupdate: updating working directory is needed or not
4357 :optupdate: updating working directory is needed or not
4357 :checkout: update destination revision (or None to default destination)
4358 :checkout: update destination revision (or None to default destination)
4358 :brev: a name, which might be a bookmark to be activated after updating
4359 :brev: a name, which might be a bookmark to be activated after updating
4359 """
4360 """
4360 if modheads == 0:
4361 if modheads == 0:
4361 return
4362 return
4362 if optupdate:
4363 if optupdate:
4363 try:
4364 try:
4364 return hg.updatetotally(ui, repo, checkout, brev)
4365 return hg.updatetotally(ui, repo, checkout, brev)
4365 except error.UpdateAbort as inst:
4366 except error.UpdateAbort as inst:
4366 msg = _("not updating: %s") % stringutil.forcebytestr(inst)
4367 msg = _("not updating: %s") % stringutil.forcebytestr(inst)
4367 hint = inst.hint
4368 hint = inst.hint
4368 raise error.UpdateAbort(msg, hint=hint)
4369 raise error.UpdateAbort(msg, hint=hint)
4369 if modheads is not None and modheads > 1:
4370 if modheads is not None and modheads > 1:
4370 currentbranchheads = len(repo.branchheads())
4371 currentbranchheads = len(repo.branchheads())
4371 if currentbranchheads == modheads:
4372 if currentbranchheads == modheads:
4372 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4373 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4373 elif currentbranchheads > 1:
4374 elif currentbranchheads > 1:
4374 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4375 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4375 "merge)\n"))
4376 "merge)\n"))
4376 else:
4377 else:
4377 ui.status(_("(run 'hg heads' to see heads)\n"))
4378 ui.status(_("(run 'hg heads' to see heads)\n"))
4378 elif not ui.configbool('commands', 'update.requiredest'):
4379 elif not ui.configbool('commands', 'update.requiredest'):
4379 ui.status(_("(run 'hg update' to get a working copy)\n"))
4380 ui.status(_("(run 'hg update' to get a working copy)\n"))
4380
4381
4381 @command('pull',
4382 @command('pull',
4382 [('u', 'update', None,
4383 [('u', 'update', None,
4383 _('update to new branch head if new descendants were pulled')),
4384 _('update to new branch head if new descendants were pulled')),
4384 ('f', 'force', None, _('run even when remote repository is unrelated')),
4385 ('f', 'force', None, _('run even when remote repository is unrelated')),
4385 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4386 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4386 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4387 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4387 ('b', 'branch', [], _('a specific branch you would like to pull'),
4388 ('b', 'branch', [], _('a specific branch you would like to pull'),
4388 _('BRANCH')),
4389 _('BRANCH')),
4389 ] + remoteopts,
4390 ] + remoteopts,
4390 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'),
4391 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'),
4391 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4392 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4392 helpbasic=True)
4393 helpbasic=True)
4393 def pull(ui, repo, source="default", **opts):
4394 def pull(ui, repo, source="default", **opts):
4394 """pull changes from the specified source
4395 """pull changes from the specified source
4395
4396
4396 Pull changes from a remote repository to a local one.
4397 Pull changes from a remote repository to a local one.
4397
4398
4398 This finds all changes from the repository at the specified path
4399 This finds all changes from the repository at the specified path
4399 or URL and adds them to a local repository (the current one unless
4400 or URL and adds them to a local repository (the current one unless
4400 -R is specified). By default, this does not update the copy of the
4401 -R is specified). By default, this does not update the copy of the
4401 project in the working directory.
4402 project in the working directory.
4402
4403
4403 When cloning from servers that support it, Mercurial may fetch
4404 When cloning from servers that support it, Mercurial may fetch
4404 pre-generated data. When this is done, hooks operating on incoming
4405 pre-generated data. When this is done, hooks operating on incoming
4405 changesets and changegroups may fire more than once, once for each
4406 changesets and changegroups may fire more than once, once for each
4406 pre-generated bundle and as well as for any additional remaining
4407 pre-generated bundle and as well as for any additional remaining
4407 data. See :hg:`help -e clonebundles` for more.
4408 data. See :hg:`help -e clonebundles` for more.
4408
4409
4409 Use :hg:`incoming` if you want to see what would have been added
4410 Use :hg:`incoming` if you want to see what would have been added
4410 by a pull at the time you issued this command. If you then decide
4411 by a pull at the time you issued this command. If you then decide
4411 to add those changes to the repository, you should use :hg:`pull
4412 to add those changes to the repository, you should use :hg:`pull
4412 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4413 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4413
4414
4414 If SOURCE is omitted, the 'default' path will be used.
4415 If SOURCE is omitted, the 'default' path will be used.
4415 See :hg:`help urls` for more information.
4416 See :hg:`help urls` for more information.
4416
4417
4417 Specifying bookmark as ``.`` is equivalent to specifying the active
4418 Specifying bookmark as ``.`` is equivalent to specifying the active
4418 bookmark's name.
4419 bookmark's name.
4419
4420
4420 Returns 0 on success, 1 if an update had unresolved files.
4421 Returns 0 on success, 1 if an update had unresolved files.
4421 """
4422 """
4422
4423
4423 opts = pycompat.byteskwargs(opts)
4424 opts = pycompat.byteskwargs(opts)
4424 if ui.configbool('commands', 'update.requiredest') and opts.get('update'):
4425 if ui.configbool('commands', 'update.requiredest') and opts.get('update'):
4425 msg = _('update destination required by configuration')
4426 msg = _('update destination required by configuration')
4426 hint = _('use hg pull followed by hg update DEST')
4427 hint = _('use hg pull followed by hg update DEST')
4427 raise error.Abort(msg, hint=hint)
4428 raise error.Abort(msg, hint=hint)
4428
4429
4429 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4430 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4430 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4431 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4431 other = hg.peer(repo, opts, source)
4432 other = hg.peer(repo, opts, source)
4432 try:
4433 try:
4433 revs, checkout = hg.addbranchrevs(repo, other, branches,
4434 revs, checkout = hg.addbranchrevs(repo, other, branches,
4434 opts.get('rev'))
4435 opts.get('rev'))
4435
4436
4436 pullopargs = {}
4437 pullopargs = {}
4437
4438
4438 nodes = None
4439 nodes = None
4439 if opts.get('bookmark') or revs:
4440 if opts.get('bookmark') or revs:
4440 # The list of bookmark used here is the same used to actually update
4441 # The list of bookmark used here is the same used to actually update
4441 # the bookmark names, to avoid the race from issue 4689 and we do
4442 # the bookmark names, to avoid the race from issue 4689 and we do
4442 # all lookup and bookmark queries in one go so they see the same
4443 # all lookup and bookmark queries in one go so they see the same
4443 # version of the server state (issue 4700).
4444 # version of the server state (issue 4700).
4444 nodes = []
4445 nodes = []
4445 fnodes = []
4446 fnodes = []
4446 revs = revs or []
4447 revs = revs or []
4447 if revs and not other.capable('lookup'):
4448 if revs and not other.capable('lookup'):
4448 err = _("other repository doesn't support revision lookup, "
4449 err = _("other repository doesn't support revision lookup, "
4449 "so a rev cannot be specified.")
4450 "so a rev cannot be specified.")
4450 raise error.Abort(err)
4451 raise error.Abort(err)
4451 with other.commandexecutor() as e:
4452 with other.commandexecutor() as e:
4452 fremotebookmarks = e.callcommand('listkeys', {
4453 fremotebookmarks = e.callcommand('listkeys', {
4453 'namespace': 'bookmarks'
4454 'namespace': 'bookmarks'
4454 })
4455 })
4455 for r in revs:
4456 for r in revs:
4456 fnodes.append(e.callcommand('lookup', {'key': r}))
4457 fnodes.append(e.callcommand('lookup', {'key': r}))
4457 remotebookmarks = fremotebookmarks.result()
4458 remotebookmarks = fremotebookmarks.result()
4458 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
4459 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
4459 pullopargs['remotebookmarks'] = remotebookmarks
4460 pullopargs['remotebookmarks'] = remotebookmarks
4460 for b in opts.get('bookmark', []):
4461 for b in opts.get('bookmark', []):
4461 b = repo._bookmarks.expandname(b)
4462 b = repo._bookmarks.expandname(b)
4462 if b not in remotebookmarks:
4463 if b not in remotebookmarks:
4463 raise error.Abort(_('remote bookmark %s not found!') % b)
4464 raise error.Abort(_('remote bookmark %s not found!') % b)
4464 nodes.append(remotebookmarks[b])
4465 nodes.append(remotebookmarks[b])
4465 for i, rev in enumerate(revs):
4466 for i, rev in enumerate(revs):
4466 node = fnodes[i].result()
4467 node = fnodes[i].result()
4467 nodes.append(node)
4468 nodes.append(node)
4468 if rev == checkout:
4469 if rev == checkout:
4469 checkout = node
4470 checkout = node
4470
4471
4471 wlock = util.nullcontextmanager()
4472 wlock = util.nullcontextmanager()
4472 if opts.get('update'):
4473 if opts.get('update'):
4473 wlock = repo.wlock()
4474 wlock = repo.wlock()
4474 with wlock:
4475 with wlock:
4475 pullopargs.update(opts.get('opargs', {}))
4476 pullopargs.update(opts.get('opargs', {}))
4476 modheads = exchange.pull(repo, other, heads=nodes,
4477 modheads = exchange.pull(repo, other, heads=nodes,
4477 force=opts.get('force'),
4478 force=opts.get('force'),
4478 bookmarks=opts.get('bookmark', ()),
4479 bookmarks=opts.get('bookmark', ()),
4479 opargs=pullopargs).cgresult
4480 opargs=pullopargs).cgresult
4480
4481
4481 # brev is a name, which might be a bookmark to be activated at
4482 # brev is a name, which might be a bookmark to be activated at
4482 # the end of the update. In other words, it is an explicit
4483 # the end of the update. In other words, it is an explicit
4483 # destination of the update
4484 # destination of the update
4484 brev = None
4485 brev = None
4485
4486
4486 if checkout:
4487 if checkout:
4487 checkout = repo.changelog.rev(checkout)
4488 checkout = repo.changelog.rev(checkout)
4488
4489
4489 # order below depends on implementation of
4490 # order below depends on implementation of
4490 # hg.addbranchrevs(). opts['bookmark'] is ignored,
4491 # hg.addbranchrevs(). opts['bookmark'] is ignored,
4491 # because 'checkout' is determined without it.
4492 # because 'checkout' is determined without it.
4492 if opts.get('rev'):
4493 if opts.get('rev'):
4493 brev = opts['rev'][0]
4494 brev = opts['rev'][0]
4494 elif opts.get('branch'):
4495 elif opts.get('branch'):
4495 brev = opts['branch'][0]
4496 brev = opts['branch'][0]
4496 else:
4497 else:
4497 brev = branches[0]
4498 brev = branches[0]
4498 repo._subtoppath = source
4499 repo._subtoppath = source
4499 try:
4500 try:
4500 ret = postincoming(ui, repo, modheads, opts.get('update'),
4501 ret = postincoming(ui, repo, modheads, opts.get('update'),
4501 checkout, brev)
4502 checkout, brev)
4502
4503
4503 finally:
4504 finally:
4504 del repo._subtoppath
4505 del repo._subtoppath
4505
4506
4506 finally:
4507 finally:
4507 other.close()
4508 other.close()
4508 return ret
4509 return ret
4509
4510
4510 @command('push',
4511 @command('push',
4511 [('f', 'force', None, _('force push')),
4512 [('f', 'force', None, _('force push')),
4512 ('r', 'rev', [],
4513 ('r', 'rev', [],
4513 _('a changeset intended to be included in the destination'),
4514 _('a changeset intended to be included in the destination'),
4514 _('REV')),
4515 _('REV')),
4515 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4516 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4516 ('b', 'branch', [],
4517 ('b', 'branch', [],
4517 _('a specific branch you would like to push'), _('BRANCH')),
4518 _('a specific branch you would like to push'), _('BRANCH')),
4518 ('', 'new-branch', False, _('allow pushing a new branch')),
4519 ('', 'new-branch', False, _('allow pushing a new branch')),
4519 ('', 'pushvars', [], _('variables that can be sent to server (ADVANCED)')),
4520 ('', 'pushvars', [], _('variables that can be sent to server (ADVANCED)')),
4520 ('', 'publish', False, _('push the changeset as public (EXPERIMENTAL)')),
4521 ('', 'publish', False, _('push the changeset as public (EXPERIMENTAL)')),
4521 ] + remoteopts,
4522 ] + remoteopts,
4522 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'),
4523 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'),
4523 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4524 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4524 helpbasic=True)
4525 helpbasic=True)
4525 def push(ui, repo, dest=None, **opts):
4526 def push(ui, repo, dest=None, **opts):
4526 """push changes to the specified destination
4527 """push changes to the specified destination
4527
4528
4528 Push changesets from the local repository to the specified
4529 Push changesets from the local repository to the specified
4529 destination.
4530 destination.
4530
4531
4531 This operation is symmetrical to pull: it is identical to a pull
4532 This operation is symmetrical to pull: it is identical to a pull
4532 in the destination repository from the current one.
4533 in the destination repository from the current one.
4533
4534
4534 By default, push will not allow creation of new heads at the
4535 By default, push will not allow creation of new heads at the
4535 destination, since multiple heads would make it unclear which head
4536 destination, since multiple heads would make it unclear which head
4536 to use. In this situation, it is recommended to pull and merge
4537 to use. In this situation, it is recommended to pull and merge
4537 before pushing.
4538 before pushing.
4538
4539
4539 Use --new-branch if you want to allow push to create a new named
4540 Use --new-branch if you want to allow push to create a new named
4540 branch that is not present at the destination. This allows you to
4541 branch that is not present at the destination. This allows you to
4541 only create a new branch without forcing other changes.
4542 only create a new branch without forcing other changes.
4542
4543
4543 .. note::
4544 .. note::
4544
4545
4545 Extra care should be taken with the -f/--force option,
4546 Extra care should be taken with the -f/--force option,
4546 which will push all new heads on all branches, an action which will
4547 which will push all new heads on all branches, an action which will
4547 almost always cause confusion for collaborators.
4548 almost always cause confusion for collaborators.
4548
4549
4549 If -r/--rev is used, the specified revision and all its ancestors
4550 If -r/--rev is used, the specified revision and all its ancestors
4550 will be pushed to the remote repository.
4551 will be pushed to the remote repository.
4551
4552
4552 If -B/--bookmark is used, the specified bookmarked revision, its
4553 If -B/--bookmark is used, the specified bookmarked revision, its
4553 ancestors, and the bookmark will be pushed to the remote
4554 ancestors, and the bookmark will be pushed to the remote
4554 repository. Specifying ``.`` is equivalent to specifying the active
4555 repository. Specifying ``.`` is equivalent to specifying the active
4555 bookmark's name.
4556 bookmark's name.
4556
4557
4557 Please see :hg:`help urls` for important details about ``ssh://``
4558 Please see :hg:`help urls` for important details about ``ssh://``
4558 URLs. If DESTINATION is omitted, a default path will be used.
4559 URLs. If DESTINATION is omitted, a default path will be used.
4559
4560
4560 .. container:: verbose
4561 .. container:: verbose
4561
4562
4562 The --pushvars option sends strings to the server that become
4563 The --pushvars option sends strings to the server that become
4563 environment variables prepended with ``HG_USERVAR_``. For example,
4564 environment variables prepended with ``HG_USERVAR_``. For example,
4564 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
4565 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
4565 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
4566 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
4566
4567
4567 pushvars can provide for user-overridable hooks as well as set debug
4568 pushvars can provide for user-overridable hooks as well as set debug
4568 levels. One example is having a hook that blocks commits containing
4569 levels. One example is having a hook that blocks commits containing
4569 conflict markers, but enables the user to override the hook if the file
4570 conflict markers, but enables the user to override the hook if the file
4570 is using conflict markers for testing purposes or the file format has
4571 is using conflict markers for testing purposes or the file format has
4571 strings that look like conflict markers.
4572 strings that look like conflict markers.
4572
4573
4573 By default, servers will ignore `--pushvars`. To enable it add the
4574 By default, servers will ignore `--pushvars`. To enable it add the
4574 following to your configuration file::
4575 following to your configuration file::
4575
4576
4576 [push]
4577 [push]
4577 pushvars.server = true
4578 pushvars.server = true
4578
4579
4579 Returns 0 if push was successful, 1 if nothing to push.
4580 Returns 0 if push was successful, 1 if nothing to push.
4580 """
4581 """
4581
4582
4582 opts = pycompat.byteskwargs(opts)
4583 opts = pycompat.byteskwargs(opts)
4583 if opts.get('bookmark'):
4584 if opts.get('bookmark'):
4584 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4585 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4585 for b in opts['bookmark']:
4586 for b in opts['bookmark']:
4586 # translate -B options to -r so changesets get pushed
4587 # translate -B options to -r so changesets get pushed
4587 b = repo._bookmarks.expandname(b)
4588 b = repo._bookmarks.expandname(b)
4588 if b in repo._bookmarks:
4589 if b in repo._bookmarks:
4589 opts.setdefault('rev', []).append(b)
4590 opts.setdefault('rev', []).append(b)
4590 else:
4591 else:
4591 # if we try to push a deleted bookmark, translate it to null
4592 # if we try to push a deleted bookmark, translate it to null
4592 # this lets simultaneous -r, -b options continue working
4593 # this lets simultaneous -r, -b options continue working
4593 opts.setdefault('rev', []).append("null")
4594 opts.setdefault('rev', []).append("null")
4594
4595
4595 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4596 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4596 if not path:
4597 if not path:
4597 raise error.Abort(_('default repository not configured!'),
4598 raise error.Abort(_('default repository not configured!'),
4598 hint=_("see 'hg help config.paths'"))
4599 hint=_("see 'hg help config.paths'"))
4599 dest = path.pushloc or path.loc
4600 dest = path.pushloc or path.loc
4600 branches = (path.branch, opts.get('branch') or [])
4601 branches = (path.branch, opts.get('branch') or [])
4601 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4602 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4602 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4603 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4603 other = hg.peer(repo, opts, dest)
4604 other = hg.peer(repo, opts, dest)
4604
4605
4605 if revs:
4606 if revs:
4606 revs = [repo[r].node() for r in scmutil.revrange(repo, revs)]
4607 revs = [repo[r].node() for r in scmutil.revrange(repo, revs)]
4607 if not revs:
4608 if not revs:
4608 raise error.Abort(_("specified revisions evaluate to an empty set"),
4609 raise error.Abort(_("specified revisions evaluate to an empty set"),
4609 hint=_("use different revision arguments"))
4610 hint=_("use different revision arguments"))
4610 elif path.pushrev:
4611 elif path.pushrev:
4611 # It doesn't make any sense to specify ancestor revisions. So limit
4612 # It doesn't make any sense to specify ancestor revisions. So limit
4612 # to DAG heads to make discovery simpler.
4613 # to DAG heads to make discovery simpler.
4613 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4614 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4614 revs = scmutil.revrange(repo, [expr])
4615 revs = scmutil.revrange(repo, [expr])
4615 revs = [repo[rev].node() for rev in revs]
4616 revs = [repo[rev].node() for rev in revs]
4616 if not revs:
4617 if not revs:
4617 raise error.Abort(_('default push revset for path evaluates to an '
4618 raise error.Abort(_('default push revset for path evaluates to an '
4618 'empty set'))
4619 'empty set'))
4619
4620
4620 repo._subtoppath = dest
4621 repo._subtoppath = dest
4621 try:
4622 try:
4622 # push subrepos depth-first for coherent ordering
4623 # push subrepos depth-first for coherent ordering
4623 c = repo['.']
4624 c = repo['.']
4624 subs = c.substate # only repos that are committed
4625 subs = c.substate # only repos that are committed
4625 for s in sorted(subs):
4626 for s in sorted(subs):
4626 result = c.sub(s).push(opts)
4627 result = c.sub(s).push(opts)
4627 if result == 0:
4628 if result == 0:
4628 return not result
4629 return not result
4629 finally:
4630 finally:
4630 del repo._subtoppath
4631 del repo._subtoppath
4631
4632
4632 opargs = dict(opts.get('opargs', {})) # copy opargs since we may mutate it
4633 opargs = dict(opts.get('opargs', {})) # copy opargs since we may mutate it
4633 opargs.setdefault('pushvars', []).extend(opts.get('pushvars', []))
4634 opargs.setdefault('pushvars', []).extend(opts.get('pushvars', []))
4634
4635
4635 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4636 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4636 newbranch=opts.get('new_branch'),
4637 newbranch=opts.get('new_branch'),
4637 bookmarks=opts.get('bookmark', ()),
4638 bookmarks=opts.get('bookmark', ()),
4638 publish=opts.get('publish'),
4639 publish=opts.get('publish'),
4639 opargs=opargs)
4640 opargs=opargs)
4640
4641
4641 result = not pushop.cgresult
4642 result = not pushop.cgresult
4642
4643
4643 if pushop.bkresult is not None:
4644 if pushop.bkresult is not None:
4644 if pushop.bkresult == 2:
4645 if pushop.bkresult == 2:
4645 result = 2
4646 result = 2
4646 elif not result and pushop.bkresult:
4647 elif not result and pushop.bkresult:
4647 result = 2
4648 result = 2
4648
4649
4649 return result
4650 return result
4650
4651
4651 @command('recover', [], helpcategory=command.CATEGORY_MAINTENANCE)
4652 @command('recover', [], helpcategory=command.CATEGORY_MAINTENANCE)
4652 def recover(ui, repo):
4653 def recover(ui, repo):
4653 """roll back an interrupted transaction
4654 """roll back an interrupted transaction
4654
4655
4655 Recover from an interrupted commit or pull.
4656 Recover from an interrupted commit or pull.
4656
4657
4657 This command tries to fix the repository status after an
4658 This command tries to fix the repository status after an
4658 interrupted operation. It should only be necessary when Mercurial
4659 interrupted operation. It should only be necessary when Mercurial
4659 suggests it.
4660 suggests it.
4660
4661
4661 Returns 0 if successful, 1 if nothing to recover or verify fails.
4662 Returns 0 if successful, 1 if nothing to recover or verify fails.
4662 """
4663 """
4663 if repo.recover():
4664 if repo.recover():
4664 return hg.verify(repo)
4665 return hg.verify(repo)
4665 return 1
4666 return 1
4666
4667
4667 @command('remove|rm',
4668 @command('remove|rm',
4668 [('A', 'after', None, _('record delete for missing files')),
4669 [('A', 'after', None, _('record delete for missing files')),
4669 ('f', 'force', None,
4670 ('f', 'force', None,
4670 _('forget added files, delete modified files')),
4671 _('forget added files, delete modified files')),
4671 ] + subrepoopts + walkopts + dryrunopts,
4672 ] + subrepoopts + walkopts + dryrunopts,
4672 _('[OPTION]... FILE...'),
4673 _('[OPTION]... FILE...'),
4673 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4674 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4674 helpbasic=True, inferrepo=True)
4675 helpbasic=True, inferrepo=True)
4675 def remove(ui, repo, *pats, **opts):
4676 def remove(ui, repo, *pats, **opts):
4676 """remove the specified files on the next commit
4677 """remove the specified files on the next commit
4677
4678
4678 Schedule the indicated files for removal from the current branch.
4679 Schedule the indicated files for removal from the current branch.
4679
4680
4680 This command schedules the files to be removed at the next commit.
4681 This command schedules the files to be removed at the next commit.
4681 To undo a remove before that, see :hg:`revert`. To undo added
4682 To undo a remove before that, see :hg:`revert`. To undo added
4682 files, see :hg:`forget`.
4683 files, see :hg:`forget`.
4683
4684
4684 .. container:: verbose
4685 .. container:: verbose
4685
4686
4686 -A/--after can be used to remove only files that have already
4687 -A/--after can be used to remove only files that have already
4687 been deleted, -f/--force can be used to force deletion, and -Af
4688 been deleted, -f/--force can be used to force deletion, and -Af
4688 can be used to remove files from the next revision without
4689 can be used to remove files from the next revision without
4689 deleting them from the working directory.
4690 deleting them from the working directory.
4690
4691
4691 The following table details the behavior of remove for different
4692 The following table details the behavior of remove for different
4692 file states (columns) and option combinations (rows). The file
4693 file states (columns) and option combinations (rows). The file
4693 states are Added [A], Clean [C], Modified [M] and Missing [!]
4694 states are Added [A], Clean [C], Modified [M] and Missing [!]
4694 (as reported by :hg:`status`). The actions are Warn, Remove
4695 (as reported by :hg:`status`). The actions are Warn, Remove
4695 (from branch) and Delete (from disk):
4696 (from branch) and Delete (from disk):
4696
4697
4697 ========= == == == ==
4698 ========= == == == ==
4698 opt/state A C M !
4699 opt/state A C M !
4699 ========= == == == ==
4700 ========= == == == ==
4700 none W RD W R
4701 none W RD W R
4701 -f R RD RD R
4702 -f R RD RD R
4702 -A W W W R
4703 -A W W W R
4703 -Af R R R R
4704 -Af R R R R
4704 ========= == == == ==
4705 ========= == == == ==
4705
4706
4706 .. note::
4707 .. note::
4707
4708
4708 :hg:`remove` never deletes files in Added [A] state from the
4709 :hg:`remove` never deletes files in Added [A] state from the
4709 working directory, not even if ``--force`` is specified.
4710 working directory, not even if ``--force`` is specified.
4710
4711
4711 Returns 0 on success, 1 if any warnings encountered.
4712 Returns 0 on success, 1 if any warnings encountered.
4712 """
4713 """
4713
4714
4714 opts = pycompat.byteskwargs(opts)
4715 opts = pycompat.byteskwargs(opts)
4715 after, force = opts.get('after'), opts.get('force')
4716 after, force = opts.get('after'), opts.get('force')
4716 dryrun = opts.get('dry_run')
4717 dryrun = opts.get('dry_run')
4717 if not pats and not after:
4718 if not pats and not after:
4718 raise error.Abort(_('no files specified'))
4719 raise error.Abort(_('no files specified'))
4719
4720
4720 m = scmutil.match(repo[None], pats, opts)
4721 m = scmutil.match(repo[None], pats, opts)
4721 subrepos = opts.get('subrepos')
4722 subrepos = opts.get('subrepos')
4722 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=True)
4723 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=True)
4723 return cmdutil.remove(ui, repo, m, "", uipathfn, after, force, subrepos,
4724 return cmdutil.remove(ui, repo, m, "", uipathfn, after, force, subrepos,
4724 dryrun=dryrun)
4725 dryrun=dryrun)
4725
4726
4726 @command('rename|move|mv',
4727 @command('rename|move|mv',
4727 [('A', 'after', None, _('record a rename that has already occurred')),
4728 [('A', 'after', None, _('record a rename that has already occurred')),
4728 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4729 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4729 ] + walkopts + dryrunopts,
4730 ] + walkopts + dryrunopts,
4730 _('[OPTION]... SOURCE... DEST'),
4731 _('[OPTION]... SOURCE... DEST'),
4731 helpcategory=command.CATEGORY_WORKING_DIRECTORY)
4732 helpcategory=command.CATEGORY_WORKING_DIRECTORY)
4732 def rename(ui, repo, *pats, **opts):
4733 def rename(ui, repo, *pats, **opts):
4733 """rename files; equivalent of copy + remove
4734 """rename files; equivalent of copy + remove
4734
4735
4735 Mark dest as copies of sources; mark sources for deletion. If dest
4736 Mark dest as copies of sources; mark sources for deletion. If dest
4736 is a directory, copies are put in that directory. If dest is a
4737 is a directory, copies are put in that directory. If dest is a
4737 file, there can only be one source.
4738 file, there can only be one source.
4738
4739
4739 By default, this command copies the contents of files as they
4740 By default, this command copies the contents of files as they
4740 exist in the working directory. If invoked with -A/--after, the
4741 exist in the working directory. If invoked with -A/--after, the
4741 operation is recorded, but no copying is performed.
4742 operation is recorded, but no copying is performed.
4742
4743
4743 This command takes effect at the next commit. To undo a rename
4744 This command takes effect at the next commit. To undo a rename
4744 before that, see :hg:`revert`.
4745 before that, see :hg:`revert`.
4745
4746
4746 Returns 0 on success, 1 if errors are encountered.
4747 Returns 0 on success, 1 if errors are encountered.
4747 """
4748 """
4748 opts = pycompat.byteskwargs(opts)
4749 opts = pycompat.byteskwargs(opts)
4749 with repo.wlock(False):
4750 with repo.wlock(False):
4750 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4751 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4751
4752
4752 @command('resolve',
4753 @command('resolve',
4753 [('a', 'all', None, _('select all unresolved files')),
4754 [('a', 'all', None, _('select all unresolved files')),
4754 ('l', 'list', None, _('list state of files needing merge')),
4755 ('l', 'list', None, _('list state of files needing merge')),
4755 ('m', 'mark', None, _('mark files as resolved')),
4756 ('m', 'mark', None, _('mark files as resolved')),
4756 ('u', 'unmark', None, _('mark files as unresolved')),
4757 ('u', 'unmark', None, _('mark files as unresolved')),
4757 ('n', 'no-status', None, _('hide status prefix')),
4758 ('n', 'no-status', None, _('hide status prefix')),
4758 ('', 're-merge', None, _('re-merge files'))]
4759 ('', 're-merge', None, _('re-merge files'))]
4759 + mergetoolopts + walkopts + formatteropts,
4760 + mergetoolopts + walkopts + formatteropts,
4760 _('[OPTION]... [FILE]...'),
4761 _('[OPTION]... [FILE]...'),
4761 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4762 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4762 inferrepo=True)
4763 inferrepo=True)
4763 def resolve(ui, repo, *pats, **opts):
4764 def resolve(ui, repo, *pats, **opts):
4764 """redo merges or set/view the merge status of files
4765 """redo merges or set/view the merge status of files
4765
4766
4766 Merges with unresolved conflicts are often the result of
4767 Merges with unresolved conflicts are often the result of
4767 non-interactive merging using the ``internal:merge`` configuration
4768 non-interactive merging using the ``internal:merge`` configuration
4768 setting, or a command-line merge tool like ``diff3``. The resolve
4769 setting, or a command-line merge tool like ``diff3``. The resolve
4769 command is used to manage the files involved in a merge, after
4770 command is used to manage the files involved in a merge, after
4770 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4771 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4771 working directory must have two parents). See :hg:`help
4772 working directory must have two parents). See :hg:`help
4772 merge-tools` for information on configuring merge tools.
4773 merge-tools` for information on configuring merge tools.
4773
4774
4774 The resolve command can be used in the following ways:
4775 The resolve command can be used in the following ways:
4775
4776
4776 - :hg:`resolve [--re-merge] [--tool TOOL] FILE...`: attempt to re-merge
4777 - :hg:`resolve [--re-merge] [--tool TOOL] FILE...`: attempt to re-merge
4777 the specified files, discarding any previous merge attempts. Re-merging
4778 the specified files, discarding any previous merge attempts. Re-merging
4778 is not performed for files already marked as resolved. Use ``--all/-a``
4779 is not performed for files already marked as resolved. Use ``--all/-a``
4779 to select all unresolved files. ``--tool`` can be used to specify
4780 to select all unresolved files. ``--tool`` can be used to specify
4780 the merge tool used for the given files. It overrides the HGMERGE
4781 the merge tool used for the given files. It overrides the HGMERGE
4781 environment variable and your configuration files. Previous file
4782 environment variable and your configuration files. Previous file
4782 contents are saved with a ``.orig`` suffix.
4783 contents are saved with a ``.orig`` suffix.
4783
4784
4784 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4785 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4785 (e.g. after having manually fixed-up the files). The default is
4786 (e.g. after having manually fixed-up the files). The default is
4786 to mark all unresolved files.
4787 to mark all unresolved files.
4787
4788
4788 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4789 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4789 default is to mark all resolved files.
4790 default is to mark all resolved files.
4790
4791
4791 - :hg:`resolve -l`: list files which had or still have conflicts.
4792 - :hg:`resolve -l`: list files which had or still have conflicts.
4792 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4793 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4793 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4794 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4794 the list. See :hg:`help filesets` for details.
4795 the list. See :hg:`help filesets` for details.
4795
4796
4796 .. note::
4797 .. note::
4797
4798
4798 Mercurial will not let you commit files with unresolved merge
4799 Mercurial will not let you commit files with unresolved merge
4799 conflicts. You must use :hg:`resolve -m ...` before you can
4800 conflicts. You must use :hg:`resolve -m ...` before you can
4800 commit after a conflicting merge.
4801 commit after a conflicting merge.
4801
4802
4802 .. container:: verbose
4803 .. container:: verbose
4803
4804
4804 Template:
4805 Template:
4805
4806
4806 The following keywords are supported in addition to the common template
4807 The following keywords are supported in addition to the common template
4807 keywords and functions. See also :hg:`help templates`.
4808 keywords and functions. See also :hg:`help templates`.
4808
4809
4809 :mergestatus: String. Character denoting merge conflicts, ``U`` or ``R``.
4810 :mergestatus: String. Character denoting merge conflicts, ``U`` or ``R``.
4810 :path: String. Repository-absolute path of the file.
4811 :path: String. Repository-absolute path of the file.
4811
4812
4812 Returns 0 on success, 1 if any files fail a resolve attempt.
4813 Returns 0 on success, 1 if any files fail a resolve attempt.
4813 """
4814 """
4814
4815
4815 opts = pycompat.byteskwargs(opts)
4816 opts = pycompat.byteskwargs(opts)
4816 confirm = ui.configbool('commands', 'resolve.confirm')
4817 confirm = ui.configbool('commands', 'resolve.confirm')
4817 flaglist = 'all mark unmark list no_status re_merge'.split()
4818 flaglist = 'all mark unmark list no_status re_merge'.split()
4818 all, mark, unmark, show, nostatus, remerge = \
4819 all, mark, unmark, show, nostatus, remerge = \
4819 [opts.get(o) for o in flaglist]
4820 [opts.get(o) for o in flaglist]
4820
4821
4821 actioncount = len(list(filter(None, [show, mark, unmark, remerge])))
4822 actioncount = len(list(filter(None, [show, mark, unmark, remerge])))
4822 if actioncount > 1:
4823 if actioncount > 1:
4823 raise error.Abort(_("too many actions specified"))
4824 raise error.Abort(_("too many actions specified"))
4824 elif (actioncount == 0
4825 elif (actioncount == 0
4825 and ui.configbool('commands', 'resolve.explicit-re-merge')):
4826 and ui.configbool('commands', 'resolve.explicit-re-merge')):
4826 hint = _('use --mark, --unmark, --list or --re-merge')
4827 hint = _('use --mark, --unmark, --list or --re-merge')
4827 raise error.Abort(_('no action specified'), hint=hint)
4828 raise error.Abort(_('no action specified'), hint=hint)
4828 if pats and all:
4829 if pats and all:
4829 raise error.Abort(_("can't specify --all and patterns"))
4830 raise error.Abort(_("can't specify --all and patterns"))
4830 if not (all or pats or show or mark or unmark):
4831 if not (all or pats or show or mark or unmark):
4831 raise error.Abort(_('no files or directories specified'),
4832 raise error.Abort(_('no files or directories specified'),
4832 hint=('use --all to re-merge all unresolved files'))
4833 hint=('use --all to re-merge all unresolved files'))
4833
4834
4834 if confirm:
4835 if confirm:
4835 if all:
4836 if all:
4836 if ui.promptchoice(_(b're-merge all unresolved files (yn)?'
4837 if ui.promptchoice(_(b're-merge all unresolved files (yn)?'
4837 b'$$ &Yes $$ &No')):
4838 b'$$ &Yes $$ &No')):
4838 raise error.Abort(_('user quit'))
4839 raise error.Abort(_('user quit'))
4839 if mark and not pats:
4840 if mark and not pats:
4840 if ui.promptchoice(_(b'mark all unresolved files as resolved (yn)?'
4841 if ui.promptchoice(_(b'mark all unresolved files as resolved (yn)?'
4841 b'$$ &Yes $$ &No')):
4842 b'$$ &Yes $$ &No')):
4842 raise error.Abort(_('user quit'))
4843 raise error.Abort(_('user quit'))
4843 if unmark and not pats:
4844 if unmark and not pats:
4844 if ui.promptchoice(_(b'mark all resolved files as unresolved (yn)?'
4845 if ui.promptchoice(_(b'mark all resolved files as unresolved (yn)?'
4845 b'$$ &Yes $$ &No')):
4846 b'$$ &Yes $$ &No')):
4846 raise error.Abort(_('user quit'))
4847 raise error.Abort(_('user quit'))
4847
4848
4848 uipathfn = scmutil.getuipathfn(repo)
4849 uipathfn = scmutil.getuipathfn(repo)
4849
4850
4850 if show:
4851 if show:
4851 ui.pager('resolve')
4852 ui.pager('resolve')
4852 fm = ui.formatter('resolve', opts)
4853 fm = ui.formatter('resolve', opts)
4853 ms = mergemod.mergestate.read(repo)
4854 ms = mergemod.mergestate.read(repo)
4854 wctx = repo[None]
4855 wctx = repo[None]
4855 m = scmutil.match(wctx, pats, opts)
4856 m = scmutil.match(wctx, pats, opts)
4856
4857
4857 # Labels and keys based on merge state. Unresolved path conflicts show
4858 # Labels and keys based on merge state. Unresolved path conflicts show
4858 # as 'P'. Resolved path conflicts show as 'R', the same as normal
4859 # as 'P'. Resolved path conflicts show as 'R', the same as normal
4859 # resolved conflicts.
4860 # resolved conflicts.
4860 mergestateinfo = {
4861 mergestateinfo = {
4861 mergemod.MERGE_RECORD_UNRESOLVED: ('resolve.unresolved', 'U'),
4862 mergemod.MERGE_RECORD_UNRESOLVED: ('resolve.unresolved', 'U'),
4862 mergemod.MERGE_RECORD_RESOLVED: ('resolve.resolved', 'R'),
4863 mergemod.MERGE_RECORD_RESOLVED: ('resolve.resolved', 'R'),
4863 mergemod.MERGE_RECORD_UNRESOLVED_PATH: ('resolve.unresolved', 'P'),
4864 mergemod.MERGE_RECORD_UNRESOLVED_PATH: ('resolve.unresolved', 'P'),
4864 mergemod.MERGE_RECORD_RESOLVED_PATH: ('resolve.resolved', 'R'),
4865 mergemod.MERGE_RECORD_RESOLVED_PATH: ('resolve.resolved', 'R'),
4865 mergemod.MERGE_RECORD_DRIVER_RESOLVED: ('resolve.driverresolved',
4866 mergemod.MERGE_RECORD_DRIVER_RESOLVED: ('resolve.driverresolved',
4866 'D'),
4867 'D'),
4867 }
4868 }
4868
4869
4869 for f in ms:
4870 for f in ms:
4870 if not m(f):
4871 if not m(f):
4871 continue
4872 continue
4872
4873
4873 label, key = mergestateinfo[ms[f]]
4874 label, key = mergestateinfo[ms[f]]
4874 fm.startitem()
4875 fm.startitem()
4875 fm.context(ctx=wctx)
4876 fm.context(ctx=wctx)
4876 fm.condwrite(not nostatus, 'mergestatus', '%s ', key, label=label)
4877 fm.condwrite(not nostatus, 'mergestatus', '%s ', key, label=label)
4877 fm.data(path=f)
4878 fm.data(path=f)
4878 fm.plain('%s\n' % uipathfn(f), label=label)
4879 fm.plain('%s\n' % uipathfn(f), label=label)
4879 fm.end()
4880 fm.end()
4880 return 0
4881 return 0
4881
4882
4882 with repo.wlock():
4883 with repo.wlock():
4883 ms = mergemod.mergestate.read(repo)
4884 ms = mergemod.mergestate.read(repo)
4884
4885
4885 if not (ms.active() or repo.dirstate.p2() != nullid):
4886 if not (ms.active() or repo.dirstate.p2() != nullid):
4886 raise error.Abort(
4887 raise error.Abort(
4887 _('resolve command not applicable when not merging'))
4888 _('resolve command not applicable when not merging'))
4888
4889
4889 wctx = repo[None]
4890 wctx = repo[None]
4890
4891
4891 if (ms.mergedriver
4892 if (ms.mergedriver
4892 and ms.mdstate() == mergemod.MERGE_DRIVER_STATE_UNMARKED):
4893 and ms.mdstate() == mergemod.MERGE_DRIVER_STATE_UNMARKED):
4893 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4894 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4894 ms.commit()
4895 ms.commit()
4895 # allow mark and unmark to go through
4896 # allow mark and unmark to go through
4896 if not mark and not unmark and not proceed:
4897 if not mark and not unmark and not proceed:
4897 return 1
4898 return 1
4898
4899
4899 m = scmutil.match(wctx, pats, opts)
4900 m = scmutil.match(wctx, pats, opts)
4900 ret = 0
4901 ret = 0
4901 didwork = False
4902 didwork = False
4902 runconclude = False
4903 runconclude = False
4903
4904
4904 tocomplete = []
4905 tocomplete = []
4905 hasconflictmarkers = []
4906 hasconflictmarkers = []
4906 if mark:
4907 if mark:
4907 markcheck = ui.config('commands', 'resolve.mark-check')
4908 markcheck = ui.config('commands', 'resolve.mark-check')
4908 if markcheck not in ['warn', 'abort']:
4909 if markcheck not in ['warn', 'abort']:
4909 # Treat all invalid / unrecognized values as 'none'.
4910 # Treat all invalid / unrecognized values as 'none'.
4910 markcheck = False
4911 markcheck = False
4911 for f in ms:
4912 for f in ms:
4912 if not m(f):
4913 if not m(f):
4913 continue
4914 continue
4914
4915
4915 didwork = True
4916 didwork = True
4916
4917
4917 # don't let driver-resolved files be marked, and run the conclude
4918 # don't let driver-resolved files be marked, and run the conclude
4918 # step if asked to resolve
4919 # step if asked to resolve
4919 if ms[f] == mergemod.MERGE_RECORD_DRIVER_RESOLVED:
4920 if ms[f] == mergemod.MERGE_RECORD_DRIVER_RESOLVED:
4920 exact = m.exact(f)
4921 exact = m.exact(f)
4921 if mark:
4922 if mark:
4922 if exact:
4923 if exact:
4923 ui.warn(_('not marking %s as it is driver-resolved\n')
4924 ui.warn(_('not marking %s as it is driver-resolved\n')
4924 % f)
4925 % f)
4925 elif unmark:
4926 elif unmark:
4926 if exact:
4927 if exact:
4927 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4928 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4928 % f)
4929 % f)
4929 else:
4930 else:
4930 runconclude = True
4931 runconclude = True
4931 continue
4932 continue
4932
4933
4933 # path conflicts must be resolved manually
4934 # path conflicts must be resolved manually
4934 if ms[f] in (mergemod.MERGE_RECORD_UNRESOLVED_PATH,
4935 if ms[f] in (mergemod.MERGE_RECORD_UNRESOLVED_PATH,
4935 mergemod.MERGE_RECORD_RESOLVED_PATH):
4936 mergemod.MERGE_RECORD_RESOLVED_PATH):
4936 if mark:
4937 if mark:
4937 ms.mark(f, mergemod.MERGE_RECORD_RESOLVED_PATH)
4938 ms.mark(f, mergemod.MERGE_RECORD_RESOLVED_PATH)
4938 elif unmark:
4939 elif unmark:
4939 ms.mark(f, mergemod.MERGE_RECORD_UNRESOLVED_PATH)
4940 ms.mark(f, mergemod.MERGE_RECORD_UNRESOLVED_PATH)
4940 elif ms[f] == mergemod.MERGE_RECORD_UNRESOLVED_PATH:
4941 elif ms[f] == mergemod.MERGE_RECORD_UNRESOLVED_PATH:
4941 ui.warn(_('%s: path conflict must be resolved manually\n')
4942 ui.warn(_('%s: path conflict must be resolved manually\n')
4942 % f)
4943 % f)
4943 continue
4944 continue
4944
4945
4945 if mark:
4946 if mark:
4946 if markcheck:
4947 if markcheck:
4947 fdata = repo.wvfs.tryread(f)
4948 fdata = repo.wvfs.tryread(f)
4948 if filemerge.hasconflictmarkers(fdata) and \
4949 if filemerge.hasconflictmarkers(fdata) and \
4949 ms[f] != mergemod.MERGE_RECORD_RESOLVED:
4950 ms[f] != mergemod.MERGE_RECORD_RESOLVED:
4950 hasconflictmarkers.append(f)
4951 hasconflictmarkers.append(f)
4951 ms.mark(f, mergemod.MERGE_RECORD_RESOLVED)
4952 ms.mark(f, mergemod.MERGE_RECORD_RESOLVED)
4952 elif unmark:
4953 elif unmark:
4953 ms.mark(f, mergemod.MERGE_RECORD_UNRESOLVED)
4954 ms.mark(f, mergemod.MERGE_RECORD_UNRESOLVED)
4954 else:
4955 else:
4955 # backup pre-resolve (merge uses .orig for its own purposes)
4956 # backup pre-resolve (merge uses .orig for its own purposes)
4956 a = repo.wjoin(f)
4957 a = repo.wjoin(f)
4957 try:
4958 try:
4958 util.copyfile(a, a + ".resolve")
4959 util.copyfile(a, a + ".resolve")
4959 except (IOError, OSError) as inst:
4960 except (IOError, OSError) as inst:
4960 if inst.errno != errno.ENOENT:
4961 if inst.errno != errno.ENOENT:
4961 raise
4962 raise
4962
4963
4963 try:
4964 try:
4964 # preresolve file
4965 # preresolve file
4965 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
4966 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
4966 with ui.configoverride(overrides, 'resolve'):
4967 with ui.configoverride(overrides, 'resolve'):
4967 complete, r = ms.preresolve(f, wctx)
4968 complete, r = ms.preresolve(f, wctx)
4968 if not complete:
4969 if not complete:
4969 tocomplete.append(f)
4970 tocomplete.append(f)
4970 elif r:
4971 elif r:
4971 ret = 1
4972 ret = 1
4972 finally:
4973 finally:
4973 ms.commit()
4974 ms.commit()
4974
4975
4975 # replace filemerge's .orig file with our resolve file, but only
4976 # replace filemerge's .orig file with our resolve file, but only
4976 # for merges that are complete
4977 # for merges that are complete
4977 if complete:
4978 if complete:
4978 try:
4979 try:
4979 util.rename(a + ".resolve",
4980 util.rename(a + ".resolve",
4980 scmutil.backuppath(ui, repo, f))
4981 scmutil.backuppath(ui, repo, f))
4981 except OSError as inst:
4982 except OSError as inst:
4982 if inst.errno != errno.ENOENT:
4983 if inst.errno != errno.ENOENT:
4983 raise
4984 raise
4984
4985
4985 if hasconflictmarkers:
4986 if hasconflictmarkers:
4986 ui.warn(_('warning: the following files still have conflict '
4987 ui.warn(_('warning: the following files still have conflict '
4987 'markers:\n ') + '\n '.join(hasconflictmarkers) + '\n')
4988 'markers:\n ') + '\n '.join(hasconflictmarkers) + '\n')
4988 if markcheck == 'abort' and not all and not pats:
4989 if markcheck == 'abort' and not all and not pats:
4989 raise error.Abort(_('conflict markers detected'),
4990 raise error.Abort(_('conflict markers detected'),
4990 hint=_('use --all to mark anyway'))
4991 hint=_('use --all to mark anyway'))
4991
4992
4992 for f in tocomplete:
4993 for f in tocomplete:
4993 try:
4994 try:
4994 # resolve file
4995 # resolve file
4995 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
4996 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
4996 with ui.configoverride(overrides, 'resolve'):
4997 with ui.configoverride(overrides, 'resolve'):
4997 r = ms.resolve(f, wctx)
4998 r = ms.resolve(f, wctx)
4998 if r:
4999 if r:
4999 ret = 1
5000 ret = 1
5000 finally:
5001 finally:
5001 ms.commit()
5002 ms.commit()
5002
5003
5003 # replace filemerge's .orig file with our resolve file
5004 # replace filemerge's .orig file with our resolve file
5004 a = repo.wjoin(f)
5005 a = repo.wjoin(f)
5005 try:
5006 try:
5006 util.rename(a + ".resolve", scmutil.backuppath(ui, repo, f))
5007 util.rename(a + ".resolve", scmutil.backuppath(ui, repo, f))
5007 except OSError as inst:
5008 except OSError as inst:
5008 if inst.errno != errno.ENOENT:
5009 if inst.errno != errno.ENOENT:
5009 raise
5010 raise
5010
5011
5011 ms.commit()
5012 ms.commit()
5012 ms.recordactions()
5013 ms.recordactions()
5013
5014
5014 if not didwork and pats:
5015 if not didwork and pats:
5015 hint = None
5016 hint = None
5016 if not any([p for p in pats if p.find(':') >= 0]):
5017 if not any([p for p in pats if p.find(':') >= 0]):
5017 pats = ['path:%s' % p for p in pats]
5018 pats = ['path:%s' % p for p in pats]
5018 m = scmutil.match(wctx, pats, opts)
5019 m = scmutil.match(wctx, pats, opts)
5019 for f in ms:
5020 for f in ms:
5020 if not m(f):
5021 if not m(f):
5021 continue
5022 continue
5022 def flag(o):
5023 def flag(o):
5023 if o == 're_merge':
5024 if o == 're_merge':
5024 return '--re-merge '
5025 return '--re-merge '
5025 return '-%s ' % o[0:1]
5026 return '-%s ' % o[0:1]
5026 flags = ''.join([flag(o) for o in flaglist if opts.get(o)])
5027 flags = ''.join([flag(o) for o in flaglist if opts.get(o)])
5027 hint = _("(try: hg resolve %s%s)\n") % (
5028 hint = _("(try: hg resolve %s%s)\n") % (
5028 flags,
5029 flags,
5029 ' '.join(pats))
5030 ' '.join(pats))
5030 break
5031 break
5031 ui.warn(_("arguments do not match paths that need resolving\n"))
5032 ui.warn(_("arguments do not match paths that need resolving\n"))
5032 if hint:
5033 if hint:
5033 ui.warn(hint)
5034 ui.warn(hint)
5034 elif ms.mergedriver and ms.mdstate() != 's':
5035 elif ms.mergedriver and ms.mdstate() != 's':
5035 # run conclude step when either a driver-resolved file is requested
5036 # run conclude step when either a driver-resolved file is requested
5036 # or there are no driver-resolved files
5037 # or there are no driver-resolved files
5037 # we can't use 'ret' to determine whether any files are unresolved
5038 # we can't use 'ret' to determine whether any files are unresolved
5038 # because we might not have tried to resolve some
5039 # because we might not have tried to resolve some
5039 if ((runconclude or not list(ms.driverresolved()))
5040 if ((runconclude or not list(ms.driverresolved()))
5040 and not list(ms.unresolved())):
5041 and not list(ms.unresolved())):
5041 proceed = mergemod.driverconclude(repo, ms, wctx)
5042 proceed = mergemod.driverconclude(repo, ms, wctx)
5042 ms.commit()
5043 ms.commit()
5043 if not proceed:
5044 if not proceed:
5044 return 1
5045 return 1
5045
5046
5046 # Nudge users into finishing an unfinished operation
5047 # Nudge users into finishing an unfinished operation
5047 unresolvedf = list(ms.unresolved())
5048 unresolvedf = list(ms.unresolved())
5048 driverresolvedf = list(ms.driverresolved())
5049 driverresolvedf = list(ms.driverresolved())
5049 if not unresolvedf and not driverresolvedf:
5050 if not unresolvedf and not driverresolvedf:
5050 ui.status(_('(no more unresolved files)\n'))
5051 ui.status(_('(no more unresolved files)\n'))
5051 cmdutil.checkafterresolved(repo)
5052 cmdutil.checkafterresolved(repo)
5052 elif not unresolvedf:
5053 elif not unresolvedf:
5053 ui.status(_('(no more unresolved files -- '
5054 ui.status(_('(no more unresolved files -- '
5054 'run "hg resolve --all" to conclude)\n'))
5055 'run "hg resolve --all" to conclude)\n'))
5055
5056
5056 return ret
5057 return ret
5057
5058
5058 @command('revert',
5059 @command('revert',
5059 [('a', 'all', None, _('revert all changes when no arguments given')),
5060 [('a', 'all', None, _('revert all changes when no arguments given')),
5060 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5061 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5061 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5062 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5062 ('C', 'no-backup', None, _('do not save backup copies of files')),
5063 ('C', 'no-backup', None, _('do not save backup copies of files')),
5063 ('i', 'interactive', None, _('interactively select the changes')),
5064 ('i', 'interactive', None, _('interactively select the changes')),
5064 ] + walkopts + dryrunopts,
5065 ] + walkopts + dryrunopts,
5065 _('[OPTION]... [-r REV] [NAME]...'),
5066 _('[OPTION]... [-r REV] [NAME]...'),
5066 helpcategory=command.CATEGORY_WORKING_DIRECTORY)
5067 helpcategory=command.CATEGORY_WORKING_DIRECTORY)
5067 def revert(ui, repo, *pats, **opts):
5068 def revert(ui, repo, *pats, **opts):
5068 """restore files to their checkout state
5069 """restore files to their checkout state
5069
5070
5070 .. note::
5071 .. note::
5071
5072
5072 To check out earlier revisions, you should use :hg:`update REV`.
5073 To check out earlier revisions, you should use :hg:`update REV`.
5073 To cancel an uncommitted merge (and lose your changes),
5074 To cancel an uncommitted merge (and lose your changes),
5074 use :hg:`merge --abort`.
5075 use :hg:`merge --abort`.
5075
5076
5076 With no revision specified, revert the specified files or directories
5077 With no revision specified, revert the specified files or directories
5077 to the contents they had in the parent of the working directory.
5078 to the contents they had in the parent of the working directory.
5078 This restores the contents of files to an unmodified
5079 This restores the contents of files to an unmodified
5079 state and unschedules adds, removes, copies, and renames. If the
5080 state and unschedules adds, removes, copies, and renames. If the
5080 working directory has two parents, you must explicitly specify a
5081 working directory has two parents, you must explicitly specify a
5081 revision.
5082 revision.
5082
5083
5083 Using the -r/--rev or -d/--date options, revert the given files or
5084 Using the -r/--rev or -d/--date options, revert the given files or
5084 directories to their states as of a specific revision. Because
5085 directories to their states as of a specific revision. Because
5085 revert does not change the working directory parents, this will
5086 revert does not change the working directory parents, this will
5086 cause these files to appear modified. This can be helpful to "back
5087 cause these files to appear modified. This can be helpful to "back
5087 out" some or all of an earlier change. See :hg:`backout` for a
5088 out" some or all of an earlier change. See :hg:`backout` for a
5088 related method.
5089 related method.
5089
5090
5090 Modified files are saved with a .orig suffix before reverting.
5091 Modified files are saved with a .orig suffix before reverting.
5091 To disable these backups, use --no-backup. It is possible to store
5092 To disable these backups, use --no-backup. It is possible to store
5092 the backup files in a custom directory relative to the root of the
5093 the backup files in a custom directory relative to the root of the
5093 repository by setting the ``ui.origbackuppath`` configuration
5094 repository by setting the ``ui.origbackuppath`` configuration
5094 option.
5095 option.
5095
5096
5096 See :hg:`help dates` for a list of formats valid for -d/--date.
5097 See :hg:`help dates` for a list of formats valid for -d/--date.
5097
5098
5098 See :hg:`help backout` for a way to reverse the effect of an
5099 See :hg:`help backout` for a way to reverse the effect of an
5099 earlier changeset.
5100 earlier changeset.
5100
5101
5101 Returns 0 on success.
5102 Returns 0 on success.
5102 """
5103 """
5103
5104
5104 opts = pycompat.byteskwargs(opts)
5105 opts = pycompat.byteskwargs(opts)
5105 if opts.get("date"):
5106 if opts.get("date"):
5106 if opts.get("rev"):
5107 if opts.get("rev"):
5107 raise error.Abort(_("you can't specify a revision and a date"))
5108 raise error.Abort(_("you can't specify a revision and a date"))
5108 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5109 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5109
5110
5110 parent, p2 = repo.dirstate.parents()
5111 parent, p2 = repo.dirstate.parents()
5111 if not opts.get('rev') and p2 != nullid:
5112 if not opts.get('rev') and p2 != nullid:
5112 # revert after merge is a trap for new users (issue2915)
5113 # revert after merge is a trap for new users (issue2915)
5113 raise error.Abort(_('uncommitted merge with no revision specified'),
5114 raise error.Abort(_('uncommitted merge with no revision specified'),
5114 hint=_("use 'hg update' or see 'hg help revert'"))
5115 hint=_("use 'hg update' or see 'hg help revert'"))
5115
5116
5116 rev = opts.get('rev')
5117 rev = opts.get('rev')
5117 if rev:
5118 if rev:
5118 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
5119 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
5119 ctx = scmutil.revsingle(repo, rev)
5120 ctx = scmutil.revsingle(repo, rev)
5120
5121
5121 if (not (pats or opts.get('include') or opts.get('exclude') or
5122 if (not (pats or opts.get('include') or opts.get('exclude') or
5122 opts.get('all') or opts.get('interactive'))):
5123 opts.get('all') or opts.get('interactive'))):
5123 msg = _("no files or directories specified")
5124 msg = _("no files or directories specified")
5124 if p2 != nullid:
5125 if p2 != nullid:
5125 hint = _("uncommitted merge, use --all to discard all changes,"
5126 hint = _("uncommitted merge, use --all to discard all changes,"
5126 " or 'hg update -C .' to abort the merge")
5127 " or 'hg update -C .' to abort the merge")
5127 raise error.Abort(msg, hint=hint)
5128 raise error.Abort(msg, hint=hint)
5128 dirty = any(repo.status())
5129 dirty = any(repo.status())
5129 node = ctx.node()
5130 node = ctx.node()
5130 if node != parent:
5131 if node != parent:
5131 if dirty:
5132 if dirty:
5132 hint = _("uncommitted changes, use --all to discard all"
5133 hint = _("uncommitted changes, use --all to discard all"
5133 " changes, or 'hg update %d' to update") % ctx.rev()
5134 " changes, or 'hg update %d' to update") % ctx.rev()
5134 else:
5135 else:
5135 hint = _("use --all to revert all files,"
5136 hint = _("use --all to revert all files,"
5136 " or 'hg update %d' to update") % ctx.rev()
5137 " or 'hg update %d' to update") % ctx.rev()
5137 elif dirty:
5138 elif dirty:
5138 hint = _("uncommitted changes, use --all to discard all changes")
5139 hint = _("uncommitted changes, use --all to discard all changes")
5139 else:
5140 else:
5140 hint = _("use --all to revert all files")
5141 hint = _("use --all to revert all files")
5141 raise error.Abort(msg, hint=hint)
5142 raise error.Abort(msg, hint=hint)
5142
5143
5143 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats,
5144 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats,
5144 **pycompat.strkwargs(opts))
5145 **pycompat.strkwargs(opts))
5145
5146
5146 @command(
5147 @command(
5147 'rollback',
5148 'rollback',
5148 dryrunopts + [('f', 'force', False, _('ignore safety measures'))],
5149 dryrunopts + [('f', 'force', False, _('ignore safety measures'))],
5149 helpcategory=command.CATEGORY_MAINTENANCE)
5150 helpcategory=command.CATEGORY_MAINTENANCE)
5150 def rollback(ui, repo, **opts):
5151 def rollback(ui, repo, **opts):
5151 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5152 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5152
5153
5153 Please use :hg:`commit --amend` instead of rollback to correct
5154 Please use :hg:`commit --amend` instead of rollback to correct
5154 mistakes in the last commit.
5155 mistakes in the last commit.
5155
5156
5156 This command should be used with care. There is only one level of
5157 This command should be used with care. There is only one level of
5157 rollback, and there is no way to undo a rollback. It will also
5158 rollback, and there is no way to undo a rollback. It will also
5158 restore the dirstate at the time of the last transaction, losing
5159 restore the dirstate at the time of the last transaction, losing
5159 any dirstate changes since that time. This command does not alter
5160 any dirstate changes since that time. This command does not alter
5160 the working directory.
5161 the working directory.
5161
5162
5162 Transactions are used to encapsulate the effects of all commands
5163 Transactions are used to encapsulate the effects of all commands
5163 that create new changesets or propagate existing changesets into a
5164 that create new changesets or propagate existing changesets into a
5164 repository.
5165 repository.
5165
5166
5166 .. container:: verbose
5167 .. container:: verbose
5167
5168
5168 For example, the following commands are transactional, and their
5169 For example, the following commands are transactional, and their
5169 effects can be rolled back:
5170 effects can be rolled back:
5170
5171
5171 - commit
5172 - commit
5172 - import
5173 - import
5173 - pull
5174 - pull
5174 - push (with this repository as the destination)
5175 - push (with this repository as the destination)
5175 - unbundle
5176 - unbundle
5176
5177
5177 To avoid permanent data loss, rollback will refuse to rollback a
5178 To avoid permanent data loss, rollback will refuse to rollback a
5178 commit transaction if it isn't checked out. Use --force to
5179 commit transaction if it isn't checked out. Use --force to
5179 override this protection.
5180 override this protection.
5180
5181
5181 The rollback command can be entirely disabled by setting the
5182 The rollback command can be entirely disabled by setting the
5182 ``ui.rollback`` configuration setting to false. If you're here
5183 ``ui.rollback`` configuration setting to false. If you're here
5183 because you want to use rollback and it's disabled, you can
5184 because you want to use rollback and it's disabled, you can
5184 re-enable the command by setting ``ui.rollback`` to true.
5185 re-enable the command by setting ``ui.rollback`` to true.
5185
5186
5186 This command is not intended for use on public repositories. Once
5187 This command is not intended for use on public repositories. Once
5187 changes are visible for pull by other users, rolling a transaction
5188 changes are visible for pull by other users, rolling a transaction
5188 back locally is ineffective (someone else may already have pulled
5189 back locally is ineffective (someone else may already have pulled
5189 the changes). Furthermore, a race is possible with readers of the
5190 the changes). Furthermore, a race is possible with readers of the
5190 repository; for example an in-progress pull from the repository
5191 repository; for example an in-progress pull from the repository
5191 may fail if a rollback is performed.
5192 may fail if a rollback is performed.
5192
5193
5193 Returns 0 on success, 1 if no rollback data is available.
5194 Returns 0 on success, 1 if no rollback data is available.
5194 """
5195 """
5195 if not ui.configbool('ui', 'rollback'):
5196 if not ui.configbool('ui', 'rollback'):
5196 raise error.Abort(_('rollback is disabled because it is unsafe'),
5197 raise error.Abort(_('rollback is disabled because it is unsafe'),
5197 hint=('see `hg help -v rollback` for information'))
5198 hint=('see `hg help -v rollback` for information'))
5198 return repo.rollback(dryrun=opts.get(r'dry_run'),
5199 return repo.rollback(dryrun=opts.get(r'dry_run'),
5199 force=opts.get(r'force'))
5200 force=opts.get(r'force'))
5200
5201
5201 @command(
5202 @command(
5202 'root', [], intents={INTENT_READONLY},
5203 'root', [], intents={INTENT_READONLY},
5203 helpcategory=command.CATEGORY_WORKING_DIRECTORY)
5204 helpcategory=command.CATEGORY_WORKING_DIRECTORY)
5204 def root(ui, repo):
5205 def root(ui, repo):
5205 """print the root (top) of the current working directory
5206 """print the root (top) of the current working directory
5206
5207
5207 Print the root directory of the current repository.
5208 Print the root directory of the current repository.
5208
5209
5209 Returns 0 on success.
5210 Returns 0 on success.
5210 """
5211 """
5211 ui.write(repo.root + "\n")
5212 ui.write(repo.root + "\n")
5212
5213
5213 @command('serve',
5214 @command('serve',
5214 [('A', 'accesslog', '', _('name of access log file to write to'),
5215 [('A', 'accesslog', '', _('name of access log file to write to'),
5215 _('FILE')),
5216 _('FILE')),
5216 ('d', 'daemon', None, _('run server in background')),
5217 ('d', 'daemon', None, _('run server in background')),
5217 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
5218 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
5218 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5219 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5219 # use string type, then we can check if something was passed
5220 # use string type, then we can check if something was passed
5220 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5221 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5221 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5222 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5222 _('ADDR')),
5223 _('ADDR')),
5223 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5224 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5224 _('PREFIX')),
5225 _('PREFIX')),
5225 ('n', 'name', '',
5226 ('n', 'name', '',
5226 _('name to show in web pages (default: working directory)'), _('NAME')),
5227 _('name to show in web pages (default: working directory)'), _('NAME')),
5227 ('', 'web-conf', '',
5228 ('', 'web-conf', '',
5228 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
5229 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
5229 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5230 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5230 _('FILE')),
5231 _('FILE')),
5231 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5232 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5232 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
5233 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
5233 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
5234 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
5234 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5235 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5235 ('', 'style', '', _('template style to use'), _('STYLE')),
5236 ('', 'style', '', _('template style to use'), _('STYLE')),
5236 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5237 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5237 ('', 'certificate', '', _('SSL certificate file'), _('FILE')),
5238 ('', 'certificate', '', _('SSL certificate file'), _('FILE')),
5238 ('', 'print-url', None, _('start and print only the URL'))]
5239 ('', 'print-url', None, _('start and print only the URL'))]
5239 + subrepoopts,
5240 + subrepoopts,
5240 _('[OPTION]...'),
5241 _('[OPTION]...'),
5241 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5242 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5242 helpbasic=True, optionalrepo=True)
5243 helpbasic=True, optionalrepo=True)
5243 def serve(ui, repo, **opts):
5244 def serve(ui, repo, **opts):
5244 """start stand-alone webserver
5245 """start stand-alone webserver
5245
5246
5246 Start a local HTTP repository browser and pull server. You can use
5247 Start a local HTTP repository browser and pull server. You can use
5247 this for ad-hoc sharing and browsing of repositories. It is
5248 this for ad-hoc sharing and browsing of repositories. It is
5248 recommended to use a real web server to serve a repository for
5249 recommended to use a real web server to serve a repository for
5249 longer periods of time.
5250 longer periods of time.
5250
5251
5251 Please note that the server does not implement access control.
5252 Please note that the server does not implement access control.
5252 This means that, by default, anybody can read from the server and
5253 This means that, by default, anybody can read from the server and
5253 nobody can write to it by default. Set the ``web.allow-push``
5254 nobody can write to it by default. Set the ``web.allow-push``
5254 option to ``*`` to allow everybody to push to the server. You
5255 option to ``*`` to allow everybody to push to the server. You
5255 should use a real web server if you need to authenticate users.
5256 should use a real web server if you need to authenticate users.
5256
5257
5257 By default, the server logs accesses to stdout and errors to
5258 By default, the server logs accesses to stdout and errors to
5258 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5259 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5259 files.
5260 files.
5260
5261
5261 To have the server choose a free port number to listen on, specify
5262 To have the server choose a free port number to listen on, specify
5262 a port number of 0; in this case, the server will print the port
5263 a port number of 0; in this case, the server will print the port
5263 number it uses.
5264 number it uses.
5264
5265
5265 Returns 0 on success.
5266 Returns 0 on success.
5266 """
5267 """
5267
5268
5268 opts = pycompat.byteskwargs(opts)
5269 opts = pycompat.byteskwargs(opts)
5269 if opts["stdio"] and opts["cmdserver"]:
5270 if opts["stdio"] and opts["cmdserver"]:
5270 raise error.Abort(_("cannot use --stdio with --cmdserver"))
5271 raise error.Abort(_("cannot use --stdio with --cmdserver"))
5271 if opts["print_url"] and ui.verbose:
5272 if opts["print_url"] and ui.verbose:
5272 raise error.Abort(_("cannot use --print-url with --verbose"))
5273 raise error.Abort(_("cannot use --print-url with --verbose"))
5273
5274
5274 if opts["stdio"]:
5275 if opts["stdio"]:
5275 if repo is None:
5276 if repo is None:
5276 raise error.RepoError(_("there is no Mercurial repository here"
5277 raise error.RepoError(_("there is no Mercurial repository here"
5277 " (.hg not found)"))
5278 " (.hg not found)"))
5278 s = wireprotoserver.sshserver(ui, repo)
5279 s = wireprotoserver.sshserver(ui, repo)
5279 s.serve_forever()
5280 s.serve_forever()
5280
5281
5281 service = server.createservice(ui, repo, opts)
5282 service = server.createservice(ui, repo, opts)
5282 return server.runservice(opts, initfn=service.init, runfn=service.run)
5283 return server.runservice(opts, initfn=service.init, runfn=service.run)
5283
5284
5284 _NOTTERSE = 'nothing'
5285 _NOTTERSE = 'nothing'
5285
5286
5286 @command('status|st',
5287 @command('status|st',
5287 [('A', 'all', None, _('show status of all files')),
5288 [('A', 'all', None, _('show status of all files')),
5288 ('m', 'modified', None, _('show only modified files')),
5289 ('m', 'modified', None, _('show only modified files')),
5289 ('a', 'added', None, _('show only added files')),
5290 ('a', 'added', None, _('show only added files')),
5290 ('r', 'removed', None, _('show only removed files')),
5291 ('r', 'removed', None, _('show only removed files')),
5291 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5292 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5292 ('c', 'clean', None, _('show only files without changes')),
5293 ('c', 'clean', None, _('show only files without changes')),
5293 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5294 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5294 ('i', 'ignored', None, _('show only ignored files')),
5295 ('i', 'ignored', None, _('show only ignored files')),
5295 ('n', 'no-status', None, _('hide status prefix')),
5296 ('n', 'no-status', None, _('hide status prefix')),
5296 ('t', 'terse', _NOTTERSE, _('show the terse output (EXPERIMENTAL)')),
5297 ('t', 'terse', _NOTTERSE, _('show the terse output (EXPERIMENTAL)')),
5297 ('C', 'copies', None, _('show source of copied files')),
5298 ('C', 'copies', None, _('show source of copied files')),
5298 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5299 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5299 ('', 'rev', [], _('show difference from revision'), _('REV')),
5300 ('', 'rev', [], _('show difference from revision'), _('REV')),
5300 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5301 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5301 ] + walkopts + subrepoopts + formatteropts,
5302 ] + walkopts + subrepoopts + formatteropts,
5302 _('[OPTION]... [FILE]...'),
5303 _('[OPTION]... [FILE]...'),
5303 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5304 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5304 helpbasic=True, inferrepo=True,
5305 helpbasic=True, inferrepo=True,
5305 intents={INTENT_READONLY})
5306 intents={INTENT_READONLY})
5306 def status(ui, repo, *pats, **opts):
5307 def status(ui, repo, *pats, **opts):
5307 """show changed files in the working directory
5308 """show changed files in the working directory
5308
5309
5309 Show status of files in the repository. If names are given, only
5310 Show status of files in the repository. If names are given, only
5310 files that match are shown. Files that are clean or ignored or
5311 files that match are shown. Files that are clean or ignored or
5311 the source of a copy/move operation, are not listed unless
5312 the source of a copy/move operation, are not listed unless
5312 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5313 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5313 Unless options described with "show only ..." are given, the
5314 Unless options described with "show only ..." are given, the
5314 options -mardu are used.
5315 options -mardu are used.
5315
5316
5316 Option -q/--quiet hides untracked (unknown and ignored) files
5317 Option -q/--quiet hides untracked (unknown and ignored) files
5317 unless explicitly requested with -u/--unknown or -i/--ignored.
5318 unless explicitly requested with -u/--unknown or -i/--ignored.
5318
5319
5319 .. note::
5320 .. note::
5320
5321
5321 :hg:`status` may appear to disagree with diff if permissions have
5322 :hg:`status` may appear to disagree with diff if permissions have
5322 changed or a merge has occurred. The standard diff format does
5323 changed or a merge has occurred. The standard diff format does
5323 not report permission changes and diff only reports changes
5324 not report permission changes and diff only reports changes
5324 relative to one merge parent.
5325 relative to one merge parent.
5325
5326
5326 If one revision is given, it is used as the base revision.
5327 If one revision is given, it is used as the base revision.
5327 If two revisions are given, the differences between them are
5328 If two revisions are given, the differences between them are
5328 shown. The --change option can also be used as a shortcut to list
5329 shown. The --change option can also be used as a shortcut to list
5329 the changed files of a revision from its first parent.
5330 the changed files of a revision from its first parent.
5330
5331
5331 The codes used to show the status of files are::
5332 The codes used to show the status of files are::
5332
5333
5333 M = modified
5334 M = modified
5334 A = added
5335 A = added
5335 R = removed
5336 R = removed
5336 C = clean
5337 C = clean
5337 ! = missing (deleted by non-hg command, but still tracked)
5338 ! = missing (deleted by non-hg command, but still tracked)
5338 ? = not tracked
5339 ? = not tracked
5339 I = ignored
5340 I = ignored
5340 = origin of the previous file (with --copies)
5341 = origin of the previous file (with --copies)
5341
5342
5342 .. container:: verbose
5343 .. container:: verbose
5343
5344
5344 The -t/--terse option abbreviates the output by showing only the directory
5345 The -t/--terse option abbreviates the output by showing only the directory
5345 name if all the files in it share the same status. The option takes an
5346 name if all the files in it share the same status. The option takes an
5346 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
5347 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
5347 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
5348 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
5348 for 'ignored' and 'c' for clean.
5349 for 'ignored' and 'c' for clean.
5349
5350
5350 It abbreviates only those statuses which are passed. Note that clean and
5351 It abbreviates only those statuses which are passed. Note that clean and
5351 ignored files are not displayed with '--terse ic' unless the -c/--clean
5352 ignored files are not displayed with '--terse ic' unless the -c/--clean
5352 and -i/--ignored options are also used.
5353 and -i/--ignored options are also used.
5353
5354
5354 The -v/--verbose option shows information when the repository is in an
5355 The -v/--verbose option shows information when the repository is in an
5355 unfinished merge, shelve, rebase state etc. You can have this behavior
5356 unfinished merge, shelve, rebase state etc. You can have this behavior
5356 turned on by default by enabling the ``commands.status.verbose`` option.
5357 turned on by default by enabling the ``commands.status.verbose`` option.
5357
5358
5358 You can skip displaying some of these states by setting
5359 You can skip displaying some of these states by setting
5359 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
5360 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
5360 'histedit', 'merge', 'rebase', or 'unshelve'.
5361 'histedit', 'merge', 'rebase', or 'unshelve'.
5361
5362
5362 Template:
5363 Template:
5363
5364
5364 The following keywords are supported in addition to the common template
5365 The following keywords are supported in addition to the common template
5365 keywords and functions. See also :hg:`help templates`.
5366 keywords and functions. See also :hg:`help templates`.
5366
5367
5367 :path: String. Repository-absolute path of the file.
5368 :path: String. Repository-absolute path of the file.
5368 :source: String. Repository-absolute path of the file originated from.
5369 :source: String. Repository-absolute path of the file originated from.
5369 Available if ``--copies`` is specified.
5370 Available if ``--copies`` is specified.
5370 :status: String. Character denoting file's status.
5371 :status: String. Character denoting file's status.
5371
5372
5372 Examples:
5373 Examples:
5373
5374
5374 - show changes in the working directory relative to a
5375 - show changes in the working directory relative to a
5375 changeset::
5376 changeset::
5376
5377
5377 hg status --rev 9353
5378 hg status --rev 9353
5378
5379
5379 - show changes in the working directory relative to the
5380 - show changes in the working directory relative to the
5380 current directory (see :hg:`help patterns` for more information)::
5381 current directory (see :hg:`help patterns` for more information)::
5381
5382
5382 hg status re:
5383 hg status re:
5383
5384
5384 - show all changes including copies in an existing changeset::
5385 - show all changes including copies in an existing changeset::
5385
5386
5386 hg status --copies --change 9353
5387 hg status --copies --change 9353
5387
5388
5388 - get a NUL separated list of added files, suitable for xargs::
5389 - get a NUL separated list of added files, suitable for xargs::
5389
5390
5390 hg status -an0
5391 hg status -an0
5391
5392
5392 - show more information about the repository status, abbreviating
5393 - show more information about the repository status, abbreviating
5393 added, removed, modified, deleted, and untracked paths::
5394 added, removed, modified, deleted, and untracked paths::
5394
5395
5395 hg status -v -t mardu
5396 hg status -v -t mardu
5396
5397
5397 Returns 0 on success.
5398 Returns 0 on success.
5398
5399
5399 """
5400 """
5400
5401
5401 opts = pycompat.byteskwargs(opts)
5402 opts = pycompat.byteskwargs(opts)
5402 revs = opts.get('rev')
5403 revs = opts.get('rev')
5403 change = opts.get('change')
5404 change = opts.get('change')
5404 terse = opts.get('terse')
5405 terse = opts.get('terse')
5405 if terse is _NOTTERSE:
5406 if terse is _NOTTERSE:
5406 if revs:
5407 if revs:
5407 terse = ''
5408 terse = ''
5408 else:
5409 else:
5409 terse = ui.config('commands', 'status.terse')
5410 terse = ui.config('commands', 'status.terse')
5410
5411
5411 if revs and change:
5412 if revs and change:
5412 msg = _('cannot specify --rev and --change at the same time')
5413 msg = _('cannot specify --rev and --change at the same time')
5413 raise error.Abort(msg)
5414 raise error.Abort(msg)
5414 elif revs and terse:
5415 elif revs and terse:
5415 msg = _('cannot use --terse with --rev')
5416 msg = _('cannot use --terse with --rev')
5416 raise error.Abort(msg)
5417 raise error.Abort(msg)
5417 elif change:
5418 elif change:
5418 repo = scmutil.unhidehashlikerevs(repo, [change], 'nowarn')
5419 repo = scmutil.unhidehashlikerevs(repo, [change], 'nowarn')
5419 ctx2 = scmutil.revsingle(repo, change, None)
5420 ctx2 = scmutil.revsingle(repo, change, None)
5420 ctx1 = ctx2.p1()
5421 ctx1 = ctx2.p1()
5421 else:
5422 else:
5422 repo = scmutil.unhidehashlikerevs(repo, revs, 'nowarn')
5423 repo = scmutil.unhidehashlikerevs(repo, revs, 'nowarn')
5423 ctx1, ctx2 = scmutil.revpair(repo, revs)
5424 ctx1, ctx2 = scmutil.revpair(repo, revs)
5424
5425
5425 forcerelativevalue = None
5426 forcerelativevalue = None
5426 if ui.hasconfig('commands', 'status.relative'):
5427 if ui.hasconfig('commands', 'status.relative'):
5427 forcerelativevalue = ui.configbool('commands', 'status.relative')
5428 forcerelativevalue = ui.configbool('commands', 'status.relative')
5428 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats),
5429 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats),
5429 forcerelativevalue=forcerelativevalue)
5430 forcerelativevalue=forcerelativevalue)
5430
5431
5431 if opts.get('print0'):
5432 if opts.get('print0'):
5432 end = '\0'
5433 end = '\0'
5433 else:
5434 else:
5434 end = '\n'
5435 end = '\n'
5435 copy = {}
5436 copy = {}
5436 states = 'modified added removed deleted unknown ignored clean'.split()
5437 states = 'modified added removed deleted unknown ignored clean'.split()
5437 show = [k for k in states if opts.get(k)]
5438 show = [k for k in states if opts.get(k)]
5438 if opts.get('all'):
5439 if opts.get('all'):
5439 show += ui.quiet and (states[:4] + ['clean']) or states
5440 show += ui.quiet and (states[:4] + ['clean']) or states
5440
5441
5441 if not show:
5442 if not show:
5442 if ui.quiet:
5443 if ui.quiet:
5443 show = states[:4]
5444 show = states[:4]
5444 else:
5445 else:
5445 show = states[:5]
5446 show = states[:5]
5446
5447
5447 m = scmutil.match(ctx2, pats, opts)
5448 m = scmutil.match(ctx2, pats, opts)
5448 if terse:
5449 if terse:
5449 # we need to compute clean and unknown to terse
5450 # we need to compute clean and unknown to terse
5450 stat = repo.status(ctx1.node(), ctx2.node(), m,
5451 stat = repo.status(ctx1.node(), ctx2.node(), m,
5451 'ignored' in show or 'i' in terse,
5452 'ignored' in show or 'i' in terse,
5452 clean=True, unknown=True,
5453 clean=True, unknown=True,
5453 listsubrepos=opts.get('subrepos'))
5454 listsubrepos=opts.get('subrepos'))
5454
5455
5455 stat = cmdutil.tersedir(stat, terse)
5456 stat = cmdutil.tersedir(stat, terse)
5456 else:
5457 else:
5457 stat = repo.status(ctx1.node(), ctx2.node(), m,
5458 stat = repo.status(ctx1.node(), ctx2.node(), m,
5458 'ignored' in show, 'clean' in show,
5459 'ignored' in show, 'clean' in show,
5459 'unknown' in show, opts.get('subrepos'))
5460 'unknown' in show, opts.get('subrepos'))
5460
5461
5461 changestates = zip(states, pycompat.iterbytestr('MAR!?IC'), stat)
5462 changestates = zip(states, pycompat.iterbytestr('MAR!?IC'), stat)
5462
5463
5463 if (opts.get('all') or opts.get('copies')
5464 if (opts.get('all') or opts.get('copies')
5464 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
5465 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
5465 copy = copies.pathcopies(ctx1, ctx2, m)
5466 copy = copies.pathcopies(ctx1, ctx2, m)
5466
5467
5467 ui.pager('status')
5468 ui.pager('status')
5468 fm = ui.formatter('status', opts)
5469 fm = ui.formatter('status', opts)
5469 fmt = '%s' + end
5470 fmt = '%s' + end
5470 showchar = not opts.get('no_status')
5471 showchar = not opts.get('no_status')
5471
5472
5472 for state, char, files in changestates:
5473 for state, char, files in changestates:
5473 if state in show:
5474 if state in show:
5474 label = 'status.' + state
5475 label = 'status.' + state
5475 for f in files:
5476 for f in files:
5476 fm.startitem()
5477 fm.startitem()
5477 fm.context(ctx=ctx2)
5478 fm.context(ctx=ctx2)
5478 fm.data(path=f)
5479 fm.data(path=f)
5479 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5480 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5480 fm.plain(fmt % uipathfn(f), label=label)
5481 fm.plain(fmt % uipathfn(f), label=label)
5481 if f in copy:
5482 if f in copy:
5482 fm.data(source=copy[f])
5483 fm.data(source=copy[f])
5483 fm.plain((' %s' + end) % uipathfn(copy[f]),
5484 fm.plain((' %s' + end) % uipathfn(copy[f]),
5484 label='status.copied')
5485 label='status.copied')
5485
5486
5486 if ((ui.verbose or ui.configbool('commands', 'status.verbose'))
5487 if ((ui.verbose or ui.configbool('commands', 'status.verbose'))
5487 and not ui.plain()):
5488 and not ui.plain()):
5488 cmdutil.morestatus(repo, fm)
5489 cmdutil.morestatus(repo, fm)
5489 fm.end()
5490 fm.end()
5490
5491
5491 @command('summary|sum',
5492 @command('summary|sum',
5492 [('', 'remote', None, _('check for push and pull'))],
5493 [('', 'remote', None, _('check for push and pull'))],
5493 '[--remote]',
5494 '[--remote]',
5494 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5495 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5495 helpbasic=True,
5496 helpbasic=True,
5496 intents={INTENT_READONLY})
5497 intents={INTENT_READONLY})
5497 def summary(ui, repo, **opts):
5498 def summary(ui, repo, **opts):
5498 """summarize working directory state
5499 """summarize working directory state
5499
5500
5500 This generates a brief summary of the working directory state,
5501 This generates a brief summary of the working directory state,
5501 including parents, branch, commit status, phase and available updates.
5502 including parents, branch, commit status, phase and available updates.
5502
5503
5503 With the --remote option, this will check the default paths for
5504 With the --remote option, this will check the default paths for
5504 incoming and outgoing changes. This can be time-consuming.
5505 incoming and outgoing changes. This can be time-consuming.
5505
5506
5506 Returns 0 on success.
5507 Returns 0 on success.
5507 """
5508 """
5508
5509
5509 opts = pycompat.byteskwargs(opts)
5510 opts = pycompat.byteskwargs(opts)
5510 ui.pager('summary')
5511 ui.pager('summary')
5511 ctx = repo[None]
5512 ctx = repo[None]
5512 parents = ctx.parents()
5513 parents = ctx.parents()
5513 pnode = parents[0].node()
5514 pnode = parents[0].node()
5514 marks = []
5515 marks = []
5515
5516
5516 try:
5517 try:
5517 ms = mergemod.mergestate.read(repo)
5518 ms = mergemod.mergestate.read(repo)
5518 except error.UnsupportedMergeRecords as e:
5519 except error.UnsupportedMergeRecords as e:
5519 s = ' '.join(e.recordtypes)
5520 s = ' '.join(e.recordtypes)
5520 ui.warn(
5521 ui.warn(
5521 _('warning: merge state has unsupported record types: %s\n') % s)
5522 _('warning: merge state has unsupported record types: %s\n') % s)
5522 unresolved = []
5523 unresolved = []
5523 else:
5524 else:
5524 unresolved = list(ms.unresolved())
5525 unresolved = list(ms.unresolved())
5525
5526
5526 for p in parents:
5527 for p in parents:
5527 # label with log.changeset (instead of log.parent) since this
5528 # label with log.changeset (instead of log.parent) since this
5528 # shows a working directory parent *changeset*:
5529 # shows a working directory parent *changeset*:
5529 # i18n: column positioning for "hg summary"
5530 # i18n: column positioning for "hg summary"
5530 ui.write(_('parent: %d:%s ') % (p.rev(), p),
5531 ui.write(_('parent: %d:%s ') % (p.rev(), p),
5531 label=logcmdutil.changesetlabels(p))
5532 label=logcmdutil.changesetlabels(p))
5532 ui.write(' '.join(p.tags()), label='log.tag')
5533 ui.write(' '.join(p.tags()), label='log.tag')
5533 if p.bookmarks():
5534 if p.bookmarks():
5534 marks.extend(p.bookmarks())
5535 marks.extend(p.bookmarks())
5535 if p.rev() == -1:
5536 if p.rev() == -1:
5536 if not len(repo):
5537 if not len(repo):
5537 ui.write(_(' (empty repository)'))
5538 ui.write(_(' (empty repository)'))
5538 else:
5539 else:
5539 ui.write(_(' (no revision checked out)'))
5540 ui.write(_(' (no revision checked out)'))
5540 if p.obsolete():
5541 if p.obsolete():
5541 ui.write(_(' (obsolete)'))
5542 ui.write(_(' (obsolete)'))
5542 if p.isunstable():
5543 if p.isunstable():
5543 instabilities = (ui.label(instability, 'trouble.%s' % instability)
5544 instabilities = (ui.label(instability, 'trouble.%s' % instability)
5544 for instability in p.instabilities())
5545 for instability in p.instabilities())
5545 ui.write(' ('
5546 ui.write(' ('
5546 + ', '.join(instabilities)
5547 + ', '.join(instabilities)
5547 + ')')
5548 + ')')
5548 ui.write('\n')
5549 ui.write('\n')
5549 if p.description():
5550 if p.description():
5550 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5551 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5551 label='log.summary')
5552 label='log.summary')
5552
5553
5553 branch = ctx.branch()
5554 branch = ctx.branch()
5554 bheads = repo.branchheads(branch)
5555 bheads = repo.branchheads(branch)
5555 # i18n: column positioning for "hg summary"
5556 # i18n: column positioning for "hg summary"
5556 m = _('branch: %s\n') % branch
5557 m = _('branch: %s\n') % branch
5557 if branch != 'default':
5558 if branch != 'default':
5558 ui.write(m, label='log.branch')
5559 ui.write(m, label='log.branch')
5559 else:
5560 else:
5560 ui.status(m, label='log.branch')
5561 ui.status(m, label='log.branch')
5561
5562
5562 if marks:
5563 if marks:
5563 active = repo._activebookmark
5564 active = repo._activebookmark
5564 # i18n: column positioning for "hg summary"
5565 # i18n: column positioning for "hg summary"
5565 ui.write(_('bookmarks:'), label='log.bookmark')
5566 ui.write(_('bookmarks:'), label='log.bookmark')
5566 if active is not None:
5567 if active is not None:
5567 if active in marks:
5568 if active in marks:
5568 ui.write(' *' + active, label=bookmarks.activebookmarklabel)
5569 ui.write(' *' + active, label=bookmarks.activebookmarklabel)
5569 marks.remove(active)
5570 marks.remove(active)
5570 else:
5571 else:
5571 ui.write(' [%s]' % active, label=bookmarks.activebookmarklabel)
5572 ui.write(' [%s]' % active, label=bookmarks.activebookmarklabel)
5572 for m in marks:
5573 for m in marks:
5573 ui.write(' ' + m, label='log.bookmark')
5574 ui.write(' ' + m, label='log.bookmark')
5574 ui.write('\n', label='log.bookmark')
5575 ui.write('\n', label='log.bookmark')
5575
5576
5576 status = repo.status(unknown=True)
5577 status = repo.status(unknown=True)
5577
5578
5578 c = repo.dirstate.copies()
5579 c = repo.dirstate.copies()
5579 copied, renamed = [], []
5580 copied, renamed = [], []
5580 for d, s in c.iteritems():
5581 for d, s in c.iteritems():
5581 if s in status.removed:
5582 if s in status.removed:
5582 status.removed.remove(s)
5583 status.removed.remove(s)
5583 renamed.append(d)
5584 renamed.append(d)
5584 else:
5585 else:
5585 copied.append(d)
5586 copied.append(d)
5586 if d in status.added:
5587 if d in status.added:
5587 status.added.remove(d)
5588 status.added.remove(d)
5588
5589
5589 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5590 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5590
5591
5591 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
5592 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
5592 (ui.label(_('%d added'), 'status.added'), status.added),
5593 (ui.label(_('%d added'), 'status.added'), status.added),
5593 (ui.label(_('%d removed'), 'status.removed'), status.removed),
5594 (ui.label(_('%d removed'), 'status.removed'), status.removed),
5594 (ui.label(_('%d renamed'), 'status.copied'), renamed),
5595 (ui.label(_('%d renamed'), 'status.copied'), renamed),
5595 (ui.label(_('%d copied'), 'status.copied'), copied),
5596 (ui.label(_('%d copied'), 'status.copied'), copied),
5596 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
5597 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
5597 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
5598 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
5598 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
5599 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
5599 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
5600 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
5600 t = []
5601 t = []
5601 for l, s in labels:
5602 for l, s in labels:
5602 if s:
5603 if s:
5603 t.append(l % len(s))
5604 t.append(l % len(s))
5604
5605
5605 t = ', '.join(t)
5606 t = ', '.join(t)
5606 cleanworkdir = False
5607 cleanworkdir = False
5607
5608
5608 if repo.vfs.exists('graftstate'):
5609 if repo.vfs.exists('graftstate'):
5609 t += _(' (graft in progress)')
5610 t += _(' (graft in progress)')
5610 if repo.vfs.exists('updatestate'):
5611 if repo.vfs.exists('updatestate'):
5611 t += _(' (interrupted update)')
5612 t += _(' (interrupted update)')
5612 elif len(parents) > 1:
5613 elif len(parents) > 1:
5613 t += _(' (merge)')
5614 t += _(' (merge)')
5614 elif branch != parents[0].branch():
5615 elif branch != parents[0].branch():
5615 t += _(' (new branch)')
5616 t += _(' (new branch)')
5616 elif (parents[0].closesbranch() and
5617 elif (parents[0].closesbranch() and
5617 pnode in repo.branchheads(branch, closed=True)):
5618 pnode in repo.branchheads(branch, closed=True)):
5618 t += _(' (head closed)')
5619 t += _(' (head closed)')
5619 elif not (status.modified or status.added or status.removed or renamed or
5620 elif not (status.modified or status.added or status.removed or renamed or
5620 copied or subs):
5621 copied or subs):
5621 t += _(' (clean)')
5622 t += _(' (clean)')
5622 cleanworkdir = True
5623 cleanworkdir = True
5623 elif pnode not in bheads:
5624 elif pnode not in bheads:
5624 t += _(' (new branch head)')
5625 t += _(' (new branch head)')
5625
5626
5626 if parents:
5627 if parents:
5627 pendingphase = max(p.phase() for p in parents)
5628 pendingphase = max(p.phase() for p in parents)
5628 else:
5629 else:
5629 pendingphase = phases.public
5630 pendingphase = phases.public
5630
5631
5631 if pendingphase > phases.newcommitphase(ui):
5632 if pendingphase > phases.newcommitphase(ui):
5632 t += ' (%s)' % phases.phasenames[pendingphase]
5633 t += ' (%s)' % phases.phasenames[pendingphase]
5633
5634
5634 if cleanworkdir:
5635 if cleanworkdir:
5635 # i18n: column positioning for "hg summary"
5636 # i18n: column positioning for "hg summary"
5636 ui.status(_('commit: %s\n') % t.strip())
5637 ui.status(_('commit: %s\n') % t.strip())
5637 else:
5638 else:
5638 # i18n: column positioning for "hg summary"
5639 # i18n: column positioning for "hg summary"
5639 ui.write(_('commit: %s\n') % t.strip())
5640 ui.write(_('commit: %s\n') % t.strip())
5640
5641
5641 # all ancestors of branch heads - all ancestors of parent = new csets
5642 # all ancestors of branch heads - all ancestors of parent = new csets
5642 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
5643 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
5643 bheads))
5644 bheads))
5644
5645
5645 if new == 0:
5646 if new == 0:
5646 # i18n: column positioning for "hg summary"
5647 # i18n: column positioning for "hg summary"
5647 ui.status(_('update: (current)\n'))
5648 ui.status(_('update: (current)\n'))
5648 elif pnode not in bheads:
5649 elif pnode not in bheads:
5649 # i18n: column positioning for "hg summary"
5650 # i18n: column positioning for "hg summary"
5650 ui.write(_('update: %d new changesets (update)\n') % new)
5651 ui.write(_('update: %d new changesets (update)\n') % new)
5651 else:
5652 else:
5652 # i18n: column positioning for "hg summary"
5653 # i18n: column positioning for "hg summary"
5653 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5654 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5654 (new, len(bheads)))
5655 (new, len(bheads)))
5655
5656
5656 t = []
5657 t = []
5657 draft = len(repo.revs('draft()'))
5658 draft = len(repo.revs('draft()'))
5658 if draft:
5659 if draft:
5659 t.append(_('%d draft') % draft)
5660 t.append(_('%d draft') % draft)
5660 secret = len(repo.revs('secret()'))
5661 secret = len(repo.revs('secret()'))
5661 if secret:
5662 if secret:
5662 t.append(_('%d secret') % secret)
5663 t.append(_('%d secret') % secret)
5663
5664
5664 if draft or secret:
5665 if draft or secret:
5665 ui.status(_('phases: %s\n') % ', '.join(t))
5666 ui.status(_('phases: %s\n') % ', '.join(t))
5666
5667
5667 if obsolete.isenabled(repo, obsolete.createmarkersopt):
5668 if obsolete.isenabled(repo, obsolete.createmarkersopt):
5668 for trouble in ("orphan", "contentdivergent", "phasedivergent"):
5669 for trouble in ("orphan", "contentdivergent", "phasedivergent"):
5669 numtrouble = len(repo.revs(trouble + "()"))
5670 numtrouble = len(repo.revs(trouble + "()"))
5670 # We write all the possibilities to ease translation
5671 # We write all the possibilities to ease translation
5671 troublemsg = {
5672 troublemsg = {
5672 "orphan": _("orphan: %d changesets"),
5673 "orphan": _("orphan: %d changesets"),
5673 "contentdivergent": _("content-divergent: %d changesets"),
5674 "contentdivergent": _("content-divergent: %d changesets"),
5674 "phasedivergent": _("phase-divergent: %d changesets"),
5675 "phasedivergent": _("phase-divergent: %d changesets"),
5675 }
5676 }
5676 if numtrouble > 0:
5677 if numtrouble > 0:
5677 ui.status(troublemsg[trouble] % numtrouble + "\n")
5678 ui.status(troublemsg[trouble] % numtrouble + "\n")
5678
5679
5679 cmdutil.summaryhooks(ui, repo)
5680 cmdutil.summaryhooks(ui, repo)
5680
5681
5681 if opts.get('remote'):
5682 if opts.get('remote'):
5682 needsincoming, needsoutgoing = True, True
5683 needsincoming, needsoutgoing = True, True
5683 else:
5684 else:
5684 needsincoming, needsoutgoing = False, False
5685 needsincoming, needsoutgoing = False, False
5685 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5686 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5686 if i:
5687 if i:
5687 needsincoming = True
5688 needsincoming = True
5688 if o:
5689 if o:
5689 needsoutgoing = True
5690 needsoutgoing = True
5690 if not needsincoming and not needsoutgoing:
5691 if not needsincoming and not needsoutgoing:
5691 return
5692 return
5692
5693
5693 def getincoming():
5694 def getincoming():
5694 source, branches = hg.parseurl(ui.expandpath('default'))
5695 source, branches = hg.parseurl(ui.expandpath('default'))
5695 sbranch = branches[0]
5696 sbranch = branches[0]
5696 try:
5697 try:
5697 other = hg.peer(repo, {}, source)
5698 other = hg.peer(repo, {}, source)
5698 except error.RepoError:
5699 except error.RepoError:
5699 if opts.get('remote'):
5700 if opts.get('remote'):
5700 raise
5701 raise
5701 return source, sbranch, None, None, None
5702 return source, sbranch, None, None, None
5702 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5703 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5703 if revs:
5704 if revs:
5704 revs = [other.lookup(rev) for rev in revs]
5705 revs = [other.lookup(rev) for rev in revs]
5705 ui.debug('comparing with %s\n' % util.hidepassword(source))
5706 ui.debug('comparing with %s\n' % util.hidepassword(source))
5706 repo.ui.pushbuffer()
5707 repo.ui.pushbuffer()
5707 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5708 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5708 repo.ui.popbuffer()
5709 repo.ui.popbuffer()
5709 return source, sbranch, other, commoninc, commoninc[1]
5710 return source, sbranch, other, commoninc, commoninc[1]
5710
5711
5711 if needsincoming:
5712 if needsincoming:
5712 source, sbranch, sother, commoninc, incoming = getincoming()
5713 source, sbranch, sother, commoninc, incoming = getincoming()
5713 else:
5714 else:
5714 source = sbranch = sother = commoninc = incoming = None
5715 source = sbranch = sother = commoninc = incoming = None
5715
5716
5716 def getoutgoing():
5717 def getoutgoing():
5717 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5718 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5718 dbranch = branches[0]
5719 dbranch = branches[0]
5719 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5720 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5720 if source != dest:
5721 if source != dest:
5721 try:
5722 try:
5722 dother = hg.peer(repo, {}, dest)
5723 dother = hg.peer(repo, {}, dest)
5723 except error.RepoError:
5724 except error.RepoError:
5724 if opts.get('remote'):
5725 if opts.get('remote'):
5725 raise
5726 raise
5726 return dest, dbranch, None, None
5727 return dest, dbranch, None, None
5727 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5728 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5728 elif sother is None:
5729 elif sother is None:
5729 # there is no explicit destination peer, but source one is invalid
5730 # there is no explicit destination peer, but source one is invalid
5730 return dest, dbranch, None, None
5731 return dest, dbranch, None, None
5731 else:
5732 else:
5732 dother = sother
5733 dother = sother
5733 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5734 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5734 common = None
5735 common = None
5735 else:
5736 else:
5736 common = commoninc
5737 common = commoninc
5737 if revs:
5738 if revs:
5738 revs = [repo.lookup(rev) for rev in revs]
5739 revs = [repo.lookup(rev) for rev in revs]
5739 repo.ui.pushbuffer()
5740 repo.ui.pushbuffer()
5740 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5741 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5741 commoninc=common)
5742 commoninc=common)
5742 repo.ui.popbuffer()
5743 repo.ui.popbuffer()
5743 return dest, dbranch, dother, outgoing
5744 return dest, dbranch, dother, outgoing
5744
5745
5745 if needsoutgoing:
5746 if needsoutgoing:
5746 dest, dbranch, dother, outgoing = getoutgoing()
5747 dest, dbranch, dother, outgoing = getoutgoing()
5747 else:
5748 else:
5748 dest = dbranch = dother = outgoing = None
5749 dest = dbranch = dother = outgoing = None
5749
5750
5750 if opts.get('remote'):
5751 if opts.get('remote'):
5751 t = []
5752 t = []
5752 if incoming:
5753 if incoming:
5753 t.append(_('1 or more incoming'))
5754 t.append(_('1 or more incoming'))
5754 o = outgoing.missing
5755 o = outgoing.missing
5755 if o:
5756 if o:
5756 t.append(_('%d outgoing') % len(o))
5757 t.append(_('%d outgoing') % len(o))
5757 other = dother or sother
5758 other = dother or sother
5758 if 'bookmarks' in other.listkeys('namespaces'):
5759 if 'bookmarks' in other.listkeys('namespaces'):
5759 counts = bookmarks.summary(repo, other)
5760 counts = bookmarks.summary(repo, other)
5760 if counts[0] > 0:
5761 if counts[0] > 0:
5761 t.append(_('%d incoming bookmarks') % counts[0])
5762 t.append(_('%d incoming bookmarks') % counts[0])
5762 if counts[1] > 0:
5763 if counts[1] > 0:
5763 t.append(_('%d outgoing bookmarks') % counts[1])
5764 t.append(_('%d outgoing bookmarks') % counts[1])
5764
5765
5765 if t:
5766 if t:
5766 # i18n: column positioning for "hg summary"
5767 # i18n: column positioning for "hg summary"
5767 ui.write(_('remote: %s\n') % (', '.join(t)))
5768 ui.write(_('remote: %s\n') % (', '.join(t)))
5768 else:
5769 else:
5769 # i18n: column positioning for "hg summary"
5770 # i18n: column positioning for "hg summary"
5770 ui.status(_('remote: (synced)\n'))
5771 ui.status(_('remote: (synced)\n'))
5771
5772
5772 cmdutil.summaryremotehooks(ui, repo, opts,
5773 cmdutil.summaryremotehooks(ui, repo, opts,
5773 ((source, sbranch, sother, commoninc),
5774 ((source, sbranch, sother, commoninc),
5774 (dest, dbranch, dother, outgoing)))
5775 (dest, dbranch, dother, outgoing)))
5775
5776
5776 @command('tag',
5777 @command('tag',
5777 [('f', 'force', None, _('force tag')),
5778 [('f', 'force', None, _('force tag')),
5778 ('l', 'local', None, _('make the tag local')),
5779 ('l', 'local', None, _('make the tag local')),
5779 ('r', 'rev', '', _('revision to tag'), _('REV')),
5780 ('r', 'rev', '', _('revision to tag'), _('REV')),
5780 ('', 'remove', None, _('remove a tag')),
5781 ('', 'remove', None, _('remove a tag')),
5781 # -l/--local is already there, commitopts cannot be used
5782 # -l/--local is already there, commitopts cannot be used
5782 ('e', 'edit', None, _('invoke editor on commit messages')),
5783 ('e', 'edit', None, _('invoke editor on commit messages')),
5783 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5784 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5784 ] + commitopts2,
5785 ] + commitopts2,
5785 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'),
5786 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'),
5786 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION)
5787 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION)
5787 def tag(ui, repo, name1, *names, **opts):
5788 def tag(ui, repo, name1, *names, **opts):
5788 """add one or more tags for the current or given revision
5789 """add one or more tags for the current or given revision
5789
5790
5790 Name a particular revision using <name>.
5791 Name a particular revision using <name>.
5791
5792
5792 Tags are used to name particular revisions of the repository and are
5793 Tags are used to name particular revisions of the repository and are
5793 very useful to compare different revisions, to go back to significant
5794 very useful to compare different revisions, to go back to significant
5794 earlier versions or to mark branch points as releases, etc. Changing
5795 earlier versions or to mark branch points as releases, etc. Changing
5795 an existing tag is normally disallowed; use -f/--force to override.
5796 an existing tag is normally disallowed; use -f/--force to override.
5796
5797
5797 If no revision is given, the parent of the working directory is
5798 If no revision is given, the parent of the working directory is
5798 used.
5799 used.
5799
5800
5800 To facilitate version control, distribution, and merging of tags,
5801 To facilitate version control, distribution, and merging of tags,
5801 they are stored as a file named ".hgtags" which is managed similarly
5802 they are stored as a file named ".hgtags" which is managed similarly
5802 to other project files and can be hand-edited if necessary. This
5803 to other project files and can be hand-edited if necessary. This
5803 also means that tagging creates a new commit. The file
5804 also means that tagging creates a new commit. The file
5804 ".hg/localtags" is used for local tags (not shared among
5805 ".hg/localtags" is used for local tags (not shared among
5805 repositories).
5806 repositories).
5806
5807
5807 Tag commits are usually made at the head of a branch. If the parent
5808 Tag commits are usually made at the head of a branch. If the parent
5808 of the working directory is not a branch head, :hg:`tag` aborts; use
5809 of the working directory is not a branch head, :hg:`tag` aborts; use
5809 -f/--force to force the tag commit to be based on a non-head
5810 -f/--force to force the tag commit to be based on a non-head
5810 changeset.
5811 changeset.
5811
5812
5812 See :hg:`help dates` for a list of formats valid for -d/--date.
5813 See :hg:`help dates` for a list of formats valid for -d/--date.
5813
5814
5814 Since tag names have priority over branch names during revision
5815 Since tag names have priority over branch names during revision
5815 lookup, using an existing branch name as a tag name is discouraged.
5816 lookup, using an existing branch name as a tag name is discouraged.
5816
5817
5817 Returns 0 on success.
5818 Returns 0 on success.
5818 """
5819 """
5819 opts = pycompat.byteskwargs(opts)
5820 opts = pycompat.byteskwargs(opts)
5820 with repo.wlock(), repo.lock():
5821 with repo.wlock(), repo.lock():
5821 rev_ = "."
5822 rev_ = "."
5822 names = [t.strip() for t in (name1,) + names]
5823 names = [t.strip() for t in (name1,) + names]
5823 if len(names) != len(set(names)):
5824 if len(names) != len(set(names)):
5824 raise error.Abort(_('tag names must be unique'))
5825 raise error.Abort(_('tag names must be unique'))
5825 for n in names:
5826 for n in names:
5826 scmutil.checknewlabel(repo, n, 'tag')
5827 scmutil.checknewlabel(repo, n, 'tag')
5827 if not n:
5828 if not n:
5828 raise error.Abort(_('tag names cannot consist entirely of '
5829 raise error.Abort(_('tag names cannot consist entirely of '
5829 'whitespace'))
5830 'whitespace'))
5830 if opts.get('rev') and opts.get('remove'):
5831 if opts.get('rev') and opts.get('remove'):
5831 raise error.Abort(_("--rev and --remove are incompatible"))
5832 raise error.Abort(_("--rev and --remove are incompatible"))
5832 if opts.get('rev'):
5833 if opts.get('rev'):
5833 rev_ = opts['rev']
5834 rev_ = opts['rev']
5834 message = opts.get('message')
5835 message = opts.get('message')
5835 if opts.get('remove'):
5836 if opts.get('remove'):
5836 if opts.get('local'):
5837 if opts.get('local'):
5837 expectedtype = 'local'
5838 expectedtype = 'local'
5838 else:
5839 else:
5839 expectedtype = 'global'
5840 expectedtype = 'global'
5840
5841
5841 for n in names:
5842 for n in names:
5842 if repo.tagtype(n) == 'global':
5843 if repo.tagtype(n) == 'global':
5843 alltags = tagsmod.findglobaltags(ui, repo)
5844 alltags = tagsmod.findglobaltags(ui, repo)
5844 if alltags[n][0] == nullid:
5845 if alltags[n][0] == nullid:
5845 raise error.Abort(_("tag '%s' is already removed") % n)
5846 raise error.Abort(_("tag '%s' is already removed") % n)
5846 if not repo.tagtype(n):
5847 if not repo.tagtype(n):
5847 raise error.Abort(_("tag '%s' does not exist") % n)
5848 raise error.Abort(_("tag '%s' does not exist") % n)
5848 if repo.tagtype(n) != expectedtype:
5849 if repo.tagtype(n) != expectedtype:
5849 if expectedtype == 'global':
5850 if expectedtype == 'global':
5850 raise error.Abort(_("tag '%s' is not a global tag") % n)
5851 raise error.Abort(_("tag '%s' is not a global tag") % n)
5851 else:
5852 else:
5852 raise error.Abort(_("tag '%s' is not a local tag") % n)
5853 raise error.Abort(_("tag '%s' is not a local tag") % n)
5853 rev_ = 'null'
5854 rev_ = 'null'
5854 if not message:
5855 if not message:
5855 # we don't translate commit messages
5856 # we don't translate commit messages
5856 message = 'Removed tag %s' % ', '.join(names)
5857 message = 'Removed tag %s' % ', '.join(names)
5857 elif not opts.get('force'):
5858 elif not opts.get('force'):
5858 for n in names:
5859 for n in names:
5859 if n in repo.tags():
5860 if n in repo.tags():
5860 raise error.Abort(_("tag '%s' already exists "
5861 raise error.Abort(_("tag '%s' already exists "
5861 "(use -f to force)") % n)
5862 "(use -f to force)") % n)
5862 if not opts.get('local'):
5863 if not opts.get('local'):
5863 p1, p2 = repo.dirstate.parents()
5864 p1, p2 = repo.dirstate.parents()
5864 if p2 != nullid:
5865 if p2 != nullid:
5865 raise error.Abort(_('uncommitted merge'))
5866 raise error.Abort(_('uncommitted merge'))
5866 bheads = repo.branchheads()
5867 bheads = repo.branchheads()
5867 if not opts.get('force') and bheads and p1 not in bheads:
5868 if not opts.get('force') and bheads and p1 not in bheads:
5868 raise error.Abort(_('working directory is not at a branch head '
5869 raise error.Abort(_('working directory is not at a branch head '
5869 '(use -f to force)'))
5870 '(use -f to force)'))
5870 node = scmutil.revsingle(repo, rev_).node()
5871 node = scmutil.revsingle(repo, rev_).node()
5871
5872
5872 if not message:
5873 if not message:
5873 # we don't translate commit messages
5874 # we don't translate commit messages
5874 message = ('Added tag %s for changeset %s' %
5875 message = ('Added tag %s for changeset %s' %
5875 (', '.join(names), short(node)))
5876 (', '.join(names), short(node)))
5876
5877
5877 date = opts.get('date')
5878 date = opts.get('date')
5878 if date:
5879 if date:
5879 date = dateutil.parsedate(date)
5880 date = dateutil.parsedate(date)
5880
5881
5881 if opts.get('remove'):
5882 if opts.get('remove'):
5882 editform = 'tag.remove'
5883 editform = 'tag.remove'
5883 else:
5884 else:
5884 editform = 'tag.add'
5885 editform = 'tag.add'
5885 editor = cmdutil.getcommiteditor(editform=editform,
5886 editor = cmdutil.getcommiteditor(editform=editform,
5886 **pycompat.strkwargs(opts))
5887 **pycompat.strkwargs(opts))
5887
5888
5888 # don't allow tagging the null rev
5889 # don't allow tagging the null rev
5889 if (not opts.get('remove') and
5890 if (not opts.get('remove') and
5890 scmutil.revsingle(repo, rev_).rev() == nullrev):
5891 scmutil.revsingle(repo, rev_).rev() == nullrev):
5891 raise error.Abort(_("cannot tag null revision"))
5892 raise error.Abort(_("cannot tag null revision"))
5892
5893
5893 tagsmod.tag(repo, names, node, message, opts.get('local'),
5894 tagsmod.tag(repo, names, node, message, opts.get('local'),
5894 opts.get('user'), date, editor=editor)
5895 opts.get('user'), date, editor=editor)
5895
5896
5896 @command(
5897 @command(
5897 'tags', formatteropts, '',
5898 'tags', formatteropts, '',
5898 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
5899 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
5899 intents={INTENT_READONLY})
5900 intents={INTENT_READONLY})
5900 def tags(ui, repo, **opts):
5901 def tags(ui, repo, **opts):
5901 """list repository tags
5902 """list repository tags
5902
5903
5903 This lists both regular and local tags. When the -v/--verbose
5904 This lists both regular and local tags. When the -v/--verbose
5904 switch is used, a third column "local" is printed for local tags.
5905 switch is used, a third column "local" is printed for local tags.
5905 When the -q/--quiet switch is used, only the tag name is printed.
5906 When the -q/--quiet switch is used, only the tag name is printed.
5906
5907
5907 .. container:: verbose
5908 .. container:: verbose
5908
5909
5909 Template:
5910 Template:
5910
5911
5911 The following keywords are supported in addition to the common template
5912 The following keywords are supported in addition to the common template
5912 keywords and functions such as ``{tag}``. See also
5913 keywords and functions such as ``{tag}``. See also
5913 :hg:`help templates`.
5914 :hg:`help templates`.
5914
5915
5915 :type: String. ``local`` for local tags.
5916 :type: String. ``local`` for local tags.
5916
5917
5917 Returns 0 on success.
5918 Returns 0 on success.
5918 """
5919 """
5919
5920
5920 opts = pycompat.byteskwargs(opts)
5921 opts = pycompat.byteskwargs(opts)
5921 ui.pager('tags')
5922 ui.pager('tags')
5922 fm = ui.formatter('tags', opts)
5923 fm = ui.formatter('tags', opts)
5923 hexfunc = fm.hexfunc
5924 hexfunc = fm.hexfunc
5924
5925
5925 for t, n in reversed(repo.tagslist()):
5926 for t, n in reversed(repo.tagslist()):
5926 hn = hexfunc(n)
5927 hn = hexfunc(n)
5927 label = 'tags.normal'
5928 label = 'tags.normal'
5928 tagtype = ''
5929 tagtype = ''
5929 if repo.tagtype(t) == 'local':
5930 if repo.tagtype(t) == 'local':
5930 label = 'tags.local'
5931 label = 'tags.local'
5931 tagtype = 'local'
5932 tagtype = 'local'
5932
5933
5933 fm.startitem()
5934 fm.startitem()
5934 fm.context(repo=repo)
5935 fm.context(repo=repo)
5935 fm.write('tag', '%s', t, label=label)
5936 fm.write('tag', '%s', t, label=label)
5936 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5937 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5937 fm.condwrite(not ui.quiet, 'rev node', fmt,
5938 fm.condwrite(not ui.quiet, 'rev node', fmt,
5938 repo.changelog.rev(n), hn, label=label)
5939 repo.changelog.rev(n), hn, label=label)
5939 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5940 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5940 tagtype, label=label)
5941 tagtype, label=label)
5941 fm.plain('\n')
5942 fm.plain('\n')
5942 fm.end()
5943 fm.end()
5943
5944
5944 @command('tip',
5945 @command('tip',
5945 [('p', 'patch', None, _('show patch')),
5946 [('p', 'patch', None, _('show patch')),
5946 ('g', 'git', None, _('use git extended diff format')),
5947 ('g', 'git', None, _('use git extended diff format')),
5947 ] + templateopts,
5948 ] + templateopts,
5948 _('[-p] [-g]'),
5949 _('[-p] [-g]'),
5949 helpcategory=command.CATEGORY_CHANGE_NAVIGATION)
5950 helpcategory=command.CATEGORY_CHANGE_NAVIGATION)
5950 def tip(ui, repo, **opts):
5951 def tip(ui, repo, **opts):
5951 """show the tip revision (DEPRECATED)
5952 """show the tip revision (DEPRECATED)
5952
5953
5953 The tip revision (usually just called the tip) is the changeset
5954 The tip revision (usually just called the tip) is the changeset
5954 most recently added to the repository (and therefore the most
5955 most recently added to the repository (and therefore the most
5955 recently changed head).
5956 recently changed head).
5956
5957
5957 If you have just made a commit, that commit will be the tip. If
5958 If you have just made a commit, that commit will be the tip. If
5958 you have just pulled changes from another repository, the tip of
5959 you have just pulled changes from another repository, the tip of
5959 that repository becomes the current tip. The "tip" tag is special
5960 that repository becomes the current tip. The "tip" tag is special
5960 and cannot be renamed or assigned to a different changeset.
5961 and cannot be renamed or assigned to a different changeset.
5961
5962
5962 This command is deprecated, please use :hg:`heads` instead.
5963 This command is deprecated, please use :hg:`heads` instead.
5963
5964
5964 Returns 0 on success.
5965 Returns 0 on success.
5965 """
5966 """
5966 opts = pycompat.byteskwargs(opts)
5967 opts = pycompat.byteskwargs(opts)
5967 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
5968 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
5968 displayer.show(repo['tip'])
5969 displayer.show(repo['tip'])
5969 displayer.close()
5970 displayer.close()
5970
5971
5971 @command('unbundle',
5972 @command('unbundle',
5972 [('u', 'update', None,
5973 [('u', 'update', None,
5973 _('update to new branch head if changesets were unbundled'))],
5974 _('update to new branch head if changesets were unbundled'))],
5974 _('[-u] FILE...'),
5975 _('[-u] FILE...'),
5975 helpcategory=command.CATEGORY_IMPORT_EXPORT)
5976 helpcategory=command.CATEGORY_IMPORT_EXPORT)
5976 def unbundle(ui, repo, fname1, *fnames, **opts):
5977 def unbundle(ui, repo, fname1, *fnames, **opts):
5977 """apply one or more bundle files
5978 """apply one or more bundle files
5978
5979
5979 Apply one or more bundle files generated by :hg:`bundle`.
5980 Apply one or more bundle files generated by :hg:`bundle`.
5980
5981
5981 Returns 0 on success, 1 if an update has unresolved files.
5982 Returns 0 on success, 1 if an update has unresolved files.
5982 """
5983 """
5983 fnames = (fname1,) + fnames
5984 fnames = (fname1,) + fnames
5984
5985
5985 with repo.lock():
5986 with repo.lock():
5986 for fname in fnames:
5987 for fname in fnames:
5987 f = hg.openpath(ui, fname)
5988 f = hg.openpath(ui, fname)
5988 gen = exchange.readbundle(ui, f, fname)
5989 gen = exchange.readbundle(ui, f, fname)
5989 if isinstance(gen, streamclone.streamcloneapplier):
5990 if isinstance(gen, streamclone.streamcloneapplier):
5990 raise error.Abort(
5991 raise error.Abort(
5991 _('packed bundles cannot be applied with '
5992 _('packed bundles cannot be applied with '
5992 '"hg unbundle"'),
5993 '"hg unbundle"'),
5993 hint=_('use "hg debugapplystreamclonebundle"'))
5994 hint=_('use "hg debugapplystreamclonebundle"'))
5994 url = 'bundle:' + fname
5995 url = 'bundle:' + fname
5995 try:
5996 try:
5996 txnname = 'unbundle'
5997 txnname = 'unbundle'
5997 if not isinstance(gen, bundle2.unbundle20):
5998 if not isinstance(gen, bundle2.unbundle20):
5998 txnname = 'unbundle\n%s' % util.hidepassword(url)
5999 txnname = 'unbundle\n%s' % util.hidepassword(url)
5999 with repo.transaction(txnname) as tr:
6000 with repo.transaction(txnname) as tr:
6000 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
6001 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
6001 url=url)
6002 url=url)
6002 except error.BundleUnknownFeatureError as exc:
6003 except error.BundleUnknownFeatureError as exc:
6003 raise error.Abort(
6004 raise error.Abort(
6004 _('%s: unknown bundle feature, %s') % (fname, exc),
6005 _('%s: unknown bundle feature, %s') % (fname, exc),
6005 hint=_("see https://mercurial-scm.org/"
6006 hint=_("see https://mercurial-scm.org/"
6006 "wiki/BundleFeature for more "
6007 "wiki/BundleFeature for more "
6007 "information"))
6008 "information"))
6008 modheads = bundle2.combinechangegroupresults(op)
6009 modheads = bundle2.combinechangegroupresults(op)
6009
6010
6010 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
6011 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
6011
6012
6012 @command('update|up|checkout|co',
6013 @command('update|up|checkout|co',
6013 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
6014 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
6014 ('c', 'check', None, _('require clean working directory')),
6015 ('c', 'check', None, _('require clean working directory')),
6015 ('m', 'merge', None, _('merge uncommitted changes')),
6016 ('m', 'merge', None, _('merge uncommitted changes')),
6016 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
6017 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
6017 ('r', 'rev', '', _('revision'), _('REV'))
6018 ('r', 'rev', '', _('revision'), _('REV'))
6018 ] + mergetoolopts,
6019 ] + mergetoolopts,
6019 _('[-C|-c|-m] [-d DATE] [[-r] REV]'),
6020 _('[-C|-c|-m] [-d DATE] [[-r] REV]'),
6020 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6021 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6021 helpbasic=True)
6022 helpbasic=True)
6022 def update(ui, repo, node=None, **opts):
6023 def update(ui, repo, node=None, **opts):
6023 """update working directory (or switch revisions)
6024 """update working directory (or switch revisions)
6024
6025
6025 Update the repository's working directory to the specified
6026 Update the repository's working directory to the specified
6026 changeset. If no changeset is specified, update to the tip of the
6027 changeset. If no changeset is specified, update to the tip of the
6027 current named branch and move the active bookmark (see :hg:`help
6028 current named branch and move the active bookmark (see :hg:`help
6028 bookmarks`).
6029 bookmarks`).
6029
6030
6030 Update sets the working directory's parent revision to the specified
6031 Update sets the working directory's parent revision to the specified
6031 changeset (see :hg:`help parents`).
6032 changeset (see :hg:`help parents`).
6032
6033
6033 If the changeset is not a descendant or ancestor of the working
6034 If the changeset is not a descendant or ancestor of the working
6034 directory's parent and there are uncommitted changes, the update is
6035 directory's parent and there are uncommitted changes, the update is
6035 aborted. With the -c/--check option, the working directory is checked
6036 aborted. With the -c/--check option, the working directory is checked
6036 for uncommitted changes; if none are found, the working directory is
6037 for uncommitted changes; if none are found, the working directory is
6037 updated to the specified changeset.
6038 updated to the specified changeset.
6038
6039
6039 .. container:: verbose
6040 .. container:: verbose
6040
6041
6041 The -C/--clean, -c/--check, and -m/--merge options control what
6042 The -C/--clean, -c/--check, and -m/--merge options control what
6042 happens if the working directory contains uncommitted changes.
6043 happens if the working directory contains uncommitted changes.
6043 At most of one of them can be specified.
6044 At most of one of them can be specified.
6044
6045
6045 1. If no option is specified, and if
6046 1. If no option is specified, and if
6046 the requested changeset is an ancestor or descendant of
6047 the requested changeset is an ancestor or descendant of
6047 the working directory's parent, the uncommitted changes
6048 the working directory's parent, the uncommitted changes
6048 are merged into the requested changeset and the merged
6049 are merged into the requested changeset and the merged
6049 result is left uncommitted. If the requested changeset is
6050 result is left uncommitted. If the requested changeset is
6050 not an ancestor or descendant (that is, it is on another
6051 not an ancestor or descendant (that is, it is on another
6051 branch), the update is aborted and the uncommitted changes
6052 branch), the update is aborted and the uncommitted changes
6052 are preserved.
6053 are preserved.
6053
6054
6054 2. With the -m/--merge option, the update is allowed even if the
6055 2. With the -m/--merge option, the update is allowed even if the
6055 requested changeset is not an ancestor or descendant of
6056 requested changeset is not an ancestor or descendant of
6056 the working directory's parent.
6057 the working directory's parent.
6057
6058
6058 3. With the -c/--check option, the update is aborted and the
6059 3. With the -c/--check option, the update is aborted and the
6059 uncommitted changes are preserved.
6060 uncommitted changes are preserved.
6060
6061
6061 4. With the -C/--clean option, uncommitted changes are discarded and
6062 4. With the -C/--clean option, uncommitted changes are discarded and
6062 the working directory is updated to the requested changeset.
6063 the working directory is updated to the requested changeset.
6063
6064
6064 To cancel an uncommitted merge (and lose your changes), use
6065 To cancel an uncommitted merge (and lose your changes), use
6065 :hg:`merge --abort`.
6066 :hg:`merge --abort`.
6066
6067
6067 Use null as the changeset to remove the working directory (like
6068 Use null as the changeset to remove the working directory (like
6068 :hg:`clone -U`).
6069 :hg:`clone -U`).
6069
6070
6070 If you want to revert just one file to an older revision, use
6071 If you want to revert just one file to an older revision, use
6071 :hg:`revert [-r REV] NAME`.
6072 :hg:`revert [-r REV] NAME`.
6072
6073
6073 See :hg:`help dates` for a list of formats valid for -d/--date.
6074 See :hg:`help dates` for a list of formats valid for -d/--date.
6074
6075
6075 Returns 0 on success, 1 if there are unresolved files.
6076 Returns 0 on success, 1 if there are unresolved files.
6076 """
6077 """
6077 rev = opts.get(r'rev')
6078 rev = opts.get(r'rev')
6078 date = opts.get(r'date')
6079 date = opts.get(r'date')
6079 clean = opts.get(r'clean')
6080 clean = opts.get(r'clean')
6080 check = opts.get(r'check')
6081 check = opts.get(r'check')
6081 merge = opts.get(r'merge')
6082 merge = opts.get(r'merge')
6082 if rev and node:
6083 if rev and node:
6083 raise error.Abort(_("please specify just one revision"))
6084 raise error.Abort(_("please specify just one revision"))
6084
6085
6085 if ui.configbool('commands', 'update.requiredest'):
6086 if ui.configbool('commands', 'update.requiredest'):
6086 if not node and not rev and not date:
6087 if not node and not rev and not date:
6087 raise error.Abort(_('you must specify a destination'),
6088 raise error.Abort(_('you must specify a destination'),
6088 hint=_('for example: hg update ".::"'))
6089 hint=_('for example: hg update ".::"'))
6089
6090
6090 if rev is None or rev == '':
6091 if rev is None or rev == '':
6091 rev = node
6092 rev = node
6092
6093
6093 if date and rev is not None:
6094 if date and rev is not None:
6094 raise error.Abort(_("you can't specify a revision and a date"))
6095 raise error.Abort(_("you can't specify a revision and a date"))
6095
6096
6096 if len([x for x in (clean, check, merge) if x]) > 1:
6097 if len([x for x in (clean, check, merge) if x]) > 1:
6097 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
6098 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
6098 "or -m/--merge"))
6099 "or -m/--merge"))
6099
6100
6100 updatecheck = None
6101 updatecheck = None
6101 if check:
6102 if check:
6102 updatecheck = 'abort'
6103 updatecheck = 'abort'
6103 elif merge:
6104 elif merge:
6104 updatecheck = 'none'
6105 updatecheck = 'none'
6105
6106
6106 with repo.wlock():
6107 with repo.wlock():
6107 cmdutil.clearunfinished(repo)
6108 cmdutil.clearunfinished(repo)
6108
6109
6109 if date:
6110 if date:
6110 rev = cmdutil.finddate(ui, repo, date)
6111 rev = cmdutil.finddate(ui, repo, date)
6111
6112
6112 # if we defined a bookmark, we have to remember the original name
6113 # if we defined a bookmark, we have to remember the original name
6113 brev = rev
6114 brev = rev
6114 if rev:
6115 if rev:
6115 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
6116 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
6116 ctx = scmutil.revsingle(repo, rev, default=None)
6117 ctx = scmutil.revsingle(repo, rev, default=None)
6117 rev = ctx.rev()
6118 rev = ctx.rev()
6118 hidden = ctx.hidden()
6119 hidden = ctx.hidden()
6119 overrides = {('ui', 'forcemerge'): opts.get(r'tool', '')}
6120 overrides = {('ui', 'forcemerge'): opts.get(r'tool', '')}
6120 with ui.configoverride(overrides, 'update'):
6121 with ui.configoverride(overrides, 'update'):
6121 ret = hg.updatetotally(ui, repo, rev, brev, clean=clean,
6122 ret = hg.updatetotally(ui, repo, rev, brev, clean=clean,
6122 updatecheck=updatecheck)
6123 updatecheck=updatecheck)
6123 if hidden:
6124 if hidden:
6124 ctxstr = ctx.hex()[:12]
6125 ctxstr = ctx.hex()[:12]
6125 ui.warn(_("updated to hidden changeset %s\n") % ctxstr)
6126 ui.warn(_("updated to hidden changeset %s\n") % ctxstr)
6126
6127
6127 if ctx.obsolete():
6128 if ctx.obsolete():
6128 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
6129 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
6129 ui.warn("(%s)\n" % obsfatemsg)
6130 ui.warn("(%s)\n" % obsfatemsg)
6130 return ret
6131 return ret
6131
6132
6132 @command('verify', [], helpcategory=command.CATEGORY_MAINTENANCE)
6133 @command('verify', [], helpcategory=command.CATEGORY_MAINTENANCE)
6133 def verify(ui, repo):
6134 def verify(ui, repo):
6134 """verify the integrity of the repository
6135 """verify the integrity of the repository
6135
6136
6136 Verify the integrity of the current repository.
6137 Verify the integrity of the current repository.
6137
6138
6138 This will perform an extensive check of the repository's
6139 This will perform an extensive check of the repository's
6139 integrity, validating the hashes and checksums of each entry in
6140 integrity, validating the hashes and checksums of each entry in
6140 the changelog, manifest, and tracked files, as well as the
6141 the changelog, manifest, and tracked files, as well as the
6141 integrity of their crosslinks and indices.
6142 integrity of their crosslinks and indices.
6142
6143
6143 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
6144 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
6144 for more information about recovery from corruption of the
6145 for more information about recovery from corruption of the
6145 repository.
6146 repository.
6146
6147
6147 Returns 0 on success, 1 if errors are encountered.
6148 Returns 0 on success, 1 if errors are encountered.
6148 """
6149 """
6149 return hg.verify(repo)
6150 return hg.verify(repo)
6150
6151
6151 @command(
6152 @command(
6152 'version', [] + formatteropts, helpcategory=command.CATEGORY_HELP,
6153 'version', [] + formatteropts, helpcategory=command.CATEGORY_HELP,
6153 norepo=True, intents={INTENT_READONLY})
6154 norepo=True, intents={INTENT_READONLY})
6154 def version_(ui, **opts):
6155 def version_(ui, **opts):
6155 """output version and copyright information
6156 """output version and copyright information
6156
6157
6157 .. container:: verbose
6158 .. container:: verbose
6158
6159
6159 Template:
6160 Template:
6160
6161
6161 The following keywords are supported. See also :hg:`help templates`.
6162 The following keywords are supported. See also :hg:`help templates`.
6162
6163
6163 :extensions: List of extensions.
6164 :extensions: List of extensions.
6164 :ver: String. Version number.
6165 :ver: String. Version number.
6165
6166
6166 And each entry of ``{extensions}`` provides the following sub-keywords
6167 And each entry of ``{extensions}`` provides the following sub-keywords
6167 in addition to ``{ver}``.
6168 in addition to ``{ver}``.
6168
6169
6169 :bundled: Boolean. True if included in the release.
6170 :bundled: Boolean. True if included in the release.
6170 :name: String. Extension name.
6171 :name: String. Extension name.
6171 """
6172 """
6172 opts = pycompat.byteskwargs(opts)
6173 opts = pycompat.byteskwargs(opts)
6173 if ui.verbose:
6174 if ui.verbose:
6174 ui.pager('version')
6175 ui.pager('version')
6175 fm = ui.formatter("version", opts)
6176 fm = ui.formatter("version", opts)
6176 fm.startitem()
6177 fm.startitem()
6177 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
6178 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
6178 util.version())
6179 util.version())
6179 license = _(
6180 license = _(
6180 "(see https://mercurial-scm.org for more information)\n"
6181 "(see https://mercurial-scm.org for more information)\n"
6181 "\nCopyright (C) 2005-2019 Matt Mackall and others\n"
6182 "\nCopyright (C) 2005-2019 Matt Mackall and others\n"
6182 "This is free software; see the source for copying conditions. "
6183 "This is free software; see the source for copying conditions. "
6183 "There is NO\nwarranty; "
6184 "There is NO\nwarranty; "
6184 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
6185 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
6185 )
6186 )
6186 if not ui.quiet:
6187 if not ui.quiet:
6187 fm.plain(license)
6188 fm.plain(license)
6188
6189
6189 if ui.verbose:
6190 if ui.verbose:
6190 fm.plain(_("\nEnabled extensions:\n\n"))
6191 fm.plain(_("\nEnabled extensions:\n\n"))
6191 # format names and versions into columns
6192 # format names and versions into columns
6192 names = []
6193 names = []
6193 vers = []
6194 vers = []
6194 isinternals = []
6195 isinternals = []
6195 for name, module in extensions.extensions():
6196 for name, module in extensions.extensions():
6196 names.append(name)
6197 names.append(name)
6197 vers.append(extensions.moduleversion(module) or None)
6198 vers.append(extensions.moduleversion(module) or None)
6198 isinternals.append(extensions.ismoduleinternal(module))
6199 isinternals.append(extensions.ismoduleinternal(module))
6199 fn = fm.nested("extensions", tmpl='{name}\n')
6200 fn = fm.nested("extensions", tmpl='{name}\n')
6200 if names:
6201 if names:
6201 namefmt = " %%-%ds " % max(len(n) for n in names)
6202 namefmt = " %%-%ds " % max(len(n) for n in names)
6202 places = [_("external"), _("internal")]
6203 places = [_("external"), _("internal")]
6203 for n, v, p in zip(names, vers, isinternals):
6204 for n, v, p in zip(names, vers, isinternals):
6204 fn.startitem()
6205 fn.startitem()
6205 fn.condwrite(ui.verbose, "name", namefmt, n)
6206 fn.condwrite(ui.verbose, "name", namefmt, n)
6206 if ui.verbose:
6207 if ui.verbose:
6207 fn.plain("%s " % places[p])
6208 fn.plain("%s " % places[p])
6208 fn.data(bundled=p)
6209 fn.data(bundled=p)
6209 fn.condwrite(ui.verbose and v, "ver", "%s", v)
6210 fn.condwrite(ui.verbose and v, "ver", "%s", v)
6210 if ui.verbose:
6211 if ui.verbose:
6211 fn.plain("\n")
6212 fn.plain("\n")
6212 fn.end()
6213 fn.end()
6213 fm.end()
6214 fm.end()
6214
6215
6215 def loadcmdtable(ui, name, cmdtable):
6216 def loadcmdtable(ui, name, cmdtable):
6216 """Load command functions from specified cmdtable
6217 """Load command functions from specified cmdtable
6217 """
6218 """
6218 cmdtable = cmdtable.copy()
6219 cmdtable = cmdtable.copy()
6219 for cmd in list(cmdtable):
6220 for cmd in list(cmdtable):
6220 if not cmd.startswith('^'):
6221 if not cmd.startswith('^'):
6221 continue
6222 continue
6222 ui.deprecwarn("old-style command registration '%s' in extension '%s'"
6223 ui.deprecwarn("old-style command registration '%s' in extension '%s'"
6223 % (cmd, name), '4.8')
6224 % (cmd, name), '4.8')
6224 entry = cmdtable.pop(cmd)
6225 entry = cmdtable.pop(cmd)
6225 entry[0].helpbasic = True
6226 entry[0].helpbasic = True
6226 cmdtable[cmd[1:]] = entry
6227 cmdtable[cmd[1:]] = entry
6227
6228
6228 overrides = [cmd for cmd in cmdtable if cmd in table]
6229 overrides = [cmd for cmd in cmdtable if cmd in table]
6229 if overrides:
6230 if overrides:
6230 ui.warn(_("extension '%s' overrides commands: %s\n")
6231 ui.warn(_("extension '%s' overrides commands: %s\n")
6231 % (name, " ".join(overrides)))
6232 % (name, " ".join(overrides)))
6232 table.update(cmdtable)
6233 table.update(cmdtable)
@@ -1,1840 +1,1840 b''
1 # subrepo.py - sub-repository classes and factory
1 # subrepo.py - sub-repository classes and factory
2 #
2 #
3 # Copyright 2009-2010 Matt Mackall <mpm@selenic.com>
3 # Copyright 2009-2010 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import copy
10 import copy
11 import errno
11 import errno
12 import hashlib
12 import hashlib
13 import os
13 import os
14 import re
14 import re
15 import stat
15 import stat
16 import subprocess
16 import subprocess
17 import sys
17 import sys
18 import tarfile
18 import tarfile
19 import xml.dom.minidom
19 import xml.dom.minidom
20
20
21 from .i18n import _
21 from .i18n import _
22 from . import (
22 from . import (
23 cmdutil,
23 cmdutil,
24 encoding,
24 encoding,
25 error,
25 error,
26 exchange,
26 exchange,
27 logcmdutil,
27 logcmdutil,
28 match as matchmod,
28 match as matchmod,
29 node,
29 node,
30 pathutil,
30 pathutil,
31 phases,
31 phases,
32 pycompat,
32 pycompat,
33 scmutil,
33 scmutil,
34 subrepoutil,
34 subrepoutil,
35 util,
35 util,
36 vfs as vfsmod,
36 vfs as vfsmod,
37 )
37 )
38 from .utils import (
38 from .utils import (
39 dateutil,
39 dateutil,
40 procutil,
40 procutil,
41 stringutil,
41 stringutil,
42 )
42 )
43
43
44 hg = None
44 hg = None
45 reporelpath = subrepoutil.reporelpath
45 reporelpath = subrepoutil.reporelpath
46 subrelpath = subrepoutil.subrelpath
46 subrelpath = subrepoutil.subrelpath
47 _abssource = subrepoutil._abssource
47 _abssource = subrepoutil._abssource
48 propertycache = util.propertycache
48 propertycache = util.propertycache
49
49
50 def _expandedabspath(path):
50 def _expandedabspath(path):
51 '''
51 '''
52 get a path or url and if it is a path expand it and return an absolute path
52 get a path or url and if it is a path expand it and return an absolute path
53 '''
53 '''
54 expandedpath = util.urllocalpath(util.expandpath(path))
54 expandedpath = util.urllocalpath(util.expandpath(path))
55 u = util.url(expandedpath)
55 u = util.url(expandedpath)
56 if not u.scheme:
56 if not u.scheme:
57 path = util.normpath(os.path.abspath(u.path))
57 path = util.normpath(os.path.abspath(u.path))
58 return path
58 return path
59
59
60 def _getstorehashcachename(remotepath):
60 def _getstorehashcachename(remotepath):
61 '''get a unique filename for the store hash cache of a remote repository'''
61 '''get a unique filename for the store hash cache of a remote repository'''
62 return node.hex(hashlib.sha1(_expandedabspath(remotepath)).digest())[0:12]
62 return node.hex(hashlib.sha1(_expandedabspath(remotepath)).digest())[0:12]
63
63
64 class SubrepoAbort(error.Abort):
64 class SubrepoAbort(error.Abort):
65 """Exception class used to avoid handling a subrepo error more than once"""
65 """Exception class used to avoid handling a subrepo error more than once"""
66 def __init__(self, *args, **kw):
66 def __init__(self, *args, **kw):
67 self.subrepo = kw.pop(r'subrepo', None)
67 self.subrepo = kw.pop(r'subrepo', None)
68 self.cause = kw.pop(r'cause', None)
68 self.cause = kw.pop(r'cause', None)
69 error.Abort.__init__(self, *args, **kw)
69 error.Abort.__init__(self, *args, **kw)
70
70
71 def annotatesubrepoerror(func):
71 def annotatesubrepoerror(func):
72 def decoratedmethod(self, *args, **kargs):
72 def decoratedmethod(self, *args, **kargs):
73 try:
73 try:
74 res = func(self, *args, **kargs)
74 res = func(self, *args, **kargs)
75 except SubrepoAbort as ex:
75 except SubrepoAbort as ex:
76 # This exception has already been handled
76 # This exception has already been handled
77 raise ex
77 raise ex
78 except error.Abort as ex:
78 except error.Abort as ex:
79 subrepo = subrelpath(self)
79 subrepo = subrelpath(self)
80 errormsg = (stringutil.forcebytestr(ex) + ' '
80 errormsg = (stringutil.forcebytestr(ex) + ' '
81 + _('(in subrepository "%s")') % subrepo)
81 + _('(in subrepository "%s")') % subrepo)
82 # avoid handling this exception by raising a SubrepoAbort exception
82 # avoid handling this exception by raising a SubrepoAbort exception
83 raise SubrepoAbort(errormsg, hint=ex.hint, subrepo=subrepo,
83 raise SubrepoAbort(errormsg, hint=ex.hint, subrepo=subrepo,
84 cause=sys.exc_info())
84 cause=sys.exc_info())
85 return res
85 return res
86 return decoratedmethod
86 return decoratedmethod
87
87
88 def _updateprompt(ui, sub, dirty, local, remote):
88 def _updateprompt(ui, sub, dirty, local, remote):
89 if dirty:
89 if dirty:
90 msg = (_(' subrepository sources for %s differ\n'
90 msg = (_(' subrepository sources for %s differ\n'
91 'use (l)ocal source (%s) or (r)emote source (%s)?'
91 'use (l)ocal source (%s) or (r)emote source (%s)?'
92 '$$ &Local $$ &Remote')
92 '$$ &Local $$ &Remote')
93 % (subrelpath(sub), local, remote))
93 % (subrelpath(sub), local, remote))
94 else:
94 else:
95 msg = (_(' subrepository sources for %s differ (in checked out '
95 msg = (_(' subrepository sources for %s differ (in checked out '
96 'version)\n'
96 'version)\n'
97 'use (l)ocal source (%s) or (r)emote source (%s)?'
97 'use (l)ocal source (%s) or (r)emote source (%s)?'
98 '$$ &Local $$ &Remote')
98 '$$ &Local $$ &Remote')
99 % (subrelpath(sub), local, remote))
99 % (subrelpath(sub), local, remote))
100 return ui.promptchoice(msg, 0)
100 return ui.promptchoice(msg, 0)
101
101
102 def _sanitize(ui, vfs, ignore):
102 def _sanitize(ui, vfs, ignore):
103 for dirname, dirs, names in vfs.walk():
103 for dirname, dirs, names in vfs.walk():
104 for i, d in enumerate(dirs):
104 for i, d in enumerate(dirs):
105 if d.lower() == ignore:
105 if d.lower() == ignore:
106 del dirs[i]
106 del dirs[i]
107 break
107 break
108 if vfs.basename(dirname).lower() != '.hg':
108 if vfs.basename(dirname).lower() != '.hg':
109 continue
109 continue
110 for f in names:
110 for f in names:
111 if f.lower() == 'hgrc':
111 if f.lower() == 'hgrc':
112 ui.warn(_("warning: removing potentially hostile 'hgrc' "
112 ui.warn(_("warning: removing potentially hostile 'hgrc' "
113 "in '%s'\n") % vfs.join(dirname))
113 "in '%s'\n") % vfs.join(dirname))
114 vfs.unlink(vfs.reljoin(dirname, f))
114 vfs.unlink(vfs.reljoin(dirname, f))
115
115
116 def _auditsubrepopath(repo, path):
116 def _auditsubrepopath(repo, path):
117 # sanity check for potentially unsafe paths such as '~' and '$FOO'
117 # sanity check for potentially unsafe paths such as '~' and '$FOO'
118 if path.startswith('~') or '$' in path or util.expandpath(path) != path:
118 if path.startswith('~') or '$' in path or util.expandpath(path) != path:
119 raise error.Abort(_('subrepo path contains illegal component: %s')
119 raise error.Abort(_('subrepo path contains illegal component: %s')
120 % path)
120 % path)
121 # auditor doesn't check if the path itself is a symlink
121 # auditor doesn't check if the path itself is a symlink
122 pathutil.pathauditor(repo.root)(path)
122 pathutil.pathauditor(repo.root)(path)
123 if repo.wvfs.islink(path):
123 if repo.wvfs.islink(path):
124 raise error.Abort(_("subrepo '%s' traverses symbolic link") % path)
124 raise error.Abort(_("subrepo '%s' traverses symbolic link") % path)
125
125
126 SUBREPO_ALLOWED_DEFAULTS = {
126 SUBREPO_ALLOWED_DEFAULTS = {
127 'hg': True,
127 'hg': True,
128 'git': False,
128 'git': False,
129 'svn': False,
129 'svn': False,
130 }
130 }
131
131
132 def _checktype(ui, kind):
132 def _checktype(ui, kind):
133 # subrepos.allowed is a master kill switch. If disabled, subrepos are
133 # subrepos.allowed is a master kill switch. If disabled, subrepos are
134 # disabled period.
134 # disabled period.
135 if not ui.configbool('subrepos', 'allowed', True):
135 if not ui.configbool('subrepos', 'allowed', True):
136 raise error.Abort(_('subrepos not enabled'),
136 raise error.Abort(_('subrepos not enabled'),
137 hint=_("see 'hg help config.subrepos' for details"))
137 hint=_("see 'hg help config.subrepos' for details"))
138
138
139 default = SUBREPO_ALLOWED_DEFAULTS.get(kind, False)
139 default = SUBREPO_ALLOWED_DEFAULTS.get(kind, False)
140 if not ui.configbool('subrepos', '%s:allowed' % kind, default):
140 if not ui.configbool('subrepos', '%s:allowed' % kind, default):
141 raise error.Abort(_('%s subrepos not allowed') % kind,
141 raise error.Abort(_('%s subrepos not allowed') % kind,
142 hint=_("see 'hg help config.subrepos' for details"))
142 hint=_("see 'hg help config.subrepos' for details"))
143
143
144 if kind not in types:
144 if kind not in types:
145 raise error.Abort(_('unknown subrepo type %s') % kind)
145 raise error.Abort(_('unknown subrepo type %s') % kind)
146
146
147 def subrepo(ctx, path, allowwdir=False, allowcreate=True):
147 def subrepo(ctx, path, allowwdir=False, allowcreate=True):
148 """return instance of the right subrepo class for subrepo in path"""
148 """return instance of the right subrepo class for subrepo in path"""
149 # subrepo inherently violates our import layering rules
149 # subrepo inherently violates our import layering rules
150 # because it wants to make repo objects from deep inside the stack
150 # because it wants to make repo objects from deep inside the stack
151 # so we manually delay the circular imports to not break
151 # so we manually delay the circular imports to not break
152 # scripts that don't use our demand-loading
152 # scripts that don't use our demand-loading
153 global hg
153 global hg
154 from . import hg as h
154 from . import hg as h
155 hg = h
155 hg = h
156
156
157 repo = ctx.repo()
157 repo = ctx.repo()
158 _auditsubrepopath(repo, path)
158 _auditsubrepopath(repo, path)
159 state = ctx.substate[path]
159 state = ctx.substate[path]
160 _checktype(repo.ui, state[2])
160 _checktype(repo.ui, state[2])
161 if allowwdir:
161 if allowwdir:
162 state = (state[0], ctx.subrev(path), state[2])
162 state = (state[0], ctx.subrev(path), state[2])
163 return types[state[2]](ctx, path, state[:2], allowcreate)
163 return types[state[2]](ctx, path, state[:2], allowcreate)
164
164
165 def nullsubrepo(ctx, path, pctx):
165 def nullsubrepo(ctx, path, pctx):
166 """return an empty subrepo in pctx for the extant subrepo in ctx"""
166 """return an empty subrepo in pctx for the extant subrepo in ctx"""
167 # subrepo inherently violates our import layering rules
167 # subrepo inherently violates our import layering rules
168 # because it wants to make repo objects from deep inside the stack
168 # because it wants to make repo objects from deep inside the stack
169 # so we manually delay the circular imports to not break
169 # so we manually delay the circular imports to not break
170 # scripts that don't use our demand-loading
170 # scripts that don't use our demand-loading
171 global hg
171 global hg
172 from . import hg as h
172 from . import hg as h
173 hg = h
173 hg = h
174
174
175 repo = ctx.repo()
175 repo = ctx.repo()
176 _auditsubrepopath(repo, path)
176 _auditsubrepopath(repo, path)
177 state = ctx.substate[path]
177 state = ctx.substate[path]
178 _checktype(repo.ui, state[2])
178 _checktype(repo.ui, state[2])
179 subrev = ''
179 subrev = ''
180 if state[2] == 'hg':
180 if state[2] == 'hg':
181 subrev = "0" * 40
181 subrev = "0" * 40
182 return types[state[2]](pctx, path, (state[0], subrev), True)
182 return types[state[2]](pctx, path, (state[0], subrev), True)
183
183
184 # subrepo classes need to implement the following abstract class:
184 # subrepo classes need to implement the following abstract class:
185
185
186 class abstractsubrepo(object):
186 class abstractsubrepo(object):
187
187
188 def __init__(self, ctx, path):
188 def __init__(self, ctx, path):
189 """Initialize abstractsubrepo part
189 """Initialize abstractsubrepo part
190
190
191 ``ctx`` is the context referring this subrepository in the
191 ``ctx`` is the context referring this subrepository in the
192 parent repository.
192 parent repository.
193
193
194 ``path`` is the path to this subrepository as seen from
194 ``path`` is the path to this subrepository as seen from
195 innermost repository.
195 innermost repository.
196 """
196 """
197 self.ui = ctx.repo().ui
197 self.ui = ctx.repo().ui
198 self._ctx = ctx
198 self._ctx = ctx
199 self._path = path
199 self._path = path
200
200
201 def addwebdirpath(self, serverpath, webconf):
201 def addwebdirpath(self, serverpath, webconf):
202 """Add the hgwebdir entries for this subrepo, and any of its subrepos.
202 """Add the hgwebdir entries for this subrepo, and any of its subrepos.
203
203
204 ``serverpath`` is the path component of the URL for this repo.
204 ``serverpath`` is the path component of the URL for this repo.
205
205
206 ``webconf`` is the dictionary of hgwebdir entries.
206 ``webconf`` is the dictionary of hgwebdir entries.
207 """
207 """
208 pass
208 pass
209
209
210 def storeclean(self, path):
210 def storeclean(self, path):
211 """
211 """
212 returns true if the repository has not changed since it was last
212 returns true if the repository has not changed since it was last
213 cloned from or pushed to a given repository.
213 cloned from or pushed to a given repository.
214 """
214 """
215 return False
215 return False
216
216
217 def dirty(self, ignoreupdate=False, missing=False):
217 def dirty(self, ignoreupdate=False, missing=False):
218 """returns true if the dirstate of the subrepo is dirty or does not
218 """returns true if the dirstate of the subrepo is dirty or does not
219 match current stored state. If ignoreupdate is true, only check
219 match current stored state. If ignoreupdate is true, only check
220 whether the subrepo has uncommitted changes in its dirstate. If missing
220 whether the subrepo has uncommitted changes in its dirstate. If missing
221 is true, check for deleted files.
221 is true, check for deleted files.
222 """
222 """
223 raise NotImplementedError
223 raise NotImplementedError
224
224
225 def dirtyreason(self, ignoreupdate=False, missing=False):
225 def dirtyreason(self, ignoreupdate=False, missing=False):
226 """return reason string if it is ``dirty()``
226 """return reason string if it is ``dirty()``
227
227
228 Returned string should have enough information for the message
228 Returned string should have enough information for the message
229 of exception.
229 of exception.
230
230
231 This returns None, otherwise.
231 This returns None, otherwise.
232 """
232 """
233 if self.dirty(ignoreupdate=ignoreupdate, missing=missing):
233 if self.dirty(ignoreupdate=ignoreupdate, missing=missing):
234 return _('uncommitted changes in subrepository "%s"'
234 return _('uncommitted changes in subrepository "%s"'
235 ) % subrelpath(self)
235 ) % subrelpath(self)
236
236
237 def bailifchanged(self, ignoreupdate=False, hint=None):
237 def bailifchanged(self, ignoreupdate=False, hint=None):
238 """raise Abort if subrepository is ``dirty()``
238 """raise Abort if subrepository is ``dirty()``
239 """
239 """
240 dirtyreason = self.dirtyreason(ignoreupdate=ignoreupdate,
240 dirtyreason = self.dirtyreason(ignoreupdate=ignoreupdate,
241 missing=True)
241 missing=True)
242 if dirtyreason:
242 if dirtyreason:
243 raise error.Abort(dirtyreason, hint=hint)
243 raise error.Abort(dirtyreason, hint=hint)
244
244
245 def basestate(self):
245 def basestate(self):
246 """current working directory base state, disregarding .hgsubstate
246 """current working directory base state, disregarding .hgsubstate
247 state and working directory modifications"""
247 state and working directory modifications"""
248 raise NotImplementedError
248 raise NotImplementedError
249
249
250 def checknested(self, path):
250 def checknested(self, path):
251 """check if path is a subrepository within this repository"""
251 """check if path is a subrepository within this repository"""
252 return False
252 return False
253
253
254 def commit(self, text, user, date):
254 def commit(self, text, user, date):
255 """commit the current changes to the subrepo with the given
255 """commit the current changes to the subrepo with the given
256 log message. Use given user and date if possible. Return the
256 log message. Use given user and date if possible. Return the
257 new state of the subrepo.
257 new state of the subrepo.
258 """
258 """
259 raise NotImplementedError
259 raise NotImplementedError
260
260
261 def phase(self, state):
261 def phase(self, state):
262 """returns phase of specified state in the subrepository.
262 """returns phase of specified state in the subrepository.
263 """
263 """
264 return phases.public
264 return phases.public
265
265
266 def remove(self):
266 def remove(self):
267 """remove the subrepo
267 """remove the subrepo
268
268
269 (should verify the dirstate is not dirty first)
269 (should verify the dirstate is not dirty first)
270 """
270 """
271 raise NotImplementedError
271 raise NotImplementedError
272
272
273 def get(self, state, overwrite=False):
273 def get(self, state, overwrite=False):
274 """run whatever commands are needed to put the subrepo into
274 """run whatever commands are needed to put the subrepo into
275 this state
275 this state
276 """
276 """
277 raise NotImplementedError
277 raise NotImplementedError
278
278
279 def merge(self, state):
279 def merge(self, state):
280 """merge currently-saved state with the new state."""
280 """merge currently-saved state with the new state."""
281 raise NotImplementedError
281 raise NotImplementedError
282
282
283 def push(self, opts):
283 def push(self, opts):
284 """perform whatever action is analogous to 'hg push'
284 """perform whatever action is analogous to 'hg push'
285
285
286 This may be a no-op on some systems.
286 This may be a no-op on some systems.
287 """
287 """
288 raise NotImplementedError
288 raise NotImplementedError
289
289
290 def add(self, ui, match, prefix, uipathfn, explicitonly, **opts):
290 def add(self, ui, match, prefix, uipathfn, explicitonly, **opts):
291 return []
291 return []
292
292
293 def addremove(self, matcher, prefix, uipathfn, opts):
293 def addremove(self, matcher, prefix, uipathfn, opts):
294 self.ui.warn("%s: %s" % (prefix, _("addremove is not supported")))
294 self.ui.warn("%s: %s" % (prefix, _("addremove is not supported")))
295 return 1
295 return 1
296
296
297 def cat(self, match, fm, fntemplate, prefix, **opts):
297 def cat(self, match, fm, fntemplate, prefix, **opts):
298 return 1
298 return 1
299
299
300 def status(self, rev2, **opts):
300 def status(self, rev2, **opts):
301 return scmutil.status([], [], [], [], [], [], [])
301 return scmutil.status([], [], [], [], [], [], [])
302
302
303 def diff(self, ui, diffopts, node2, match, prefix, **opts):
303 def diff(self, ui, diffopts, node2, match, prefix, **opts):
304 pass
304 pass
305
305
306 def outgoing(self, ui, dest, opts):
306 def outgoing(self, ui, dest, opts):
307 return 1
307 return 1
308
308
309 def incoming(self, ui, source, opts):
309 def incoming(self, ui, source, opts):
310 return 1
310 return 1
311
311
312 def files(self):
312 def files(self):
313 """return filename iterator"""
313 """return filename iterator"""
314 raise NotImplementedError
314 raise NotImplementedError
315
315
316 def filedata(self, name, decode):
316 def filedata(self, name, decode):
317 """return file data, optionally passed through repo decoders"""
317 """return file data, optionally passed through repo decoders"""
318 raise NotImplementedError
318 raise NotImplementedError
319
319
320 def fileflags(self, name):
320 def fileflags(self, name):
321 """return file flags"""
321 """return file flags"""
322 return ''
322 return ''
323
323
324 def matchfileset(self, expr, badfn=None):
324 def matchfileset(self, expr, badfn=None):
325 """Resolve the fileset expression for this repo"""
325 """Resolve the fileset expression for this repo"""
326 return matchmod.nevermatcher(self.wvfs.base, '', badfn=badfn)
326 return matchmod.nevermatcher(self.wvfs.base, '', badfn=badfn)
327
327
328 def printfiles(self, ui, m, fm, fmt, subrepos):
328 def printfiles(self, ui, m, fm, fmt, subrepos):
329 """handle the files command for this subrepo"""
329 """handle the files command for this subrepo"""
330 return 1
330 return 1
331
331
332 def archive(self, archiver, prefix, match=None, decode=True):
332 def archive(self, archiver, prefix, match=None, decode=True):
333 if match is not None:
333 if match is not None:
334 files = [f for f in self.files() if match(f)]
334 files = [f for f in self.files() if match(f)]
335 else:
335 else:
336 files = self.files()
336 files = self.files()
337 total = len(files)
337 total = len(files)
338 relpath = subrelpath(self)
338 relpath = subrelpath(self)
339 progress = self.ui.makeprogress(_('archiving (%s)') % relpath,
339 progress = self.ui.makeprogress(_('archiving (%s)') % relpath,
340 unit=_('files'), total=total)
340 unit=_('files'), total=total)
341 progress.update(0)
341 progress.update(0)
342 for name in files:
342 for name in files:
343 flags = self.fileflags(name)
343 flags = self.fileflags(name)
344 mode = 'x' in flags and 0o755 or 0o644
344 mode = 'x' in flags and 0o755 or 0o644
345 symlink = 'l' in flags
345 symlink = 'l' in flags
346 archiver.addfile(prefix + name, mode, symlink,
346 archiver.addfile(prefix + name, mode, symlink,
347 self.filedata(name, decode))
347 self.filedata(name, decode))
348 progress.increment()
348 progress.increment()
349 progress.complete()
349 progress.complete()
350 return total
350 return total
351
351
352 def walk(self, match):
352 def walk(self, match):
353 '''
353 '''
354 walk recursively through the directory tree, finding all files
354 walk recursively through the directory tree, finding all files
355 matched by the match function
355 matched by the match function
356 '''
356 '''
357
357
358 def forget(self, match, prefix, dryrun, interactive):
358 def forget(self, match, prefix, uipathfn, dryrun, interactive):
359 return ([], [])
359 return ([], [])
360
360
361 def removefiles(self, matcher, prefix, uipathfn, after, force, subrepos,
361 def removefiles(self, matcher, prefix, uipathfn, after, force, subrepos,
362 dryrun, warnings):
362 dryrun, warnings):
363 """remove the matched files from the subrepository and the filesystem,
363 """remove the matched files from the subrepository and the filesystem,
364 possibly by force and/or after the file has been removed from the
364 possibly by force and/or after the file has been removed from the
365 filesystem. Return 0 on success, 1 on any warning.
365 filesystem. Return 0 on success, 1 on any warning.
366 """
366 """
367 warnings.append(_("warning: removefiles not implemented (%s)")
367 warnings.append(_("warning: removefiles not implemented (%s)")
368 % self._path)
368 % self._path)
369 return 1
369 return 1
370
370
371 def revert(self, substate, *pats, **opts):
371 def revert(self, substate, *pats, **opts):
372 self.ui.warn(_('%s: reverting %s subrepos is unsupported\n') \
372 self.ui.warn(_('%s: reverting %s subrepos is unsupported\n') \
373 % (substate[0], substate[2]))
373 % (substate[0], substate[2]))
374 return []
374 return []
375
375
376 def shortid(self, revid):
376 def shortid(self, revid):
377 return revid
377 return revid
378
378
379 def unshare(self):
379 def unshare(self):
380 '''
380 '''
381 convert this repository from shared to normal storage.
381 convert this repository from shared to normal storage.
382 '''
382 '''
383
383
384 def verify(self):
384 def verify(self):
385 '''verify the integrity of the repository. Return 0 on success or
385 '''verify the integrity of the repository. Return 0 on success or
386 warning, 1 on any error.
386 warning, 1 on any error.
387 '''
387 '''
388 return 0
388 return 0
389
389
390 @propertycache
390 @propertycache
391 def wvfs(self):
391 def wvfs(self):
392 """return vfs to access the working directory of this subrepository
392 """return vfs to access the working directory of this subrepository
393 """
393 """
394 return vfsmod.vfs(self._ctx.repo().wvfs.join(self._path))
394 return vfsmod.vfs(self._ctx.repo().wvfs.join(self._path))
395
395
396 @propertycache
396 @propertycache
397 def _relpath(self):
397 def _relpath(self):
398 """return path to this subrepository as seen from outermost repository
398 """return path to this subrepository as seen from outermost repository
399 """
399 """
400 return self.wvfs.reljoin(reporelpath(self._ctx.repo()), self._path)
400 return self.wvfs.reljoin(reporelpath(self._ctx.repo()), self._path)
401
401
402 class hgsubrepo(abstractsubrepo):
402 class hgsubrepo(abstractsubrepo):
403 def __init__(self, ctx, path, state, allowcreate):
403 def __init__(self, ctx, path, state, allowcreate):
404 super(hgsubrepo, self).__init__(ctx, path)
404 super(hgsubrepo, self).__init__(ctx, path)
405 self._state = state
405 self._state = state
406 r = ctx.repo()
406 r = ctx.repo()
407 root = r.wjoin(path)
407 root = r.wjoin(path)
408 create = allowcreate and not r.wvfs.exists('%s/.hg' % path)
408 create = allowcreate and not r.wvfs.exists('%s/.hg' % path)
409 # repository constructor does expand variables in path, which is
409 # repository constructor does expand variables in path, which is
410 # unsafe since subrepo path might come from untrusted source.
410 # unsafe since subrepo path might come from untrusted source.
411 if os.path.realpath(util.expandpath(root)) != root:
411 if os.path.realpath(util.expandpath(root)) != root:
412 raise error.Abort(_('subrepo path contains illegal component: %s')
412 raise error.Abort(_('subrepo path contains illegal component: %s')
413 % path)
413 % path)
414 self._repo = hg.repository(r.baseui, root, create=create)
414 self._repo = hg.repository(r.baseui, root, create=create)
415 if self._repo.root != root:
415 if self._repo.root != root:
416 raise error.ProgrammingError('failed to reject unsafe subrepo '
416 raise error.ProgrammingError('failed to reject unsafe subrepo '
417 'path: %s (expanded to %s)'
417 'path: %s (expanded to %s)'
418 % (root, self._repo.root))
418 % (root, self._repo.root))
419
419
420 # Propagate the parent's --hidden option
420 # Propagate the parent's --hidden option
421 if r is r.unfiltered():
421 if r is r.unfiltered():
422 self._repo = self._repo.unfiltered()
422 self._repo = self._repo.unfiltered()
423
423
424 self.ui = self._repo.ui
424 self.ui = self._repo.ui
425 for s, k in [('ui', 'commitsubrepos')]:
425 for s, k in [('ui', 'commitsubrepos')]:
426 v = r.ui.config(s, k)
426 v = r.ui.config(s, k)
427 if v:
427 if v:
428 self.ui.setconfig(s, k, v, 'subrepo')
428 self.ui.setconfig(s, k, v, 'subrepo')
429 # internal config: ui._usedassubrepo
429 # internal config: ui._usedassubrepo
430 self.ui.setconfig('ui', '_usedassubrepo', 'True', 'subrepo')
430 self.ui.setconfig('ui', '_usedassubrepo', 'True', 'subrepo')
431 self._initrepo(r, state[0], create)
431 self._initrepo(r, state[0], create)
432
432
433 @annotatesubrepoerror
433 @annotatesubrepoerror
434 def addwebdirpath(self, serverpath, webconf):
434 def addwebdirpath(self, serverpath, webconf):
435 cmdutil.addwebdirpath(self._repo, subrelpath(self), webconf)
435 cmdutil.addwebdirpath(self._repo, subrelpath(self), webconf)
436
436
437 def storeclean(self, path):
437 def storeclean(self, path):
438 with self._repo.lock():
438 with self._repo.lock():
439 return self._storeclean(path)
439 return self._storeclean(path)
440
440
441 def _storeclean(self, path):
441 def _storeclean(self, path):
442 clean = True
442 clean = True
443 itercache = self._calcstorehash(path)
443 itercache = self._calcstorehash(path)
444 for filehash in self._readstorehashcache(path):
444 for filehash in self._readstorehashcache(path):
445 if filehash != next(itercache, None):
445 if filehash != next(itercache, None):
446 clean = False
446 clean = False
447 break
447 break
448 if clean:
448 if clean:
449 # if not empty:
449 # if not empty:
450 # the cached and current pull states have a different size
450 # the cached and current pull states have a different size
451 clean = next(itercache, None) is None
451 clean = next(itercache, None) is None
452 return clean
452 return clean
453
453
454 def _calcstorehash(self, remotepath):
454 def _calcstorehash(self, remotepath):
455 '''calculate a unique "store hash"
455 '''calculate a unique "store hash"
456
456
457 This method is used to to detect when there are changes that may
457 This method is used to to detect when there are changes that may
458 require a push to a given remote path.'''
458 require a push to a given remote path.'''
459 # sort the files that will be hashed in increasing (likely) file size
459 # sort the files that will be hashed in increasing (likely) file size
460 filelist = ('bookmarks', 'store/phaseroots', 'store/00changelog.i')
460 filelist = ('bookmarks', 'store/phaseroots', 'store/00changelog.i')
461 yield '# %s\n' % _expandedabspath(remotepath)
461 yield '# %s\n' % _expandedabspath(remotepath)
462 vfs = self._repo.vfs
462 vfs = self._repo.vfs
463 for relname in filelist:
463 for relname in filelist:
464 filehash = node.hex(hashlib.sha1(vfs.tryread(relname)).digest())
464 filehash = node.hex(hashlib.sha1(vfs.tryread(relname)).digest())
465 yield '%s = %s\n' % (relname, filehash)
465 yield '%s = %s\n' % (relname, filehash)
466
466
467 @propertycache
467 @propertycache
468 def _cachestorehashvfs(self):
468 def _cachestorehashvfs(self):
469 return vfsmod.vfs(self._repo.vfs.join('cache/storehash'))
469 return vfsmod.vfs(self._repo.vfs.join('cache/storehash'))
470
470
471 def _readstorehashcache(self, remotepath):
471 def _readstorehashcache(self, remotepath):
472 '''read the store hash cache for a given remote repository'''
472 '''read the store hash cache for a given remote repository'''
473 cachefile = _getstorehashcachename(remotepath)
473 cachefile = _getstorehashcachename(remotepath)
474 return self._cachestorehashvfs.tryreadlines(cachefile, 'r')
474 return self._cachestorehashvfs.tryreadlines(cachefile, 'r')
475
475
476 def _cachestorehash(self, remotepath):
476 def _cachestorehash(self, remotepath):
477 '''cache the current store hash
477 '''cache the current store hash
478
478
479 Each remote repo requires its own store hash cache, because a subrepo
479 Each remote repo requires its own store hash cache, because a subrepo
480 store may be "clean" versus a given remote repo, but not versus another
480 store may be "clean" versus a given remote repo, but not versus another
481 '''
481 '''
482 cachefile = _getstorehashcachename(remotepath)
482 cachefile = _getstorehashcachename(remotepath)
483 with self._repo.lock():
483 with self._repo.lock():
484 storehash = list(self._calcstorehash(remotepath))
484 storehash = list(self._calcstorehash(remotepath))
485 vfs = self._cachestorehashvfs
485 vfs = self._cachestorehashvfs
486 vfs.writelines(cachefile, storehash, mode='wb', notindexed=True)
486 vfs.writelines(cachefile, storehash, mode='wb', notindexed=True)
487
487
488 def _getctx(self):
488 def _getctx(self):
489 '''fetch the context for this subrepo revision, possibly a workingctx
489 '''fetch the context for this subrepo revision, possibly a workingctx
490 '''
490 '''
491 if self._ctx.rev() is None:
491 if self._ctx.rev() is None:
492 return self._repo[None] # workingctx if parent is workingctx
492 return self._repo[None] # workingctx if parent is workingctx
493 else:
493 else:
494 rev = self._state[1]
494 rev = self._state[1]
495 return self._repo[rev]
495 return self._repo[rev]
496
496
497 @annotatesubrepoerror
497 @annotatesubrepoerror
498 def _initrepo(self, parentrepo, source, create):
498 def _initrepo(self, parentrepo, source, create):
499 self._repo._subparent = parentrepo
499 self._repo._subparent = parentrepo
500 self._repo._subsource = source
500 self._repo._subsource = source
501
501
502 if create:
502 if create:
503 lines = ['[paths]\n']
503 lines = ['[paths]\n']
504
504
505 def addpathconfig(key, value):
505 def addpathconfig(key, value):
506 if value:
506 if value:
507 lines.append('%s = %s\n' % (key, value))
507 lines.append('%s = %s\n' % (key, value))
508 self.ui.setconfig('paths', key, value, 'subrepo')
508 self.ui.setconfig('paths', key, value, 'subrepo')
509
509
510 defpath = _abssource(self._repo, abort=False)
510 defpath = _abssource(self._repo, abort=False)
511 defpushpath = _abssource(self._repo, True, abort=False)
511 defpushpath = _abssource(self._repo, True, abort=False)
512 addpathconfig('default', defpath)
512 addpathconfig('default', defpath)
513 if defpath != defpushpath:
513 if defpath != defpushpath:
514 addpathconfig('default-push', defpushpath)
514 addpathconfig('default-push', defpushpath)
515
515
516 self._repo.vfs.write('hgrc', util.tonativeeol(''.join(lines)))
516 self._repo.vfs.write('hgrc', util.tonativeeol(''.join(lines)))
517
517
518 @annotatesubrepoerror
518 @annotatesubrepoerror
519 def add(self, ui, match, prefix, uipathfn, explicitonly, **opts):
519 def add(self, ui, match, prefix, uipathfn, explicitonly, **opts):
520 return cmdutil.add(ui, self._repo, match, prefix, uipathfn,
520 return cmdutil.add(ui, self._repo, match, prefix, uipathfn,
521 explicitonly, **opts)
521 explicitonly, **opts)
522
522
523 @annotatesubrepoerror
523 @annotatesubrepoerror
524 def addremove(self, m, prefix, uipathfn, opts):
524 def addremove(self, m, prefix, uipathfn, opts):
525 # In the same way as sub directories are processed, once in a subrepo,
525 # In the same way as sub directories are processed, once in a subrepo,
526 # always entry any of its subrepos. Don't corrupt the options that will
526 # always entry any of its subrepos. Don't corrupt the options that will
527 # be used to process sibling subrepos however.
527 # be used to process sibling subrepos however.
528 opts = copy.copy(opts)
528 opts = copy.copy(opts)
529 opts['subrepos'] = True
529 opts['subrepos'] = True
530 return scmutil.addremove(self._repo, m, prefix, uipathfn, opts)
530 return scmutil.addremove(self._repo, m, prefix, uipathfn, opts)
531
531
532 @annotatesubrepoerror
532 @annotatesubrepoerror
533 def cat(self, match, fm, fntemplate, prefix, **opts):
533 def cat(self, match, fm, fntemplate, prefix, **opts):
534 rev = self._state[1]
534 rev = self._state[1]
535 ctx = self._repo[rev]
535 ctx = self._repo[rev]
536 return cmdutil.cat(self.ui, self._repo, ctx, match, fm, fntemplate,
536 return cmdutil.cat(self.ui, self._repo, ctx, match, fm, fntemplate,
537 prefix, **opts)
537 prefix, **opts)
538
538
539 @annotatesubrepoerror
539 @annotatesubrepoerror
540 def status(self, rev2, **opts):
540 def status(self, rev2, **opts):
541 try:
541 try:
542 rev1 = self._state[1]
542 rev1 = self._state[1]
543 ctx1 = self._repo[rev1]
543 ctx1 = self._repo[rev1]
544 ctx2 = self._repo[rev2]
544 ctx2 = self._repo[rev2]
545 return self._repo.status(ctx1, ctx2, **opts)
545 return self._repo.status(ctx1, ctx2, **opts)
546 except error.RepoLookupError as inst:
546 except error.RepoLookupError as inst:
547 self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
547 self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
548 % (inst, subrelpath(self)))
548 % (inst, subrelpath(self)))
549 return scmutil.status([], [], [], [], [], [], [])
549 return scmutil.status([], [], [], [], [], [], [])
550
550
551 @annotatesubrepoerror
551 @annotatesubrepoerror
552 def diff(self, ui, diffopts, node2, match, prefix, **opts):
552 def diff(self, ui, diffopts, node2, match, prefix, **opts):
553 try:
553 try:
554 node1 = node.bin(self._state[1])
554 node1 = node.bin(self._state[1])
555 # We currently expect node2 to come from substate and be
555 # We currently expect node2 to come from substate and be
556 # in hex format
556 # in hex format
557 if node2 is not None:
557 if node2 is not None:
558 node2 = node.bin(node2)
558 node2 = node.bin(node2)
559 logcmdutil.diffordiffstat(ui, self._repo, diffopts, node1, node2,
559 logcmdutil.diffordiffstat(ui, self._repo, diffopts, node1, node2,
560 match, prefix=prefix, listsubrepos=True,
560 match, prefix=prefix, listsubrepos=True,
561 **opts)
561 **opts)
562 except error.RepoLookupError as inst:
562 except error.RepoLookupError as inst:
563 self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
563 self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
564 % (inst, subrelpath(self)))
564 % (inst, subrelpath(self)))
565
565
566 @annotatesubrepoerror
566 @annotatesubrepoerror
567 def archive(self, archiver, prefix, match=None, decode=True):
567 def archive(self, archiver, prefix, match=None, decode=True):
568 self._get(self._state + ('hg',))
568 self._get(self._state + ('hg',))
569 files = self.files()
569 files = self.files()
570 if match:
570 if match:
571 files = [f for f in files if match(f)]
571 files = [f for f in files if match(f)]
572 rev = self._state[1]
572 rev = self._state[1]
573 ctx = self._repo[rev]
573 ctx = self._repo[rev]
574 scmutil.prefetchfiles(self._repo, [ctx.rev()],
574 scmutil.prefetchfiles(self._repo, [ctx.rev()],
575 scmutil.matchfiles(self._repo, files))
575 scmutil.matchfiles(self._repo, files))
576 total = abstractsubrepo.archive(self, archiver, prefix, match)
576 total = abstractsubrepo.archive(self, archiver, prefix, match)
577 for subpath in ctx.substate:
577 for subpath in ctx.substate:
578 s = subrepo(ctx, subpath, True)
578 s = subrepo(ctx, subpath, True)
579 submatch = matchmod.subdirmatcher(subpath, match)
579 submatch = matchmod.subdirmatcher(subpath, match)
580 subprefix = prefix + subpath + '/'
580 subprefix = prefix + subpath + '/'
581 total += s.archive(archiver, subprefix, submatch,
581 total += s.archive(archiver, subprefix, submatch,
582 decode)
582 decode)
583 return total
583 return total
584
584
585 @annotatesubrepoerror
585 @annotatesubrepoerror
586 def dirty(self, ignoreupdate=False, missing=False):
586 def dirty(self, ignoreupdate=False, missing=False):
587 r = self._state[1]
587 r = self._state[1]
588 if r == '' and not ignoreupdate: # no state recorded
588 if r == '' and not ignoreupdate: # no state recorded
589 return True
589 return True
590 w = self._repo[None]
590 w = self._repo[None]
591 if r != w.p1().hex() and not ignoreupdate:
591 if r != w.p1().hex() and not ignoreupdate:
592 # different version checked out
592 # different version checked out
593 return True
593 return True
594 return w.dirty(missing=missing) # working directory changed
594 return w.dirty(missing=missing) # working directory changed
595
595
596 def basestate(self):
596 def basestate(self):
597 return self._repo['.'].hex()
597 return self._repo['.'].hex()
598
598
599 def checknested(self, path):
599 def checknested(self, path):
600 return self._repo._checknested(self._repo.wjoin(path))
600 return self._repo._checknested(self._repo.wjoin(path))
601
601
602 @annotatesubrepoerror
602 @annotatesubrepoerror
603 def commit(self, text, user, date):
603 def commit(self, text, user, date):
604 # don't bother committing in the subrepo if it's only been
604 # don't bother committing in the subrepo if it's only been
605 # updated
605 # updated
606 if not self.dirty(True):
606 if not self.dirty(True):
607 return self._repo['.'].hex()
607 return self._repo['.'].hex()
608 self.ui.debug("committing subrepo %s\n" % subrelpath(self))
608 self.ui.debug("committing subrepo %s\n" % subrelpath(self))
609 n = self._repo.commit(text, user, date)
609 n = self._repo.commit(text, user, date)
610 if not n:
610 if not n:
611 return self._repo['.'].hex() # different version checked out
611 return self._repo['.'].hex() # different version checked out
612 return node.hex(n)
612 return node.hex(n)
613
613
614 @annotatesubrepoerror
614 @annotatesubrepoerror
615 def phase(self, state):
615 def phase(self, state):
616 return self._repo[state or '.'].phase()
616 return self._repo[state or '.'].phase()
617
617
618 @annotatesubrepoerror
618 @annotatesubrepoerror
619 def remove(self):
619 def remove(self):
620 # we can't fully delete the repository as it may contain
620 # we can't fully delete the repository as it may contain
621 # local-only history
621 # local-only history
622 self.ui.note(_('removing subrepo %s\n') % subrelpath(self))
622 self.ui.note(_('removing subrepo %s\n') % subrelpath(self))
623 hg.clean(self._repo, node.nullid, False)
623 hg.clean(self._repo, node.nullid, False)
624
624
625 def _get(self, state):
625 def _get(self, state):
626 source, revision, kind = state
626 source, revision, kind = state
627 parentrepo = self._repo._subparent
627 parentrepo = self._repo._subparent
628
628
629 if revision in self._repo.unfiltered():
629 if revision in self._repo.unfiltered():
630 # Allow shared subrepos tracked at null to setup the sharedpath
630 # Allow shared subrepos tracked at null to setup the sharedpath
631 if len(self._repo) != 0 or not parentrepo.shared():
631 if len(self._repo) != 0 or not parentrepo.shared():
632 return True
632 return True
633 self._repo._subsource = source
633 self._repo._subsource = source
634 srcurl = _abssource(self._repo)
634 srcurl = _abssource(self._repo)
635
635
636 # Defer creating the peer until after the status message is logged, in
636 # Defer creating the peer until after the status message is logged, in
637 # case there are network problems.
637 # case there are network problems.
638 getpeer = lambda: hg.peer(self._repo, {}, srcurl)
638 getpeer = lambda: hg.peer(self._repo, {}, srcurl)
639
639
640 if len(self._repo) == 0:
640 if len(self._repo) == 0:
641 # use self._repo.vfs instead of self.wvfs to remove .hg only
641 # use self._repo.vfs instead of self.wvfs to remove .hg only
642 self._repo.vfs.rmtree()
642 self._repo.vfs.rmtree()
643
643
644 # A remote subrepo could be shared if there is a local copy
644 # A remote subrepo could be shared if there is a local copy
645 # relative to the parent's share source. But clone pooling doesn't
645 # relative to the parent's share source. But clone pooling doesn't
646 # assemble the repos in a tree, so that can't be consistently done.
646 # assemble the repos in a tree, so that can't be consistently done.
647 # A simpler option is for the user to configure clone pooling, and
647 # A simpler option is for the user to configure clone pooling, and
648 # work with that.
648 # work with that.
649 if parentrepo.shared() and hg.islocal(srcurl):
649 if parentrepo.shared() and hg.islocal(srcurl):
650 self.ui.status(_('sharing subrepo %s from %s\n')
650 self.ui.status(_('sharing subrepo %s from %s\n')
651 % (subrelpath(self), srcurl))
651 % (subrelpath(self), srcurl))
652 shared = hg.share(self._repo._subparent.baseui,
652 shared = hg.share(self._repo._subparent.baseui,
653 getpeer(), self._repo.root,
653 getpeer(), self._repo.root,
654 update=False, bookmarks=False)
654 update=False, bookmarks=False)
655 self._repo = shared.local()
655 self._repo = shared.local()
656 else:
656 else:
657 # TODO: find a common place for this and this code in the
657 # TODO: find a common place for this and this code in the
658 # share.py wrap of the clone command.
658 # share.py wrap of the clone command.
659 if parentrepo.shared():
659 if parentrepo.shared():
660 pool = self.ui.config('share', 'pool')
660 pool = self.ui.config('share', 'pool')
661 if pool:
661 if pool:
662 pool = util.expandpath(pool)
662 pool = util.expandpath(pool)
663
663
664 shareopts = {
664 shareopts = {
665 'pool': pool,
665 'pool': pool,
666 'mode': self.ui.config('share', 'poolnaming'),
666 'mode': self.ui.config('share', 'poolnaming'),
667 }
667 }
668 else:
668 else:
669 shareopts = {}
669 shareopts = {}
670
670
671 self.ui.status(_('cloning subrepo %s from %s\n')
671 self.ui.status(_('cloning subrepo %s from %s\n')
672 % (subrelpath(self), util.hidepassword(srcurl)))
672 % (subrelpath(self), util.hidepassword(srcurl)))
673 other, cloned = hg.clone(self._repo._subparent.baseui, {},
673 other, cloned = hg.clone(self._repo._subparent.baseui, {},
674 getpeer(), self._repo.root,
674 getpeer(), self._repo.root,
675 update=False, shareopts=shareopts)
675 update=False, shareopts=shareopts)
676 self._repo = cloned.local()
676 self._repo = cloned.local()
677 self._initrepo(parentrepo, source, create=True)
677 self._initrepo(parentrepo, source, create=True)
678 self._cachestorehash(srcurl)
678 self._cachestorehash(srcurl)
679 else:
679 else:
680 self.ui.status(_('pulling subrepo %s from %s\n')
680 self.ui.status(_('pulling subrepo %s from %s\n')
681 % (subrelpath(self), util.hidepassword(srcurl)))
681 % (subrelpath(self), util.hidepassword(srcurl)))
682 cleansub = self.storeclean(srcurl)
682 cleansub = self.storeclean(srcurl)
683 exchange.pull(self._repo, getpeer())
683 exchange.pull(self._repo, getpeer())
684 if cleansub:
684 if cleansub:
685 # keep the repo clean after pull
685 # keep the repo clean after pull
686 self._cachestorehash(srcurl)
686 self._cachestorehash(srcurl)
687 return False
687 return False
688
688
689 @annotatesubrepoerror
689 @annotatesubrepoerror
690 def get(self, state, overwrite=False):
690 def get(self, state, overwrite=False):
691 inrepo = self._get(state)
691 inrepo = self._get(state)
692 source, revision, kind = state
692 source, revision, kind = state
693 repo = self._repo
693 repo = self._repo
694 repo.ui.debug("getting subrepo %s\n" % self._path)
694 repo.ui.debug("getting subrepo %s\n" % self._path)
695 if inrepo:
695 if inrepo:
696 urepo = repo.unfiltered()
696 urepo = repo.unfiltered()
697 ctx = urepo[revision]
697 ctx = urepo[revision]
698 if ctx.hidden():
698 if ctx.hidden():
699 urepo.ui.warn(
699 urepo.ui.warn(
700 _('revision %s in subrepository "%s" is hidden\n') \
700 _('revision %s in subrepository "%s" is hidden\n') \
701 % (revision[0:12], self._path))
701 % (revision[0:12], self._path))
702 repo = urepo
702 repo = urepo
703 hg.updaterepo(repo, revision, overwrite)
703 hg.updaterepo(repo, revision, overwrite)
704
704
705 @annotatesubrepoerror
705 @annotatesubrepoerror
706 def merge(self, state):
706 def merge(self, state):
707 self._get(state)
707 self._get(state)
708 cur = self._repo['.']
708 cur = self._repo['.']
709 dst = self._repo[state[1]]
709 dst = self._repo[state[1]]
710 anc = dst.ancestor(cur)
710 anc = dst.ancestor(cur)
711
711
712 def mergefunc():
712 def mergefunc():
713 if anc == cur and dst.branch() == cur.branch():
713 if anc == cur and dst.branch() == cur.branch():
714 self.ui.debug('updating subrepository "%s"\n'
714 self.ui.debug('updating subrepository "%s"\n'
715 % subrelpath(self))
715 % subrelpath(self))
716 hg.update(self._repo, state[1])
716 hg.update(self._repo, state[1])
717 elif anc == dst:
717 elif anc == dst:
718 self.ui.debug('skipping subrepository "%s"\n'
718 self.ui.debug('skipping subrepository "%s"\n'
719 % subrelpath(self))
719 % subrelpath(self))
720 else:
720 else:
721 self.ui.debug('merging subrepository "%s"\n' % subrelpath(self))
721 self.ui.debug('merging subrepository "%s"\n' % subrelpath(self))
722 hg.merge(self._repo, state[1], remind=False)
722 hg.merge(self._repo, state[1], remind=False)
723
723
724 wctx = self._repo[None]
724 wctx = self._repo[None]
725 if self.dirty():
725 if self.dirty():
726 if anc != dst:
726 if anc != dst:
727 if _updateprompt(self.ui, self, wctx.dirty(), cur, dst):
727 if _updateprompt(self.ui, self, wctx.dirty(), cur, dst):
728 mergefunc()
728 mergefunc()
729 else:
729 else:
730 mergefunc()
730 mergefunc()
731 else:
731 else:
732 mergefunc()
732 mergefunc()
733
733
734 @annotatesubrepoerror
734 @annotatesubrepoerror
735 def push(self, opts):
735 def push(self, opts):
736 force = opts.get('force')
736 force = opts.get('force')
737 newbranch = opts.get('new_branch')
737 newbranch = opts.get('new_branch')
738 ssh = opts.get('ssh')
738 ssh = opts.get('ssh')
739
739
740 # push subrepos depth-first for coherent ordering
740 # push subrepos depth-first for coherent ordering
741 c = self._repo['.']
741 c = self._repo['.']
742 subs = c.substate # only repos that are committed
742 subs = c.substate # only repos that are committed
743 for s in sorted(subs):
743 for s in sorted(subs):
744 if c.sub(s).push(opts) == 0:
744 if c.sub(s).push(opts) == 0:
745 return False
745 return False
746
746
747 dsturl = _abssource(self._repo, True)
747 dsturl = _abssource(self._repo, True)
748 if not force:
748 if not force:
749 if self.storeclean(dsturl):
749 if self.storeclean(dsturl):
750 self.ui.status(
750 self.ui.status(
751 _('no changes made to subrepo %s since last push to %s\n')
751 _('no changes made to subrepo %s since last push to %s\n')
752 % (subrelpath(self), util.hidepassword(dsturl)))
752 % (subrelpath(self), util.hidepassword(dsturl)))
753 return None
753 return None
754 self.ui.status(_('pushing subrepo %s to %s\n') %
754 self.ui.status(_('pushing subrepo %s to %s\n') %
755 (subrelpath(self), util.hidepassword(dsturl)))
755 (subrelpath(self), util.hidepassword(dsturl)))
756 other = hg.peer(self._repo, {'ssh': ssh}, dsturl)
756 other = hg.peer(self._repo, {'ssh': ssh}, dsturl)
757 res = exchange.push(self._repo, other, force, newbranch=newbranch)
757 res = exchange.push(self._repo, other, force, newbranch=newbranch)
758
758
759 # the repo is now clean
759 # the repo is now clean
760 self._cachestorehash(dsturl)
760 self._cachestorehash(dsturl)
761 return res.cgresult
761 return res.cgresult
762
762
763 @annotatesubrepoerror
763 @annotatesubrepoerror
764 def outgoing(self, ui, dest, opts):
764 def outgoing(self, ui, dest, opts):
765 if 'rev' in opts or 'branch' in opts:
765 if 'rev' in opts or 'branch' in opts:
766 opts = copy.copy(opts)
766 opts = copy.copy(opts)
767 opts.pop('rev', None)
767 opts.pop('rev', None)
768 opts.pop('branch', None)
768 opts.pop('branch', None)
769 return hg.outgoing(ui, self._repo, _abssource(self._repo, True), opts)
769 return hg.outgoing(ui, self._repo, _abssource(self._repo, True), opts)
770
770
771 @annotatesubrepoerror
771 @annotatesubrepoerror
772 def incoming(self, ui, source, opts):
772 def incoming(self, ui, source, opts):
773 if 'rev' in opts or 'branch' in opts:
773 if 'rev' in opts or 'branch' in opts:
774 opts = copy.copy(opts)
774 opts = copy.copy(opts)
775 opts.pop('rev', None)
775 opts.pop('rev', None)
776 opts.pop('branch', None)
776 opts.pop('branch', None)
777 return hg.incoming(ui, self._repo, _abssource(self._repo, False), opts)
777 return hg.incoming(ui, self._repo, _abssource(self._repo, False), opts)
778
778
779 @annotatesubrepoerror
779 @annotatesubrepoerror
780 def files(self):
780 def files(self):
781 rev = self._state[1]
781 rev = self._state[1]
782 ctx = self._repo[rev]
782 ctx = self._repo[rev]
783 return ctx.manifest().keys()
783 return ctx.manifest().keys()
784
784
785 def filedata(self, name, decode):
785 def filedata(self, name, decode):
786 rev = self._state[1]
786 rev = self._state[1]
787 data = self._repo[rev][name].data()
787 data = self._repo[rev][name].data()
788 if decode:
788 if decode:
789 data = self._repo.wwritedata(name, data)
789 data = self._repo.wwritedata(name, data)
790 return data
790 return data
791
791
792 def fileflags(self, name):
792 def fileflags(self, name):
793 rev = self._state[1]
793 rev = self._state[1]
794 ctx = self._repo[rev]
794 ctx = self._repo[rev]
795 return ctx.flags(name)
795 return ctx.flags(name)
796
796
797 @annotatesubrepoerror
797 @annotatesubrepoerror
798 def printfiles(self, ui, m, fm, fmt, subrepos):
798 def printfiles(self, ui, m, fm, fmt, subrepos):
799 # If the parent context is a workingctx, use the workingctx here for
799 # If the parent context is a workingctx, use the workingctx here for
800 # consistency.
800 # consistency.
801 if self._ctx.rev() is None:
801 if self._ctx.rev() is None:
802 ctx = self._repo[None]
802 ctx = self._repo[None]
803 else:
803 else:
804 rev = self._state[1]
804 rev = self._state[1]
805 ctx = self._repo[rev]
805 ctx = self._repo[rev]
806 return cmdutil.files(ui, ctx, m, fm, fmt, subrepos)
806 return cmdutil.files(ui, ctx, m, fm, fmt, subrepos)
807
807
808 @annotatesubrepoerror
808 @annotatesubrepoerror
809 def matchfileset(self, expr, badfn=None):
809 def matchfileset(self, expr, badfn=None):
810 repo = self._repo
810 repo = self._repo
811 if self._ctx.rev() is None:
811 if self._ctx.rev() is None:
812 ctx = repo[None]
812 ctx = repo[None]
813 else:
813 else:
814 rev = self._state[1]
814 rev = self._state[1]
815 ctx = repo[rev]
815 ctx = repo[rev]
816
816
817 matchers = [ctx.matchfileset(expr, badfn=badfn)]
817 matchers = [ctx.matchfileset(expr, badfn=badfn)]
818
818
819 for subpath in ctx.substate:
819 for subpath in ctx.substate:
820 sub = ctx.sub(subpath)
820 sub = ctx.sub(subpath)
821
821
822 try:
822 try:
823 sm = sub.matchfileset(expr, badfn=badfn)
823 sm = sub.matchfileset(expr, badfn=badfn)
824 pm = matchmod.prefixdirmatcher(repo.root, repo.getcwd(),
824 pm = matchmod.prefixdirmatcher(repo.root, repo.getcwd(),
825 subpath, sm, badfn=badfn)
825 subpath, sm, badfn=badfn)
826 matchers.append(pm)
826 matchers.append(pm)
827 except error.LookupError:
827 except error.LookupError:
828 self.ui.status(_("skipping missing subrepository: %s\n")
828 self.ui.status(_("skipping missing subrepository: %s\n")
829 % self.wvfs.reljoin(reporelpath(self), subpath))
829 % self.wvfs.reljoin(reporelpath(self), subpath))
830 if len(matchers) == 1:
830 if len(matchers) == 1:
831 return matchers[0]
831 return matchers[0]
832 return matchmod.unionmatcher(matchers)
832 return matchmod.unionmatcher(matchers)
833
833
834 def walk(self, match):
834 def walk(self, match):
835 ctx = self._repo[None]
835 ctx = self._repo[None]
836 return ctx.walk(match)
836 return ctx.walk(match)
837
837
838 @annotatesubrepoerror
838 @annotatesubrepoerror
839 def forget(self, match, prefix, dryrun, interactive):
839 def forget(self, match, prefix, uipathfn, dryrun, interactive):
840 return cmdutil.forget(self.ui, self._repo, match, prefix,
840 return cmdutil.forget(self.ui, self._repo, match, prefix, uipathfn,
841 True, dryrun=dryrun, interactive=interactive)
841 True, dryrun=dryrun, interactive=interactive)
842
842
843 @annotatesubrepoerror
843 @annotatesubrepoerror
844 def removefiles(self, matcher, prefix, uipathfn, after, force, subrepos,
844 def removefiles(self, matcher, prefix, uipathfn, after, force, subrepos,
845 dryrun, warnings):
845 dryrun, warnings):
846 return cmdutil.remove(self.ui, self._repo, matcher, prefix, uipathfn,
846 return cmdutil.remove(self.ui, self._repo, matcher, prefix, uipathfn,
847 after, force, subrepos, dryrun)
847 after, force, subrepos, dryrun)
848
848
849 @annotatesubrepoerror
849 @annotatesubrepoerror
850 def revert(self, substate, *pats, **opts):
850 def revert(self, substate, *pats, **opts):
851 # reverting a subrepo is a 2 step process:
851 # reverting a subrepo is a 2 step process:
852 # 1. if the no_backup is not set, revert all modified
852 # 1. if the no_backup is not set, revert all modified
853 # files inside the subrepo
853 # files inside the subrepo
854 # 2. update the subrepo to the revision specified in
854 # 2. update the subrepo to the revision specified in
855 # the corresponding substate dictionary
855 # the corresponding substate dictionary
856 self.ui.status(_('reverting subrepo %s\n') % substate[0])
856 self.ui.status(_('reverting subrepo %s\n') % substate[0])
857 if not opts.get(r'no_backup'):
857 if not opts.get(r'no_backup'):
858 # Revert all files on the subrepo, creating backups
858 # Revert all files on the subrepo, creating backups
859 # Note that this will not recursively revert subrepos
859 # Note that this will not recursively revert subrepos
860 # We could do it if there was a set:subrepos() predicate
860 # We could do it if there was a set:subrepos() predicate
861 opts = opts.copy()
861 opts = opts.copy()
862 opts[r'date'] = None
862 opts[r'date'] = None
863 opts[r'rev'] = substate[1]
863 opts[r'rev'] = substate[1]
864
864
865 self.filerevert(*pats, **opts)
865 self.filerevert(*pats, **opts)
866
866
867 # Update the repo to the revision specified in the given substate
867 # Update the repo to the revision specified in the given substate
868 if not opts.get(r'dry_run'):
868 if not opts.get(r'dry_run'):
869 self.get(substate, overwrite=True)
869 self.get(substate, overwrite=True)
870
870
871 def filerevert(self, *pats, **opts):
871 def filerevert(self, *pats, **opts):
872 ctx = self._repo[opts[r'rev']]
872 ctx = self._repo[opts[r'rev']]
873 parents = self._repo.dirstate.parents()
873 parents = self._repo.dirstate.parents()
874 if opts.get(r'all'):
874 if opts.get(r'all'):
875 pats = ['set:modified()']
875 pats = ['set:modified()']
876 else:
876 else:
877 pats = []
877 pats = []
878 cmdutil.revert(self.ui, self._repo, ctx, parents, *pats, **opts)
878 cmdutil.revert(self.ui, self._repo, ctx, parents, *pats, **opts)
879
879
880 def shortid(self, revid):
880 def shortid(self, revid):
881 return revid[:12]
881 return revid[:12]
882
882
883 @annotatesubrepoerror
883 @annotatesubrepoerror
884 def unshare(self):
884 def unshare(self):
885 # subrepo inherently violates our import layering rules
885 # subrepo inherently violates our import layering rules
886 # because it wants to make repo objects from deep inside the stack
886 # because it wants to make repo objects from deep inside the stack
887 # so we manually delay the circular imports to not break
887 # so we manually delay the circular imports to not break
888 # scripts that don't use our demand-loading
888 # scripts that don't use our demand-loading
889 global hg
889 global hg
890 from . import hg as h
890 from . import hg as h
891 hg = h
891 hg = h
892
892
893 # Nothing prevents a user from sharing in a repo, and then making that a
893 # Nothing prevents a user from sharing in a repo, and then making that a
894 # subrepo. Alternately, the previous unshare attempt may have failed
894 # subrepo. Alternately, the previous unshare attempt may have failed
895 # part way through. So recurse whether or not this layer is shared.
895 # part way through. So recurse whether or not this layer is shared.
896 if self._repo.shared():
896 if self._repo.shared():
897 self.ui.status(_("unsharing subrepo '%s'\n") % self._relpath)
897 self.ui.status(_("unsharing subrepo '%s'\n") % self._relpath)
898
898
899 hg.unshare(self.ui, self._repo)
899 hg.unshare(self.ui, self._repo)
900
900
901 def verify(self):
901 def verify(self):
902 try:
902 try:
903 rev = self._state[1]
903 rev = self._state[1]
904 ctx = self._repo.unfiltered()[rev]
904 ctx = self._repo.unfiltered()[rev]
905 if ctx.hidden():
905 if ctx.hidden():
906 # Since hidden revisions aren't pushed/pulled, it seems worth an
906 # Since hidden revisions aren't pushed/pulled, it seems worth an
907 # explicit warning.
907 # explicit warning.
908 ui = self._repo.ui
908 ui = self._repo.ui
909 ui.warn(_("subrepo '%s' is hidden in revision %s\n") %
909 ui.warn(_("subrepo '%s' is hidden in revision %s\n") %
910 (self._relpath, node.short(self._ctx.node())))
910 (self._relpath, node.short(self._ctx.node())))
911 return 0
911 return 0
912 except error.RepoLookupError:
912 except error.RepoLookupError:
913 # A missing subrepo revision may be a case of needing to pull it, so
913 # A missing subrepo revision may be a case of needing to pull it, so
914 # don't treat this as an error.
914 # don't treat this as an error.
915 self._repo.ui.warn(_("subrepo '%s' not found in revision %s\n") %
915 self._repo.ui.warn(_("subrepo '%s' not found in revision %s\n") %
916 (self._relpath, node.short(self._ctx.node())))
916 (self._relpath, node.short(self._ctx.node())))
917 return 0
917 return 0
918
918
919 @propertycache
919 @propertycache
920 def wvfs(self):
920 def wvfs(self):
921 """return own wvfs for efficiency and consistency
921 """return own wvfs for efficiency and consistency
922 """
922 """
923 return self._repo.wvfs
923 return self._repo.wvfs
924
924
925 @propertycache
925 @propertycache
926 def _relpath(self):
926 def _relpath(self):
927 """return path to this subrepository as seen from outermost repository
927 """return path to this subrepository as seen from outermost repository
928 """
928 """
929 # Keep consistent dir separators by avoiding vfs.join(self._path)
929 # Keep consistent dir separators by avoiding vfs.join(self._path)
930 return reporelpath(self._repo)
930 return reporelpath(self._repo)
931
931
932 class svnsubrepo(abstractsubrepo):
932 class svnsubrepo(abstractsubrepo):
933 def __init__(self, ctx, path, state, allowcreate):
933 def __init__(self, ctx, path, state, allowcreate):
934 super(svnsubrepo, self).__init__(ctx, path)
934 super(svnsubrepo, self).__init__(ctx, path)
935 self._state = state
935 self._state = state
936 self._exe = procutil.findexe('svn')
936 self._exe = procutil.findexe('svn')
937 if not self._exe:
937 if not self._exe:
938 raise error.Abort(_("'svn' executable not found for subrepo '%s'")
938 raise error.Abort(_("'svn' executable not found for subrepo '%s'")
939 % self._path)
939 % self._path)
940
940
941 def _svncommand(self, commands, filename='', failok=False):
941 def _svncommand(self, commands, filename='', failok=False):
942 cmd = [self._exe]
942 cmd = [self._exe]
943 extrakw = {}
943 extrakw = {}
944 if not self.ui.interactive():
944 if not self.ui.interactive():
945 # Making stdin be a pipe should prevent svn from behaving
945 # Making stdin be a pipe should prevent svn from behaving
946 # interactively even if we can't pass --non-interactive.
946 # interactively even if we can't pass --non-interactive.
947 extrakw[r'stdin'] = subprocess.PIPE
947 extrakw[r'stdin'] = subprocess.PIPE
948 # Starting in svn 1.5 --non-interactive is a global flag
948 # Starting in svn 1.5 --non-interactive is a global flag
949 # instead of being per-command, but we need to support 1.4 so
949 # instead of being per-command, but we need to support 1.4 so
950 # we have to be intelligent about what commands take
950 # we have to be intelligent about what commands take
951 # --non-interactive.
951 # --non-interactive.
952 if commands[0] in ('update', 'checkout', 'commit'):
952 if commands[0] in ('update', 'checkout', 'commit'):
953 cmd.append('--non-interactive')
953 cmd.append('--non-interactive')
954 cmd.extend(commands)
954 cmd.extend(commands)
955 if filename is not None:
955 if filename is not None:
956 path = self.wvfs.reljoin(self._ctx.repo().origroot,
956 path = self.wvfs.reljoin(self._ctx.repo().origroot,
957 self._path, filename)
957 self._path, filename)
958 cmd.append(path)
958 cmd.append(path)
959 env = dict(encoding.environ)
959 env = dict(encoding.environ)
960 # Avoid localized output, preserve current locale for everything else.
960 # Avoid localized output, preserve current locale for everything else.
961 lc_all = env.get('LC_ALL')
961 lc_all = env.get('LC_ALL')
962 if lc_all:
962 if lc_all:
963 env['LANG'] = lc_all
963 env['LANG'] = lc_all
964 del env['LC_ALL']
964 del env['LC_ALL']
965 env['LC_MESSAGES'] = 'C'
965 env['LC_MESSAGES'] = 'C'
966 p = subprocess.Popen(pycompat.rapply(procutil.tonativestr, cmd),
966 p = subprocess.Popen(pycompat.rapply(procutil.tonativestr, cmd),
967 bufsize=-1, close_fds=procutil.closefds,
967 bufsize=-1, close_fds=procutil.closefds,
968 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
968 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
969 env=procutil.tonativeenv(env), **extrakw)
969 env=procutil.tonativeenv(env), **extrakw)
970 stdout, stderr = map(util.fromnativeeol, p.communicate())
970 stdout, stderr = map(util.fromnativeeol, p.communicate())
971 stderr = stderr.strip()
971 stderr = stderr.strip()
972 if not failok:
972 if not failok:
973 if p.returncode:
973 if p.returncode:
974 raise error.Abort(stderr or 'exited with code %d'
974 raise error.Abort(stderr or 'exited with code %d'
975 % p.returncode)
975 % p.returncode)
976 if stderr:
976 if stderr:
977 self.ui.warn(stderr + '\n')
977 self.ui.warn(stderr + '\n')
978 return stdout, stderr
978 return stdout, stderr
979
979
980 @propertycache
980 @propertycache
981 def _svnversion(self):
981 def _svnversion(self):
982 output, err = self._svncommand(['--version', '--quiet'], filename=None)
982 output, err = self._svncommand(['--version', '--quiet'], filename=None)
983 m = re.search(br'^(\d+)\.(\d+)', output)
983 m = re.search(br'^(\d+)\.(\d+)', output)
984 if not m:
984 if not m:
985 raise error.Abort(_('cannot retrieve svn tool version'))
985 raise error.Abort(_('cannot retrieve svn tool version'))
986 return (int(m.group(1)), int(m.group(2)))
986 return (int(m.group(1)), int(m.group(2)))
987
987
988 def _svnmissing(self):
988 def _svnmissing(self):
989 return not self.wvfs.exists('.svn')
989 return not self.wvfs.exists('.svn')
990
990
991 def _wcrevs(self):
991 def _wcrevs(self):
992 # Get the working directory revision as well as the last
992 # Get the working directory revision as well as the last
993 # commit revision so we can compare the subrepo state with
993 # commit revision so we can compare the subrepo state with
994 # both. We used to store the working directory one.
994 # both. We used to store the working directory one.
995 output, err = self._svncommand(['info', '--xml'])
995 output, err = self._svncommand(['info', '--xml'])
996 doc = xml.dom.minidom.parseString(output)
996 doc = xml.dom.minidom.parseString(output)
997 entries = doc.getElementsByTagName(r'entry')
997 entries = doc.getElementsByTagName(r'entry')
998 lastrev, rev = '0', '0'
998 lastrev, rev = '0', '0'
999 if entries:
999 if entries:
1000 rev = pycompat.bytestr(entries[0].getAttribute(r'revision')) or '0'
1000 rev = pycompat.bytestr(entries[0].getAttribute(r'revision')) or '0'
1001 commits = entries[0].getElementsByTagName(r'commit')
1001 commits = entries[0].getElementsByTagName(r'commit')
1002 if commits:
1002 if commits:
1003 lastrev = pycompat.bytestr(
1003 lastrev = pycompat.bytestr(
1004 commits[0].getAttribute(r'revision')) or '0'
1004 commits[0].getAttribute(r'revision')) or '0'
1005 return (lastrev, rev)
1005 return (lastrev, rev)
1006
1006
1007 def _wcrev(self):
1007 def _wcrev(self):
1008 return self._wcrevs()[0]
1008 return self._wcrevs()[0]
1009
1009
1010 def _wcchanged(self):
1010 def _wcchanged(self):
1011 """Return (changes, extchanges, missing) where changes is True
1011 """Return (changes, extchanges, missing) where changes is True
1012 if the working directory was changed, extchanges is
1012 if the working directory was changed, extchanges is
1013 True if any of these changes concern an external entry and missing
1013 True if any of these changes concern an external entry and missing
1014 is True if any change is a missing entry.
1014 is True if any change is a missing entry.
1015 """
1015 """
1016 output, err = self._svncommand(['status', '--xml'])
1016 output, err = self._svncommand(['status', '--xml'])
1017 externals, changes, missing = [], [], []
1017 externals, changes, missing = [], [], []
1018 doc = xml.dom.minidom.parseString(output)
1018 doc = xml.dom.minidom.parseString(output)
1019 for e in doc.getElementsByTagName(r'entry'):
1019 for e in doc.getElementsByTagName(r'entry'):
1020 s = e.getElementsByTagName(r'wc-status')
1020 s = e.getElementsByTagName(r'wc-status')
1021 if not s:
1021 if not s:
1022 continue
1022 continue
1023 item = s[0].getAttribute(r'item')
1023 item = s[0].getAttribute(r'item')
1024 props = s[0].getAttribute(r'props')
1024 props = s[0].getAttribute(r'props')
1025 path = e.getAttribute(r'path').encode('utf8')
1025 path = e.getAttribute(r'path').encode('utf8')
1026 if item == r'external':
1026 if item == r'external':
1027 externals.append(path)
1027 externals.append(path)
1028 elif item == r'missing':
1028 elif item == r'missing':
1029 missing.append(path)
1029 missing.append(path)
1030 if (item not in (r'', r'normal', r'unversioned', r'external')
1030 if (item not in (r'', r'normal', r'unversioned', r'external')
1031 or props not in (r'', r'none', r'normal')):
1031 or props not in (r'', r'none', r'normal')):
1032 changes.append(path)
1032 changes.append(path)
1033 for path in changes:
1033 for path in changes:
1034 for ext in externals:
1034 for ext in externals:
1035 if path == ext or path.startswith(ext + pycompat.ossep):
1035 if path == ext or path.startswith(ext + pycompat.ossep):
1036 return True, True, bool(missing)
1036 return True, True, bool(missing)
1037 return bool(changes), False, bool(missing)
1037 return bool(changes), False, bool(missing)
1038
1038
1039 @annotatesubrepoerror
1039 @annotatesubrepoerror
1040 def dirty(self, ignoreupdate=False, missing=False):
1040 def dirty(self, ignoreupdate=False, missing=False):
1041 if self._svnmissing():
1041 if self._svnmissing():
1042 return self._state[1] != ''
1042 return self._state[1] != ''
1043 wcchanged = self._wcchanged()
1043 wcchanged = self._wcchanged()
1044 changed = wcchanged[0] or (missing and wcchanged[2])
1044 changed = wcchanged[0] or (missing and wcchanged[2])
1045 if not changed:
1045 if not changed:
1046 if self._state[1] in self._wcrevs() or ignoreupdate:
1046 if self._state[1] in self._wcrevs() or ignoreupdate:
1047 return False
1047 return False
1048 return True
1048 return True
1049
1049
1050 def basestate(self):
1050 def basestate(self):
1051 lastrev, rev = self._wcrevs()
1051 lastrev, rev = self._wcrevs()
1052 if lastrev != rev:
1052 if lastrev != rev:
1053 # Last committed rev is not the same than rev. We would
1053 # Last committed rev is not the same than rev. We would
1054 # like to take lastrev but we do not know if the subrepo
1054 # like to take lastrev but we do not know if the subrepo
1055 # URL exists at lastrev. Test it and fallback to rev it
1055 # URL exists at lastrev. Test it and fallback to rev it
1056 # is not there.
1056 # is not there.
1057 try:
1057 try:
1058 self._svncommand(['list', '%s@%s' % (self._state[0], lastrev)])
1058 self._svncommand(['list', '%s@%s' % (self._state[0], lastrev)])
1059 return lastrev
1059 return lastrev
1060 except error.Abort:
1060 except error.Abort:
1061 pass
1061 pass
1062 return rev
1062 return rev
1063
1063
1064 @annotatesubrepoerror
1064 @annotatesubrepoerror
1065 def commit(self, text, user, date):
1065 def commit(self, text, user, date):
1066 # user and date are out of our hands since svn is centralized
1066 # user and date are out of our hands since svn is centralized
1067 changed, extchanged, missing = self._wcchanged()
1067 changed, extchanged, missing = self._wcchanged()
1068 if not changed:
1068 if not changed:
1069 return self.basestate()
1069 return self.basestate()
1070 if extchanged:
1070 if extchanged:
1071 # Do not try to commit externals
1071 # Do not try to commit externals
1072 raise error.Abort(_('cannot commit svn externals'))
1072 raise error.Abort(_('cannot commit svn externals'))
1073 if missing:
1073 if missing:
1074 # svn can commit with missing entries but aborting like hg
1074 # svn can commit with missing entries but aborting like hg
1075 # seems a better approach.
1075 # seems a better approach.
1076 raise error.Abort(_('cannot commit missing svn entries'))
1076 raise error.Abort(_('cannot commit missing svn entries'))
1077 commitinfo, err = self._svncommand(['commit', '-m', text])
1077 commitinfo, err = self._svncommand(['commit', '-m', text])
1078 self.ui.status(commitinfo)
1078 self.ui.status(commitinfo)
1079 newrev = re.search('Committed revision ([0-9]+).', commitinfo)
1079 newrev = re.search('Committed revision ([0-9]+).', commitinfo)
1080 if not newrev:
1080 if not newrev:
1081 if not commitinfo.strip():
1081 if not commitinfo.strip():
1082 # Sometimes, our definition of "changed" differs from
1082 # Sometimes, our definition of "changed" differs from
1083 # svn one. For instance, svn ignores missing files
1083 # svn one. For instance, svn ignores missing files
1084 # when committing. If there are only missing files, no
1084 # when committing. If there are only missing files, no
1085 # commit is made, no output and no error code.
1085 # commit is made, no output and no error code.
1086 raise error.Abort(_('failed to commit svn changes'))
1086 raise error.Abort(_('failed to commit svn changes'))
1087 raise error.Abort(commitinfo.splitlines()[-1])
1087 raise error.Abort(commitinfo.splitlines()[-1])
1088 newrev = newrev.groups()[0]
1088 newrev = newrev.groups()[0]
1089 self.ui.status(self._svncommand(['update', '-r', newrev])[0])
1089 self.ui.status(self._svncommand(['update', '-r', newrev])[0])
1090 return newrev
1090 return newrev
1091
1091
1092 @annotatesubrepoerror
1092 @annotatesubrepoerror
1093 def remove(self):
1093 def remove(self):
1094 if self.dirty():
1094 if self.dirty():
1095 self.ui.warn(_('not removing repo %s because '
1095 self.ui.warn(_('not removing repo %s because '
1096 'it has changes.\n') % self._path)
1096 'it has changes.\n') % self._path)
1097 return
1097 return
1098 self.ui.note(_('removing subrepo %s\n') % self._path)
1098 self.ui.note(_('removing subrepo %s\n') % self._path)
1099
1099
1100 self.wvfs.rmtree(forcibly=True)
1100 self.wvfs.rmtree(forcibly=True)
1101 try:
1101 try:
1102 pwvfs = self._ctx.repo().wvfs
1102 pwvfs = self._ctx.repo().wvfs
1103 pwvfs.removedirs(pwvfs.dirname(self._path))
1103 pwvfs.removedirs(pwvfs.dirname(self._path))
1104 except OSError:
1104 except OSError:
1105 pass
1105 pass
1106
1106
1107 @annotatesubrepoerror
1107 @annotatesubrepoerror
1108 def get(self, state, overwrite=False):
1108 def get(self, state, overwrite=False):
1109 if overwrite:
1109 if overwrite:
1110 self._svncommand(['revert', '--recursive'])
1110 self._svncommand(['revert', '--recursive'])
1111 args = ['checkout']
1111 args = ['checkout']
1112 if self._svnversion >= (1, 5):
1112 if self._svnversion >= (1, 5):
1113 args.append('--force')
1113 args.append('--force')
1114 # The revision must be specified at the end of the URL to properly
1114 # The revision must be specified at the end of the URL to properly
1115 # update to a directory which has since been deleted and recreated.
1115 # update to a directory which has since been deleted and recreated.
1116 args.append('%s@%s' % (state[0], state[1]))
1116 args.append('%s@%s' % (state[0], state[1]))
1117
1117
1118 # SEC: check that the ssh url is safe
1118 # SEC: check that the ssh url is safe
1119 util.checksafessh(state[0])
1119 util.checksafessh(state[0])
1120
1120
1121 status, err = self._svncommand(args, failok=True)
1121 status, err = self._svncommand(args, failok=True)
1122 _sanitize(self.ui, self.wvfs, '.svn')
1122 _sanitize(self.ui, self.wvfs, '.svn')
1123 if not re.search('Checked out revision [0-9]+.', status):
1123 if not re.search('Checked out revision [0-9]+.', status):
1124 if ('is already a working copy for a different URL' in err
1124 if ('is already a working copy for a different URL' in err
1125 and (self._wcchanged()[:2] == (False, False))):
1125 and (self._wcchanged()[:2] == (False, False))):
1126 # obstructed but clean working copy, so just blow it away.
1126 # obstructed but clean working copy, so just blow it away.
1127 self.remove()
1127 self.remove()
1128 self.get(state, overwrite=False)
1128 self.get(state, overwrite=False)
1129 return
1129 return
1130 raise error.Abort((status or err).splitlines()[-1])
1130 raise error.Abort((status or err).splitlines()[-1])
1131 self.ui.status(status)
1131 self.ui.status(status)
1132
1132
1133 @annotatesubrepoerror
1133 @annotatesubrepoerror
1134 def merge(self, state):
1134 def merge(self, state):
1135 old = self._state[1]
1135 old = self._state[1]
1136 new = state[1]
1136 new = state[1]
1137 wcrev = self._wcrev()
1137 wcrev = self._wcrev()
1138 if new != wcrev:
1138 if new != wcrev:
1139 dirty = old == wcrev or self._wcchanged()[0]
1139 dirty = old == wcrev or self._wcchanged()[0]
1140 if _updateprompt(self.ui, self, dirty, wcrev, new):
1140 if _updateprompt(self.ui, self, dirty, wcrev, new):
1141 self.get(state, False)
1141 self.get(state, False)
1142
1142
1143 def push(self, opts):
1143 def push(self, opts):
1144 # push is a no-op for SVN
1144 # push is a no-op for SVN
1145 return True
1145 return True
1146
1146
1147 @annotatesubrepoerror
1147 @annotatesubrepoerror
1148 def files(self):
1148 def files(self):
1149 output = self._svncommand(['list', '--recursive', '--xml'])[0]
1149 output = self._svncommand(['list', '--recursive', '--xml'])[0]
1150 doc = xml.dom.minidom.parseString(output)
1150 doc = xml.dom.minidom.parseString(output)
1151 paths = []
1151 paths = []
1152 for e in doc.getElementsByTagName(r'entry'):
1152 for e in doc.getElementsByTagName(r'entry'):
1153 kind = pycompat.bytestr(e.getAttribute(r'kind'))
1153 kind = pycompat.bytestr(e.getAttribute(r'kind'))
1154 if kind != 'file':
1154 if kind != 'file':
1155 continue
1155 continue
1156 name = r''.join(c.data for c
1156 name = r''.join(c.data for c
1157 in e.getElementsByTagName(r'name')[0].childNodes
1157 in e.getElementsByTagName(r'name')[0].childNodes
1158 if c.nodeType == c.TEXT_NODE)
1158 if c.nodeType == c.TEXT_NODE)
1159 paths.append(name.encode('utf8'))
1159 paths.append(name.encode('utf8'))
1160 return paths
1160 return paths
1161
1161
1162 def filedata(self, name, decode):
1162 def filedata(self, name, decode):
1163 return self._svncommand(['cat'], name)[0]
1163 return self._svncommand(['cat'], name)[0]
1164
1164
1165
1165
1166 class gitsubrepo(abstractsubrepo):
1166 class gitsubrepo(abstractsubrepo):
1167 def __init__(self, ctx, path, state, allowcreate):
1167 def __init__(self, ctx, path, state, allowcreate):
1168 super(gitsubrepo, self).__init__(ctx, path)
1168 super(gitsubrepo, self).__init__(ctx, path)
1169 self._state = state
1169 self._state = state
1170 self._abspath = ctx.repo().wjoin(path)
1170 self._abspath = ctx.repo().wjoin(path)
1171 self._subparent = ctx.repo()
1171 self._subparent = ctx.repo()
1172 self._ensuregit()
1172 self._ensuregit()
1173
1173
1174 def _ensuregit(self):
1174 def _ensuregit(self):
1175 try:
1175 try:
1176 self._gitexecutable = 'git'
1176 self._gitexecutable = 'git'
1177 out, err = self._gitnodir(['--version'])
1177 out, err = self._gitnodir(['--version'])
1178 except OSError as e:
1178 except OSError as e:
1179 genericerror = _("error executing git for subrepo '%s': %s")
1179 genericerror = _("error executing git for subrepo '%s': %s")
1180 notfoundhint = _("check git is installed and in your PATH")
1180 notfoundhint = _("check git is installed and in your PATH")
1181 if e.errno != errno.ENOENT:
1181 if e.errno != errno.ENOENT:
1182 raise error.Abort(genericerror % (
1182 raise error.Abort(genericerror % (
1183 self._path, encoding.strtolocal(e.strerror)))
1183 self._path, encoding.strtolocal(e.strerror)))
1184 elif pycompat.iswindows:
1184 elif pycompat.iswindows:
1185 try:
1185 try:
1186 self._gitexecutable = 'git.cmd'
1186 self._gitexecutable = 'git.cmd'
1187 out, err = self._gitnodir(['--version'])
1187 out, err = self._gitnodir(['--version'])
1188 except OSError as e2:
1188 except OSError as e2:
1189 if e2.errno == errno.ENOENT:
1189 if e2.errno == errno.ENOENT:
1190 raise error.Abort(_("couldn't find 'git' or 'git.cmd'"
1190 raise error.Abort(_("couldn't find 'git' or 'git.cmd'"
1191 " for subrepo '%s'") % self._path,
1191 " for subrepo '%s'") % self._path,
1192 hint=notfoundhint)
1192 hint=notfoundhint)
1193 else:
1193 else:
1194 raise error.Abort(genericerror % (self._path,
1194 raise error.Abort(genericerror % (self._path,
1195 encoding.strtolocal(e2.strerror)))
1195 encoding.strtolocal(e2.strerror)))
1196 else:
1196 else:
1197 raise error.Abort(_("couldn't find git for subrepo '%s'")
1197 raise error.Abort(_("couldn't find git for subrepo '%s'")
1198 % self._path, hint=notfoundhint)
1198 % self._path, hint=notfoundhint)
1199 versionstatus = self._checkversion(out)
1199 versionstatus = self._checkversion(out)
1200 if versionstatus == 'unknown':
1200 if versionstatus == 'unknown':
1201 self.ui.warn(_('cannot retrieve git version\n'))
1201 self.ui.warn(_('cannot retrieve git version\n'))
1202 elif versionstatus == 'abort':
1202 elif versionstatus == 'abort':
1203 raise error.Abort(_('git subrepo requires at least 1.6.0 or later'))
1203 raise error.Abort(_('git subrepo requires at least 1.6.0 or later'))
1204 elif versionstatus == 'warning':
1204 elif versionstatus == 'warning':
1205 self.ui.warn(_('git subrepo requires at least 1.6.0 or later\n'))
1205 self.ui.warn(_('git subrepo requires at least 1.6.0 or later\n'))
1206
1206
1207 @staticmethod
1207 @staticmethod
1208 def _gitversion(out):
1208 def _gitversion(out):
1209 m = re.search(br'^git version (\d+)\.(\d+)\.(\d+)', out)
1209 m = re.search(br'^git version (\d+)\.(\d+)\.(\d+)', out)
1210 if m:
1210 if m:
1211 return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
1211 return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
1212
1212
1213 m = re.search(br'^git version (\d+)\.(\d+)', out)
1213 m = re.search(br'^git version (\d+)\.(\d+)', out)
1214 if m:
1214 if m:
1215 return (int(m.group(1)), int(m.group(2)), 0)
1215 return (int(m.group(1)), int(m.group(2)), 0)
1216
1216
1217 return -1
1217 return -1
1218
1218
1219 @staticmethod
1219 @staticmethod
1220 def _checkversion(out):
1220 def _checkversion(out):
1221 '''ensure git version is new enough
1221 '''ensure git version is new enough
1222
1222
1223 >>> _checkversion = gitsubrepo._checkversion
1223 >>> _checkversion = gitsubrepo._checkversion
1224 >>> _checkversion(b'git version 1.6.0')
1224 >>> _checkversion(b'git version 1.6.0')
1225 'ok'
1225 'ok'
1226 >>> _checkversion(b'git version 1.8.5')
1226 >>> _checkversion(b'git version 1.8.5')
1227 'ok'
1227 'ok'
1228 >>> _checkversion(b'git version 1.4.0')
1228 >>> _checkversion(b'git version 1.4.0')
1229 'abort'
1229 'abort'
1230 >>> _checkversion(b'git version 1.5.0')
1230 >>> _checkversion(b'git version 1.5.0')
1231 'warning'
1231 'warning'
1232 >>> _checkversion(b'git version 1.9-rc0')
1232 >>> _checkversion(b'git version 1.9-rc0')
1233 'ok'
1233 'ok'
1234 >>> _checkversion(b'git version 1.9.0.265.g81cdec2')
1234 >>> _checkversion(b'git version 1.9.0.265.g81cdec2')
1235 'ok'
1235 'ok'
1236 >>> _checkversion(b'git version 1.9.0.GIT')
1236 >>> _checkversion(b'git version 1.9.0.GIT')
1237 'ok'
1237 'ok'
1238 >>> _checkversion(b'git version 12345')
1238 >>> _checkversion(b'git version 12345')
1239 'unknown'
1239 'unknown'
1240 >>> _checkversion(b'no')
1240 >>> _checkversion(b'no')
1241 'unknown'
1241 'unknown'
1242 '''
1242 '''
1243 version = gitsubrepo._gitversion(out)
1243 version = gitsubrepo._gitversion(out)
1244 # git 1.4.0 can't work at all, but 1.5.X can in at least some cases,
1244 # git 1.4.0 can't work at all, but 1.5.X can in at least some cases,
1245 # despite the docstring comment. For now, error on 1.4.0, warn on
1245 # despite the docstring comment. For now, error on 1.4.0, warn on
1246 # 1.5.0 but attempt to continue.
1246 # 1.5.0 but attempt to continue.
1247 if version == -1:
1247 if version == -1:
1248 return 'unknown'
1248 return 'unknown'
1249 if version < (1, 5, 0):
1249 if version < (1, 5, 0):
1250 return 'abort'
1250 return 'abort'
1251 elif version < (1, 6, 0):
1251 elif version < (1, 6, 0):
1252 return 'warning'
1252 return 'warning'
1253 return 'ok'
1253 return 'ok'
1254
1254
1255 def _gitcommand(self, commands, env=None, stream=False):
1255 def _gitcommand(self, commands, env=None, stream=False):
1256 return self._gitdir(commands, env=env, stream=stream)[0]
1256 return self._gitdir(commands, env=env, stream=stream)[0]
1257
1257
1258 def _gitdir(self, commands, env=None, stream=False):
1258 def _gitdir(self, commands, env=None, stream=False):
1259 return self._gitnodir(commands, env=env, stream=stream,
1259 return self._gitnodir(commands, env=env, stream=stream,
1260 cwd=self._abspath)
1260 cwd=self._abspath)
1261
1261
1262 def _gitnodir(self, commands, env=None, stream=False, cwd=None):
1262 def _gitnodir(self, commands, env=None, stream=False, cwd=None):
1263 """Calls the git command
1263 """Calls the git command
1264
1264
1265 The methods tries to call the git command. versions prior to 1.6.0
1265 The methods tries to call the git command. versions prior to 1.6.0
1266 are not supported and very probably fail.
1266 are not supported and very probably fail.
1267 """
1267 """
1268 self.ui.debug('%s: git %s\n' % (self._relpath, ' '.join(commands)))
1268 self.ui.debug('%s: git %s\n' % (self._relpath, ' '.join(commands)))
1269 if env is None:
1269 if env is None:
1270 env = encoding.environ.copy()
1270 env = encoding.environ.copy()
1271 # disable localization for Git output (issue5176)
1271 # disable localization for Git output (issue5176)
1272 env['LC_ALL'] = 'C'
1272 env['LC_ALL'] = 'C'
1273 # fix for Git CVE-2015-7545
1273 # fix for Git CVE-2015-7545
1274 if 'GIT_ALLOW_PROTOCOL' not in env:
1274 if 'GIT_ALLOW_PROTOCOL' not in env:
1275 env['GIT_ALLOW_PROTOCOL'] = 'file:git:http:https:ssh'
1275 env['GIT_ALLOW_PROTOCOL'] = 'file:git:http:https:ssh'
1276 # unless ui.quiet is set, print git's stderr,
1276 # unless ui.quiet is set, print git's stderr,
1277 # which is mostly progress and useful info
1277 # which is mostly progress and useful info
1278 errpipe = None
1278 errpipe = None
1279 if self.ui.quiet:
1279 if self.ui.quiet:
1280 errpipe = open(os.devnull, 'w')
1280 errpipe = open(os.devnull, 'w')
1281 if self.ui._colormode and len(commands) and commands[0] == "diff":
1281 if self.ui._colormode and len(commands) and commands[0] == "diff":
1282 # insert the argument in the front,
1282 # insert the argument in the front,
1283 # the end of git diff arguments is used for paths
1283 # the end of git diff arguments is used for paths
1284 commands.insert(1, '--color')
1284 commands.insert(1, '--color')
1285 p = subprocess.Popen(pycompat.rapply(procutil.tonativestr,
1285 p = subprocess.Popen(pycompat.rapply(procutil.tonativestr,
1286 [self._gitexecutable] + commands),
1286 [self._gitexecutable] + commands),
1287 bufsize=-1,
1287 bufsize=-1,
1288 cwd=pycompat.rapply(procutil.tonativestr, cwd),
1288 cwd=pycompat.rapply(procutil.tonativestr, cwd),
1289 env=procutil.tonativeenv(env),
1289 env=procutil.tonativeenv(env),
1290 close_fds=procutil.closefds,
1290 close_fds=procutil.closefds,
1291 stdout=subprocess.PIPE, stderr=errpipe)
1291 stdout=subprocess.PIPE, stderr=errpipe)
1292 if stream:
1292 if stream:
1293 return p.stdout, None
1293 return p.stdout, None
1294
1294
1295 retdata = p.stdout.read().strip()
1295 retdata = p.stdout.read().strip()
1296 # wait for the child to exit to avoid race condition.
1296 # wait for the child to exit to avoid race condition.
1297 p.wait()
1297 p.wait()
1298
1298
1299 if p.returncode != 0 and p.returncode != 1:
1299 if p.returncode != 0 and p.returncode != 1:
1300 # there are certain error codes that are ok
1300 # there are certain error codes that are ok
1301 command = commands[0]
1301 command = commands[0]
1302 if command in ('cat-file', 'symbolic-ref'):
1302 if command in ('cat-file', 'symbolic-ref'):
1303 return retdata, p.returncode
1303 return retdata, p.returncode
1304 # for all others, abort
1304 # for all others, abort
1305 raise error.Abort(_('git %s error %d in %s') %
1305 raise error.Abort(_('git %s error %d in %s') %
1306 (command, p.returncode, self._relpath))
1306 (command, p.returncode, self._relpath))
1307
1307
1308 return retdata, p.returncode
1308 return retdata, p.returncode
1309
1309
1310 def _gitmissing(self):
1310 def _gitmissing(self):
1311 return not self.wvfs.exists('.git')
1311 return not self.wvfs.exists('.git')
1312
1312
1313 def _gitstate(self):
1313 def _gitstate(self):
1314 return self._gitcommand(['rev-parse', 'HEAD'])
1314 return self._gitcommand(['rev-parse', 'HEAD'])
1315
1315
1316 def _gitcurrentbranch(self):
1316 def _gitcurrentbranch(self):
1317 current, err = self._gitdir(['symbolic-ref', 'HEAD', '--quiet'])
1317 current, err = self._gitdir(['symbolic-ref', 'HEAD', '--quiet'])
1318 if err:
1318 if err:
1319 current = None
1319 current = None
1320 return current
1320 return current
1321
1321
1322 def _gitremote(self, remote):
1322 def _gitremote(self, remote):
1323 out = self._gitcommand(['remote', 'show', '-n', remote])
1323 out = self._gitcommand(['remote', 'show', '-n', remote])
1324 line = out.split('\n')[1]
1324 line = out.split('\n')[1]
1325 i = line.index('URL: ') + len('URL: ')
1325 i = line.index('URL: ') + len('URL: ')
1326 return line[i:]
1326 return line[i:]
1327
1327
1328 def _githavelocally(self, revision):
1328 def _githavelocally(self, revision):
1329 out, code = self._gitdir(['cat-file', '-e', revision])
1329 out, code = self._gitdir(['cat-file', '-e', revision])
1330 return code == 0
1330 return code == 0
1331
1331
1332 def _gitisancestor(self, r1, r2):
1332 def _gitisancestor(self, r1, r2):
1333 base = self._gitcommand(['merge-base', r1, r2])
1333 base = self._gitcommand(['merge-base', r1, r2])
1334 return base == r1
1334 return base == r1
1335
1335
1336 def _gitisbare(self):
1336 def _gitisbare(self):
1337 return self._gitcommand(['config', '--bool', 'core.bare']) == 'true'
1337 return self._gitcommand(['config', '--bool', 'core.bare']) == 'true'
1338
1338
1339 def _gitupdatestat(self):
1339 def _gitupdatestat(self):
1340 """This must be run before git diff-index.
1340 """This must be run before git diff-index.
1341 diff-index only looks at changes to file stat;
1341 diff-index only looks at changes to file stat;
1342 this command looks at file contents and updates the stat."""
1342 this command looks at file contents and updates the stat."""
1343 self._gitcommand(['update-index', '-q', '--refresh'])
1343 self._gitcommand(['update-index', '-q', '--refresh'])
1344
1344
1345 def _gitbranchmap(self):
1345 def _gitbranchmap(self):
1346 '''returns 2 things:
1346 '''returns 2 things:
1347 a map from git branch to revision
1347 a map from git branch to revision
1348 a map from revision to branches'''
1348 a map from revision to branches'''
1349 branch2rev = {}
1349 branch2rev = {}
1350 rev2branch = {}
1350 rev2branch = {}
1351
1351
1352 out = self._gitcommand(['for-each-ref', '--format',
1352 out = self._gitcommand(['for-each-ref', '--format',
1353 '%(objectname) %(refname)'])
1353 '%(objectname) %(refname)'])
1354 for line in out.split('\n'):
1354 for line in out.split('\n'):
1355 revision, ref = line.split(' ')
1355 revision, ref = line.split(' ')
1356 if (not ref.startswith('refs/heads/') and
1356 if (not ref.startswith('refs/heads/') and
1357 not ref.startswith('refs/remotes/')):
1357 not ref.startswith('refs/remotes/')):
1358 continue
1358 continue
1359 if ref.startswith('refs/remotes/') and ref.endswith('/HEAD'):
1359 if ref.startswith('refs/remotes/') and ref.endswith('/HEAD'):
1360 continue # ignore remote/HEAD redirects
1360 continue # ignore remote/HEAD redirects
1361 branch2rev[ref] = revision
1361 branch2rev[ref] = revision
1362 rev2branch.setdefault(revision, []).append(ref)
1362 rev2branch.setdefault(revision, []).append(ref)
1363 return branch2rev, rev2branch
1363 return branch2rev, rev2branch
1364
1364
1365 def _gittracking(self, branches):
1365 def _gittracking(self, branches):
1366 'return map of remote branch to local tracking branch'
1366 'return map of remote branch to local tracking branch'
1367 # assumes no more than one local tracking branch for each remote
1367 # assumes no more than one local tracking branch for each remote
1368 tracking = {}
1368 tracking = {}
1369 for b in branches:
1369 for b in branches:
1370 if b.startswith('refs/remotes/'):
1370 if b.startswith('refs/remotes/'):
1371 continue
1371 continue
1372 bname = b.split('/', 2)[2]
1372 bname = b.split('/', 2)[2]
1373 remote = self._gitcommand(['config', 'branch.%s.remote' % bname])
1373 remote = self._gitcommand(['config', 'branch.%s.remote' % bname])
1374 if remote:
1374 if remote:
1375 ref = self._gitcommand(['config', 'branch.%s.merge' % bname])
1375 ref = self._gitcommand(['config', 'branch.%s.merge' % bname])
1376 tracking['refs/remotes/%s/%s' %
1376 tracking['refs/remotes/%s/%s' %
1377 (remote, ref.split('/', 2)[2])] = b
1377 (remote, ref.split('/', 2)[2])] = b
1378 return tracking
1378 return tracking
1379
1379
1380 def _abssource(self, source):
1380 def _abssource(self, source):
1381 if '://' not in source:
1381 if '://' not in source:
1382 # recognize the scp syntax as an absolute source
1382 # recognize the scp syntax as an absolute source
1383 colon = source.find(':')
1383 colon = source.find(':')
1384 if colon != -1 and '/' not in source[:colon]:
1384 if colon != -1 and '/' not in source[:colon]:
1385 return source
1385 return source
1386 self._subsource = source
1386 self._subsource = source
1387 return _abssource(self)
1387 return _abssource(self)
1388
1388
1389 def _fetch(self, source, revision):
1389 def _fetch(self, source, revision):
1390 if self._gitmissing():
1390 if self._gitmissing():
1391 # SEC: check for safe ssh url
1391 # SEC: check for safe ssh url
1392 util.checksafessh(source)
1392 util.checksafessh(source)
1393
1393
1394 source = self._abssource(source)
1394 source = self._abssource(source)
1395 self.ui.status(_('cloning subrepo %s from %s\n') %
1395 self.ui.status(_('cloning subrepo %s from %s\n') %
1396 (self._relpath, source))
1396 (self._relpath, source))
1397 self._gitnodir(['clone', source, self._abspath])
1397 self._gitnodir(['clone', source, self._abspath])
1398 if self._githavelocally(revision):
1398 if self._githavelocally(revision):
1399 return
1399 return
1400 self.ui.status(_('pulling subrepo %s from %s\n') %
1400 self.ui.status(_('pulling subrepo %s from %s\n') %
1401 (self._relpath, self._gitremote('origin')))
1401 (self._relpath, self._gitremote('origin')))
1402 # try only origin: the originally cloned repo
1402 # try only origin: the originally cloned repo
1403 self._gitcommand(['fetch'])
1403 self._gitcommand(['fetch'])
1404 if not self._githavelocally(revision):
1404 if not self._githavelocally(revision):
1405 raise error.Abort(_('revision %s does not exist in subrepository '
1405 raise error.Abort(_('revision %s does not exist in subrepository '
1406 '"%s"\n') % (revision, self._relpath))
1406 '"%s"\n') % (revision, self._relpath))
1407
1407
1408 @annotatesubrepoerror
1408 @annotatesubrepoerror
1409 def dirty(self, ignoreupdate=False, missing=False):
1409 def dirty(self, ignoreupdate=False, missing=False):
1410 if self._gitmissing():
1410 if self._gitmissing():
1411 return self._state[1] != ''
1411 return self._state[1] != ''
1412 if self._gitisbare():
1412 if self._gitisbare():
1413 return True
1413 return True
1414 if not ignoreupdate and self._state[1] != self._gitstate():
1414 if not ignoreupdate and self._state[1] != self._gitstate():
1415 # different version checked out
1415 # different version checked out
1416 return True
1416 return True
1417 # check for staged changes or modified files; ignore untracked files
1417 # check for staged changes or modified files; ignore untracked files
1418 self._gitupdatestat()
1418 self._gitupdatestat()
1419 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1419 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1420 return code == 1
1420 return code == 1
1421
1421
1422 def basestate(self):
1422 def basestate(self):
1423 return self._gitstate()
1423 return self._gitstate()
1424
1424
1425 @annotatesubrepoerror
1425 @annotatesubrepoerror
1426 def get(self, state, overwrite=False):
1426 def get(self, state, overwrite=False):
1427 source, revision, kind = state
1427 source, revision, kind = state
1428 if not revision:
1428 if not revision:
1429 self.remove()
1429 self.remove()
1430 return
1430 return
1431 self._fetch(source, revision)
1431 self._fetch(source, revision)
1432 # if the repo was set to be bare, unbare it
1432 # if the repo was set to be bare, unbare it
1433 if self._gitisbare():
1433 if self._gitisbare():
1434 self._gitcommand(['config', 'core.bare', 'false'])
1434 self._gitcommand(['config', 'core.bare', 'false'])
1435 if self._gitstate() == revision:
1435 if self._gitstate() == revision:
1436 self._gitcommand(['reset', '--hard', 'HEAD'])
1436 self._gitcommand(['reset', '--hard', 'HEAD'])
1437 return
1437 return
1438 elif self._gitstate() == revision:
1438 elif self._gitstate() == revision:
1439 if overwrite:
1439 if overwrite:
1440 # first reset the index to unmark new files for commit, because
1440 # first reset the index to unmark new files for commit, because
1441 # reset --hard will otherwise throw away files added for commit,
1441 # reset --hard will otherwise throw away files added for commit,
1442 # not just unmark them.
1442 # not just unmark them.
1443 self._gitcommand(['reset', 'HEAD'])
1443 self._gitcommand(['reset', 'HEAD'])
1444 self._gitcommand(['reset', '--hard', 'HEAD'])
1444 self._gitcommand(['reset', '--hard', 'HEAD'])
1445 return
1445 return
1446 branch2rev, rev2branch = self._gitbranchmap()
1446 branch2rev, rev2branch = self._gitbranchmap()
1447
1447
1448 def checkout(args):
1448 def checkout(args):
1449 cmd = ['checkout']
1449 cmd = ['checkout']
1450 if overwrite:
1450 if overwrite:
1451 # first reset the index to unmark new files for commit, because
1451 # first reset the index to unmark new files for commit, because
1452 # the -f option will otherwise throw away files added for
1452 # the -f option will otherwise throw away files added for
1453 # commit, not just unmark them.
1453 # commit, not just unmark them.
1454 self._gitcommand(['reset', 'HEAD'])
1454 self._gitcommand(['reset', 'HEAD'])
1455 cmd.append('-f')
1455 cmd.append('-f')
1456 self._gitcommand(cmd + args)
1456 self._gitcommand(cmd + args)
1457 _sanitize(self.ui, self.wvfs, '.git')
1457 _sanitize(self.ui, self.wvfs, '.git')
1458
1458
1459 def rawcheckout():
1459 def rawcheckout():
1460 # no branch to checkout, check it out with no branch
1460 # no branch to checkout, check it out with no branch
1461 self.ui.warn(_('checking out detached HEAD in '
1461 self.ui.warn(_('checking out detached HEAD in '
1462 'subrepository "%s"\n') % self._relpath)
1462 'subrepository "%s"\n') % self._relpath)
1463 self.ui.warn(_('check out a git branch if you intend '
1463 self.ui.warn(_('check out a git branch if you intend '
1464 'to make changes\n'))
1464 'to make changes\n'))
1465 checkout(['-q', revision])
1465 checkout(['-q', revision])
1466
1466
1467 if revision not in rev2branch:
1467 if revision not in rev2branch:
1468 rawcheckout()
1468 rawcheckout()
1469 return
1469 return
1470 branches = rev2branch[revision]
1470 branches = rev2branch[revision]
1471 firstlocalbranch = None
1471 firstlocalbranch = None
1472 for b in branches:
1472 for b in branches:
1473 if b == 'refs/heads/master':
1473 if b == 'refs/heads/master':
1474 # master trumps all other branches
1474 # master trumps all other branches
1475 checkout(['refs/heads/master'])
1475 checkout(['refs/heads/master'])
1476 return
1476 return
1477 if not firstlocalbranch and not b.startswith('refs/remotes/'):
1477 if not firstlocalbranch and not b.startswith('refs/remotes/'):
1478 firstlocalbranch = b
1478 firstlocalbranch = b
1479 if firstlocalbranch:
1479 if firstlocalbranch:
1480 checkout([firstlocalbranch])
1480 checkout([firstlocalbranch])
1481 return
1481 return
1482
1482
1483 tracking = self._gittracking(branch2rev.keys())
1483 tracking = self._gittracking(branch2rev.keys())
1484 # choose a remote branch already tracked if possible
1484 # choose a remote branch already tracked if possible
1485 remote = branches[0]
1485 remote = branches[0]
1486 if remote not in tracking:
1486 if remote not in tracking:
1487 for b in branches:
1487 for b in branches:
1488 if b in tracking:
1488 if b in tracking:
1489 remote = b
1489 remote = b
1490 break
1490 break
1491
1491
1492 if remote not in tracking:
1492 if remote not in tracking:
1493 # create a new local tracking branch
1493 # create a new local tracking branch
1494 local = remote.split('/', 3)[3]
1494 local = remote.split('/', 3)[3]
1495 checkout(['-b', local, remote])
1495 checkout(['-b', local, remote])
1496 elif self._gitisancestor(branch2rev[tracking[remote]], remote):
1496 elif self._gitisancestor(branch2rev[tracking[remote]], remote):
1497 # When updating to a tracked remote branch,
1497 # When updating to a tracked remote branch,
1498 # if the local tracking branch is downstream of it,
1498 # if the local tracking branch is downstream of it,
1499 # a normal `git pull` would have performed a "fast-forward merge"
1499 # a normal `git pull` would have performed a "fast-forward merge"
1500 # which is equivalent to updating the local branch to the remote.
1500 # which is equivalent to updating the local branch to the remote.
1501 # Since we are only looking at branching at update, we need to
1501 # Since we are only looking at branching at update, we need to
1502 # detect this situation and perform this action lazily.
1502 # detect this situation and perform this action lazily.
1503 if tracking[remote] != self._gitcurrentbranch():
1503 if tracking[remote] != self._gitcurrentbranch():
1504 checkout([tracking[remote]])
1504 checkout([tracking[remote]])
1505 self._gitcommand(['merge', '--ff', remote])
1505 self._gitcommand(['merge', '--ff', remote])
1506 _sanitize(self.ui, self.wvfs, '.git')
1506 _sanitize(self.ui, self.wvfs, '.git')
1507 else:
1507 else:
1508 # a real merge would be required, just checkout the revision
1508 # a real merge would be required, just checkout the revision
1509 rawcheckout()
1509 rawcheckout()
1510
1510
1511 @annotatesubrepoerror
1511 @annotatesubrepoerror
1512 def commit(self, text, user, date):
1512 def commit(self, text, user, date):
1513 if self._gitmissing():
1513 if self._gitmissing():
1514 raise error.Abort(_("subrepo %s is missing") % self._relpath)
1514 raise error.Abort(_("subrepo %s is missing") % self._relpath)
1515 cmd = ['commit', '-a', '-m', text]
1515 cmd = ['commit', '-a', '-m', text]
1516 env = encoding.environ.copy()
1516 env = encoding.environ.copy()
1517 if user:
1517 if user:
1518 cmd += ['--author', user]
1518 cmd += ['--author', user]
1519 if date:
1519 if date:
1520 # git's date parser silently ignores when seconds < 1e9
1520 # git's date parser silently ignores when seconds < 1e9
1521 # convert to ISO8601
1521 # convert to ISO8601
1522 env['GIT_AUTHOR_DATE'] = dateutil.datestr(date,
1522 env['GIT_AUTHOR_DATE'] = dateutil.datestr(date,
1523 '%Y-%m-%dT%H:%M:%S %1%2')
1523 '%Y-%m-%dT%H:%M:%S %1%2')
1524 self._gitcommand(cmd, env=env)
1524 self._gitcommand(cmd, env=env)
1525 # make sure commit works otherwise HEAD might not exist under certain
1525 # make sure commit works otherwise HEAD might not exist under certain
1526 # circumstances
1526 # circumstances
1527 return self._gitstate()
1527 return self._gitstate()
1528
1528
1529 @annotatesubrepoerror
1529 @annotatesubrepoerror
1530 def merge(self, state):
1530 def merge(self, state):
1531 source, revision, kind = state
1531 source, revision, kind = state
1532 self._fetch(source, revision)
1532 self._fetch(source, revision)
1533 base = self._gitcommand(['merge-base', revision, self._state[1]])
1533 base = self._gitcommand(['merge-base', revision, self._state[1]])
1534 self._gitupdatestat()
1534 self._gitupdatestat()
1535 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1535 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1536
1536
1537 def mergefunc():
1537 def mergefunc():
1538 if base == revision:
1538 if base == revision:
1539 self.get(state) # fast forward merge
1539 self.get(state) # fast forward merge
1540 elif base != self._state[1]:
1540 elif base != self._state[1]:
1541 self._gitcommand(['merge', '--no-commit', revision])
1541 self._gitcommand(['merge', '--no-commit', revision])
1542 _sanitize(self.ui, self.wvfs, '.git')
1542 _sanitize(self.ui, self.wvfs, '.git')
1543
1543
1544 if self.dirty():
1544 if self.dirty():
1545 if self._gitstate() != revision:
1545 if self._gitstate() != revision:
1546 dirty = self._gitstate() == self._state[1] or code != 0
1546 dirty = self._gitstate() == self._state[1] or code != 0
1547 if _updateprompt(self.ui, self, dirty,
1547 if _updateprompt(self.ui, self, dirty,
1548 self._state[1][:7], revision[:7]):
1548 self._state[1][:7], revision[:7]):
1549 mergefunc()
1549 mergefunc()
1550 else:
1550 else:
1551 mergefunc()
1551 mergefunc()
1552
1552
1553 @annotatesubrepoerror
1553 @annotatesubrepoerror
1554 def push(self, opts):
1554 def push(self, opts):
1555 force = opts.get('force')
1555 force = opts.get('force')
1556
1556
1557 if not self._state[1]:
1557 if not self._state[1]:
1558 return True
1558 return True
1559 if self._gitmissing():
1559 if self._gitmissing():
1560 raise error.Abort(_("subrepo %s is missing") % self._relpath)
1560 raise error.Abort(_("subrepo %s is missing") % self._relpath)
1561 # if a branch in origin contains the revision, nothing to do
1561 # if a branch in origin contains the revision, nothing to do
1562 branch2rev, rev2branch = self._gitbranchmap()
1562 branch2rev, rev2branch = self._gitbranchmap()
1563 if self._state[1] in rev2branch:
1563 if self._state[1] in rev2branch:
1564 for b in rev2branch[self._state[1]]:
1564 for b in rev2branch[self._state[1]]:
1565 if b.startswith('refs/remotes/origin/'):
1565 if b.startswith('refs/remotes/origin/'):
1566 return True
1566 return True
1567 for b, revision in branch2rev.iteritems():
1567 for b, revision in branch2rev.iteritems():
1568 if b.startswith('refs/remotes/origin/'):
1568 if b.startswith('refs/remotes/origin/'):
1569 if self._gitisancestor(self._state[1], revision):
1569 if self._gitisancestor(self._state[1], revision):
1570 return True
1570 return True
1571 # otherwise, try to push the currently checked out branch
1571 # otherwise, try to push the currently checked out branch
1572 cmd = ['push']
1572 cmd = ['push']
1573 if force:
1573 if force:
1574 cmd.append('--force')
1574 cmd.append('--force')
1575
1575
1576 current = self._gitcurrentbranch()
1576 current = self._gitcurrentbranch()
1577 if current:
1577 if current:
1578 # determine if the current branch is even useful
1578 # determine if the current branch is even useful
1579 if not self._gitisancestor(self._state[1], current):
1579 if not self._gitisancestor(self._state[1], current):
1580 self.ui.warn(_('unrelated git branch checked out '
1580 self.ui.warn(_('unrelated git branch checked out '
1581 'in subrepository "%s"\n') % self._relpath)
1581 'in subrepository "%s"\n') % self._relpath)
1582 return False
1582 return False
1583 self.ui.status(_('pushing branch %s of subrepository "%s"\n') %
1583 self.ui.status(_('pushing branch %s of subrepository "%s"\n') %
1584 (current.split('/', 2)[2], self._relpath))
1584 (current.split('/', 2)[2], self._relpath))
1585 ret = self._gitdir(cmd + ['origin', current])
1585 ret = self._gitdir(cmd + ['origin', current])
1586 return ret[1] == 0
1586 return ret[1] == 0
1587 else:
1587 else:
1588 self.ui.warn(_('no branch checked out in subrepository "%s"\n'
1588 self.ui.warn(_('no branch checked out in subrepository "%s"\n'
1589 'cannot push revision %s\n') %
1589 'cannot push revision %s\n') %
1590 (self._relpath, self._state[1]))
1590 (self._relpath, self._state[1]))
1591 return False
1591 return False
1592
1592
1593 @annotatesubrepoerror
1593 @annotatesubrepoerror
1594 def add(self, ui, match, prefix, uipathfn, explicitonly, **opts):
1594 def add(self, ui, match, prefix, uipathfn, explicitonly, **opts):
1595 if self._gitmissing():
1595 if self._gitmissing():
1596 return []
1596 return []
1597
1597
1598 s = self.status(None, unknown=True, clean=True)
1598 s = self.status(None, unknown=True, clean=True)
1599
1599
1600 tracked = set()
1600 tracked = set()
1601 # dirstates 'amn' warn, 'r' is added again
1601 # dirstates 'amn' warn, 'r' is added again
1602 for l in (s.modified, s.added, s.deleted, s.clean):
1602 for l in (s.modified, s.added, s.deleted, s.clean):
1603 tracked.update(l)
1603 tracked.update(l)
1604
1604
1605 # Unknown files not of interest will be rejected by the matcher
1605 # Unknown files not of interest will be rejected by the matcher
1606 files = s.unknown
1606 files = s.unknown
1607 files.extend(match.files())
1607 files.extend(match.files())
1608
1608
1609 rejected = []
1609 rejected = []
1610
1610
1611 files = [f for f in sorted(set(files)) if match(f)]
1611 files = [f for f in sorted(set(files)) if match(f)]
1612 for f in files:
1612 for f in files:
1613 exact = match.exact(f)
1613 exact = match.exact(f)
1614 command = ["add"]
1614 command = ["add"]
1615 if exact:
1615 if exact:
1616 command.append("-f") #should be added, even if ignored
1616 command.append("-f") #should be added, even if ignored
1617 if ui.verbose or not exact:
1617 if ui.verbose or not exact:
1618 ui.status(_('adding %s\n') % uipathfn(f))
1618 ui.status(_('adding %s\n') % uipathfn(f))
1619
1619
1620 if f in tracked: # hg prints 'adding' even if already tracked
1620 if f in tracked: # hg prints 'adding' even if already tracked
1621 if exact:
1621 if exact:
1622 rejected.append(f)
1622 rejected.append(f)
1623 continue
1623 continue
1624 if not opts.get(r'dry_run'):
1624 if not opts.get(r'dry_run'):
1625 self._gitcommand(command + [f])
1625 self._gitcommand(command + [f])
1626
1626
1627 for f in rejected:
1627 for f in rejected:
1628 ui.warn(_("%s already tracked!\n") % uipathfn(f))
1628 ui.warn(_("%s already tracked!\n") % uipathfn(f))
1629
1629
1630 return rejected
1630 return rejected
1631
1631
1632 @annotatesubrepoerror
1632 @annotatesubrepoerror
1633 def remove(self):
1633 def remove(self):
1634 if self._gitmissing():
1634 if self._gitmissing():
1635 return
1635 return
1636 if self.dirty():
1636 if self.dirty():
1637 self.ui.warn(_('not removing repo %s because '
1637 self.ui.warn(_('not removing repo %s because '
1638 'it has changes.\n') % self._relpath)
1638 'it has changes.\n') % self._relpath)
1639 return
1639 return
1640 # we can't fully delete the repository as it may contain
1640 # we can't fully delete the repository as it may contain
1641 # local-only history
1641 # local-only history
1642 self.ui.note(_('removing subrepo %s\n') % self._relpath)
1642 self.ui.note(_('removing subrepo %s\n') % self._relpath)
1643 self._gitcommand(['config', 'core.bare', 'true'])
1643 self._gitcommand(['config', 'core.bare', 'true'])
1644 for f, kind in self.wvfs.readdir():
1644 for f, kind in self.wvfs.readdir():
1645 if f == '.git':
1645 if f == '.git':
1646 continue
1646 continue
1647 if kind == stat.S_IFDIR:
1647 if kind == stat.S_IFDIR:
1648 self.wvfs.rmtree(f)
1648 self.wvfs.rmtree(f)
1649 else:
1649 else:
1650 self.wvfs.unlink(f)
1650 self.wvfs.unlink(f)
1651
1651
1652 def archive(self, archiver, prefix, match=None, decode=True):
1652 def archive(self, archiver, prefix, match=None, decode=True):
1653 total = 0
1653 total = 0
1654 source, revision = self._state
1654 source, revision = self._state
1655 if not revision:
1655 if not revision:
1656 return total
1656 return total
1657 self._fetch(source, revision)
1657 self._fetch(source, revision)
1658
1658
1659 # Parse git's native archive command.
1659 # Parse git's native archive command.
1660 # This should be much faster than manually traversing the trees
1660 # This should be much faster than manually traversing the trees
1661 # and objects with many subprocess calls.
1661 # and objects with many subprocess calls.
1662 tarstream = self._gitcommand(['archive', revision], stream=True)
1662 tarstream = self._gitcommand(['archive', revision], stream=True)
1663 tar = tarfile.open(fileobj=tarstream, mode=r'r|')
1663 tar = tarfile.open(fileobj=tarstream, mode=r'r|')
1664 relpath = subrelpath(self)
1664 relpath = subrelpath(self)
1665 progress = self.ui.makeprogress(_('archiving (%s)') % relpath,
1665 progress = self.ui.makeprogress(_('archiving (%s)') % relpath,
1666 unit=_('files'))
1666 unit=_('files'))
1667 progress.update(0)
1667 progress.update(0)
1668 for info in tar:
1668 for info in tar:
1669 if info.isdir():
1669 if info.isdir():
1670 continue
1670 continue
1671 bname = pycompat.fsencode(info.name)
1671 bname = pycompat.fsencode(info.name)
1672 if match and not match(bname):
1672 if match and not match(bname):
1673 continue
1673 continue
1674 if info.issym():
1674 if info.issym():
1675 data = info.linkname
1675 data = info.linkname
1676 else:
1676 else:
1677 data = tar.extractfile(info).read()
1677 data = tar.extractfile(info).read()
1678 archiver.addfile(prefix + bname, info.mode, info.issym(), data)
1678 archiver.addfile(prefix + bname, info.mode, info.issym(), data)
1679 total += 1
1679 total += 1
1680 progress.increment()
1680 progress.increment()
1681 progress.complete()
1681 progress.complete()
1682 return total
1682 return total
1683
1683
1684
1684
1685 @annotatesubrepoerror
1685 @annotatesubrepoerror
1686 def cat(self, match, fm, fntemplate, prefix, **opts):
1686 def cat(self, match, fm, fntemplate, prefix, **opts):
1687 rev = self._state[1]
1687 rev = self._state[1]
1688 if match.anypats():
1688 if match.anypats():
1689 return 1 #No support for include/exclude yet
1689 return 1 #No support for include/exclude yet
1690
1690
1691 if not match.files():
1691 if not match.files():
1692 return 1
1692 return 1
1693
1693
1694 # TODO: add support for non-plain formatter (see cmdutil.cat())
1694 # TODO: add support for non-plain formatter (see cmdutil.cat())
1695 for f in match.files():
1695 for f in match.files():
1696 output = self._gitcommand(["show", "%s:%s" % (rev, f)])
1696 output = self._gitcommand(["show", "%s:%s" % (rev, f)])
1697 fp = cmdutil.makefileobj(self._ctx, fntemplate,
1697 fp = cmdutil.makefileobj(self._ctx, fntemplate,
1698 pathname=self.wvfs.reljoin(prefix, f))
1698 pathname=self.wvfs.reljoin(prefix, f))
1699 fp.write(output)
1699 fp.write(output)
1700 fp.close()
1700 fp.close()
1701 return 0
1701 return 0
1702
1702
1703
1703
1704 @annotatesubrepoerror
1704 @annotatesubrepoerror
1705 def status(self, rev2, **opts):
1705 def status(self, rev2, **opts):
1706 rev1 = self._state[1]
1706 rev1 = self._state[1]
1707 if self._gitmissing() or not rev1:
1707 if self._gitmissing() or not rev1:
1708 # if the repo is missing, return no results
1708 # if the repo is missing, return no results
1709 return scmutil.status([], [], [], [], [], [], [])
1709 return scmutil.status([], [], [], [], [], [], [])
1710 modified, added, removed = [], [], []
1710 modified, added, removed = [], [], []
1711 self._gitupdatestat()
1711 self._gitupdatestat()
1712 if rev2:
1712 if rev2:
1713 command = ['diff-tree', '--no-renames', '-r', rev1, rev2]
1713 command = ['diff-tree', '--no-renames', '-r', rev1, rev2]
1714 else:
1714 else:
1715 command = ['diff-index', '--no-renames', rev1]
1715 command = ['diff-index', '--no-renames', rev1]
1716 out = self._gitcommand(command)
1716 out = self._gitcommand(command)
1717 for line in out.split('\n'):
1717 for line in out.split('\n'):
1718 tab = line.find('\t')
1718 tab = line.find('\t')
1719 if tab == -1:
1719 if tab == -1:
1720 continue
1720 continue
1721 status, f = line[tab - 1:tab], line[tab + 1:]
1721 status, f = line[tab - 1:tab], line[tab + 1:]
1722 if status == 'M':
1722 if status == 'M':
1723 modified.append(f)
1723 modified.append(f)
1724 elif status == 'A':
1724 elif status == 'A':
1725 added.append(f)
1725 added.append(f)
1726 elif status == 'D':
1726 elif status == 'D':
1727 removed.append(f)
1727 removed.append(f)
1728
1728
1729 deleted, unknown, ignored, clean = [], [], [], []
1729 deleted, unknown, ignored, clean = [], [], [], []
1730
1730
1731 command = ['status', '--porcelain', '-z']
1731 command = ['status', '--porcelain', '-z']
1732 if opts.get(r'unknown'):
1732 if opts.get(r'unknown'):
1733 command += ['--untracked-files=all']
1733 command += ['--untracked-files=all']
1734 if opts.get(r'ignored'):
1734 if opts.get(r'ignored'):
1735 command += ['--ignored']
1735 command += ['--ignored']
1736 out = self._gitcommand(command)
1736 out = self._gitcommand(command)
1737
1737
1738 changedfiles = set()
1738 changedfiles = set()
1739 changedfiles.update(modified)
1739 changedfiles.update(modified)
1740 changedfiles.update(added)
1740 changedfiles.update(added)
1741 changedfiles.update(removed)
1741 changedfiles.update(removed)
1742 for line in out.split('\0'):
1742 for line in out.split('\0'):
1743 if not line:
1743 if not line:
1744 continue
1744 continue
1745 st = line[0:2]
1745 st = line[0:2]
1746 #moves and copies show 2 files on one line
1746 #moves and copies show 2 files on one line
1747 if line.find('\0') >= 0:
1747 if line.find('\0') >= 0:
1748 filename1, filename2 = line[3:].split('\0')
1748 filename1, filename2 = line[3:].split('\0')
1749 else:
1749 else:
1750 filename1 = line[3:]
1750 filename1 = line[3:]
1751 filename2 = None
1751 filename2 = None
1752
1752
1753 changedfiles.add(filename1)
1753 changedfiles.add(filename1)
1754 if filename2:
1754 if filename2:
1755 changedfiles.add(filename2)
1755 changedfiles.add(filename2)
1756
1756
1757 if st == '??':
1757 if st == '??':
1758 unknown.append(filename1)
1758 unknown.append(filename1)
1759 elif st == '!!':
1759 elif st == '!!':
1760 ignored.append(filename1)
1760 ignored.append(filename1)
1761
1761
1762 if opts.get(r'clean'):
1762 if opts.get(r'clean'):
1763 out = self._gitcommand(['ls-files'])
1763 out = self._gitcommand(['ls-files'])
1764 for f in out.split('\n'):
1764 for f in out.split('\n'):
1765 if not f in changedfiles:
1765 if not f in changedfiles:
1766 clean.append(f)
1766 clean.append(f)
1767
1767
1768 return scmutil.status(modified, added, removed, deleted,
1768 return scmutil.status(modified, added, removed, deleted,
1769 unknown, ignored, clean)
1769 unknown, ignored, clean)
1770
1770
1771 @annotatesubrepoerror
1771 @annotatesubrepoerror
1772 def diff(self, ui, diffopts, node2, match, prefix, **opts):
1772 def diff(self, ui, diffopts, node2, match, prefix, **opts):
1773 node1 = self._state[1]
1773 node1 = self._state[1]
1774 cmd = ['diff', '--no-renames']
1774 cmd = ['diff', '--no-renames']
1775 if opts[r'stat']:
1775 if opts[r'stat']:
1776 cmd.append('--stat')
1776 cmd.append('--stat')
1777 else:
1777 else:
1778 # for Git, this also implies '-p'
1778 # for Git, this also implies '-p'
1779 cmd.append('-U%d' % diffopts.context)
1779 cmd.append('-U%d' % diffopts.context)
1780
1780
1781 if diffopts.noprefix:
1781 if diffopts.noprefix:
1782 cmd.extend(['--src-prefix=%s/' % prefix,
1782 cmd.extend(['--src-prefix=%s/' % prefix,
1783 '--dst-prefix=%s/' % prefix])
1783 '--dst-prefix=%s/' % prefix])
1784 else:
1784 else:
1785 cmd.extend(['--src-prefix=a/%s/' % prefix,
1785 cmd.extend(['--src-prefix=a/%s/' % prefix,
1786 '--dst-prefix=b/%s/' % prefix])
1786 '--dst-prefix=b/%s/' % prefix])
1787
1787
1788 if diffopts.ignorews:
1788 if diffopts.ignorews:
1789 cmd.append('--ignore-all-space')
1789 cmd.append('--ignore-all-space')
1790 if diffopts.ignorewsamount:
1790 if diffopts.ignorewsamount:
1791 cmd.append('--ignore-space-change')
1791 cmd.append('--ignore-space-change')
1792 if self._gitversion(self._gitcommand(['--version'])) >= (1, 8, 4) \
1792 if self._gitversion(self._gitcommand(['--version'])) >= (1, 8, 4) \
1793 and diffopts.ignoreblanklines:
1793 and diffopts.ignoreblanklines:
1794 cmd.append('--ignore-blank-lines')
1794 cmd.append('--ignore-blank-lines')
1795
1795
1796 cmd.append(node1)
1796 cmd.append(node1)
1797 if node2:
1797 if node2:
1798 cmd.append(node2)
1798 cmd.append(node2)
1799
1799
1800 output = ""
1800 output = ""
1801 if match.always():
1801 if match.always():
1802 output += self._gitcommand(cmd) + '\n'
1802 output += self._gitcommand(cmd) + '\n'
1803 else:
1803 else:
1804 st = self.status(node2)[:3]
1804 st = self.status(node2)[:3]
1805 files = [f for sublist in st for f in sublist]
1805 files = [f for sublist in st for f in sublist]
1806 for f in files:
1806 for f in files:
1807 if match(f):
1807 if match(f):
1808 output += self._gitcommand(cmd + ['--', f]) + '\n'
1808 output += self._gitcommand(cmd + ['--', f]) + '\n'
1809
1809
1810 if output.strip():
1810 if output.strip():
1811 ui.write(output)
1811 ui.write(output)
1812
1812
1813 @annotatesubrepoerror
1813 @annotatesubrepoerror
1814 def revert(self, substate, *pats, **opts):
1814 def revert(self, substate, *pats, **opts):
1815 self.ui.status(_('reverting subrepo %s\n') % substate[0])
1815 self.ui.status(_('reverting subrepo %s\n') % substate[0])
1816 if not opts.get(r'no_backup'):
1816 if not opts.get(r'no_backup'):
1817 status = self.status(None)
1817 status = self.status(None)
1818 names = status.modified
1818 names = status.modified
1819 for name in names:
1819 for name in names:
1820 # backuppath() expects a path relative to the parent repo (the
1820 # backuppath() expects a path relative to the parent repo (the
1821 # repo that ui.origbackuppath is relative to)
1821 # repo that ui.origbackuppath is relative to)
1822 parentname = os.path.join(self._path, name)
1822 parentname = os.path.join(self._path, name)
1823 bakname = scmutil.backuppath(self.ui, self._subparent,
1823 bakname = scmutil.backuppath(self.ui, self._subparent,
1824 parentname)
1824 parentname)
1825 self.ui.note(_('saving current version of %s as %s\n') %
1825 self.ui.note(_('saving current version of %s as %s\n') %
1826 (name, os.path.relpath(bakname)))
1826 (name, os.path.relpath(bakname)))
1827 util.rename(self.wvfs.join(name), bakname)
1827 util.rename(self.wvfs.join(name), bakname)
1828
1828
1829 if not opts.get(r'dry_run'):
1829 if not opts.get(r'dry_run'):
1830 self.get(substate, overwrite=True)
1830 self.get(substate, overwrite=True)
1831 return []
1831 return []
1832
1832
1833 def shortid(self, revid):
1833 def shortid(self, revid):
1834 return revid[:7]
1834 return revid[:7]
1835
1835
1836 types = {
1836 types = {
1837 'hg': hgsubrepo,
1837 'hg': hgsubrepo,
1838 'svn': svnsubrepo,
1838 'svn': svnsubrepo,
1839 'git': gitsubrepo,
1839 'git': gitsubrepo,
1840 }
1840 }
General Comments 0
You need to be logged in to leave comments. Login now