##// END OF EJS Templates
documentation: add an extra newline after note directive...
Simon Heimberg -
r19997:de16c673 stable
parent child Browse files
Show More
@@ -1,349 +1,350 b''
1 1 """automatically manage newlines in repository files
2 2
3 3 This extension allows you to manage the type of line endings (CRLF or
4 4 LF) that are used in the repository and in the local working
5 5 directory. That way you can get CRLF line endings on Windows and LF on
6 6 Unix/Mac, thereby letting everybody use their OS native line endings.
7 7
8 8 The extension reads its configuration from a versioned ``.hgeol``
9 9 configuration file found in the root of the working copy. The
10 10 ``.hgeol`` file use the same syntax as all other Mercurial
11 11 configuration files. It uses two sections, ``[patterns]`` and
12 12 ``[repository]``.
13 13
14 14 The ``[patterns]`` section specifies how line endings should be
15 15 converted between the working copy and the repository. The format is
16 16 specified by a file pattern. The first match is used, so put more
17 17 specific patterns first. The available line endings are ``LF``,
18 18 ``CRLF``, and ``BIN``.
19 19
20 20 Files with the declared format of ``CRLF`` or ``LF`` are always
21 21 checked out and stored in the repository in that format and files
22 22 declared to be binary (``BIN``) are left unchanged. Additionally,
23 23 ``native`` is an alias for checking out in the platform's default line
24 24 ending: ``LF`` on Unix (including Mac OS X) and ``CRLF`` on
25 25 Windows. Note that ``BIN`` (do nothing to line endings) is Mercurial's
26 26 default behaviour; it is only needed if you need to override a later,
27 27 more general pattern.
28 28
29 29 The optional ``[repository]`` section specifies the line endings to
30 30 use for files stored in the repository. It has a single setting,
31 31 ``native``, which determines the storage line endings for files
32 32 declared as ``native`` in the ``[patterns]`` section. It can be set to
33 33 ``LF`` or ``CRLF``. The default is ``LF``. For example, this means
34 34 that on Windows, files configured as ``native`` (``CRLF`` by default)
35 35 will be converted to ``LF`` when stored in the repository. Files
36 36 declared as ``LF``, ``CRLF``, or ``BIN`` in the ``[patterns]`` section
37 37 are always stored as-is in the repository.
38 38
39 39 Example versioned ``.hgeol`` file::
40 40
41 41 [patterns]
42 42 **.py = native
43 43 **.vcproj = CRLF
44 44 **.txt = native
45 45 Makefile = LF
46 46 **.jpg = BIN
47 47
48 48 [repository]
49 49 native = LF
50 50
51 51 .. note::
52
52 53 The rules will first apply when files are touched in the working
53 54 copy, e.g. by updating to null and back to tip to touch all files.
54 55
55 56 The extension uses an optional ``[eol]`` section read from both the
56 57 normal Mercurial configuration files and the ``.hgeol`` file, with the
57 58 latter overriding the former. You can use that section to control the
58 59 overall behavior. There are three settings:
59 60
60 61 - ``eol.native`` (default ``os.linesep``) can be set to ``LF`` or
61 62 ``CRLF`` to override the default interpretation of ``native`` for
62 63 checkout. This can be used with :hg:`archive` on Unix, say, to
63 64 generate an archive where files have line endings for Windows.
64 65
65 66 - ``eol.only-consistent`` (default True) can be set to False to make
66 67 the extension convert files with inconsistent EOLs. Inconsistent
67 68 means that there is both ``CRLF`` and ``LF`` present in the file.
68 69 Such files are normally not touched under the assumption that they
69 70 have mixed EOLs on purpose.
70 71
71 72 - ``eol.fix-trailing-newline`` (default False) can be set to True to
72 73 ensure that converted files end with a EOL character (either ``\\n``
73 74 or ``\\r\\n`` as per the configured patterns).
74 75
75 76 The extension provides ``cleverencode:`` and ``cleverdecode:`` filters
76 77 like the deprecated win32text extension does. This means that you can
77 78 disable win32text and enable eol and your filters will still work. You
78 79 only need to these filters until you have prepared a ``.hgeol`` file.
79 80
80 81 The ``win32text.forbid*`` hooks provided by the win32text extension
81 82 have been unified into a single hook named ``eol.checkheadshook``. The
82 83 hook will lookup the expected line endings from the ``.hgeol`` file,
83 84 which means you must migrate to a ``.hgeol`` file first before using
84 85 the hook. ``eol.checkheadshook`` only checks heads, intermediate
85 86 invalid revisions will be pushed. To forbid them completely, use the
86 87 ``eol.checkallhook`` hook. These hooks are best used as
87 88 ``pretxnchangegroup`` hooks.
88 89
89 90 See :hg:`help patterns` for more information about the glob patterns
90 91 used.
91 92 """
92 93
93 94 from mercurial.i18n import _
94 95 from mercurial import util, config, extensions, match, error
95 96 import re, os
96 97
97 98 testedwith = 'internal'
98 99
99 100 # Matches a lone LF, i.e., one that is not part of CRLF.
100 101 singlelf = re.compile('(^|[^\r])\n')
101 102 # Matches a single EOL which can either be a CRLF where repeated CR
102 103 # are removed or a LF. We do not care about old Macintosh files, so a
103 104 # stray CR is an error.
104 105 eolre = re.compile('\r*\n')
105 106
106 107
107 108 def inconsistenteol(data):
108 109 return '\r\n' in data and singlelf.search(data)
109 110
110 111 def tolf(s, params, ui, **kwargs):
111 112 """Filter to convert to LF EOLs."""
112 113 if util.binary(s):
113 114 return s
114 115 if ui.configbool('eol', 'only-consistent', True) and inconsistenteol(s):
115 116 return s
116 117 if (ui.configbool('eol', 'fix-trailing-newline', False)
117 118 and s and s[-1] != '\n'):
118 119 s = s + '\n'
119 120 return eolre.sub('\n', s)
120 121
121 122 def tocrlf(s, params, ui, **kwargs):
122 123 """Filter to convert to CRLF EOLs."""
123 124 if util.binary(s):
124 125 return s
125 126 if ui.configbool('eol', 'only-consistent', True) and inconsistenteol(s):
126 127 return s
127 128 if (ui.configbool('eol', 'fix-trailing-newline', False)
128 129 and s and s[-1] != '\n'):
129 130 s = s + '\n'
130 131 return eolre.sub('\r\n', s)
131 132
132 133 def isbinary(s, params):
133 134 """Filter to do nothing with the file."""
134 135 return s
135 136
136 137 filters = {
137 138 'to-lf': tolf,
138 139 'to-crlf': tocrlf,
139 140 'is-binary': isbinary,
140 141 # The following provide backwards compatibility with win32text
141 142 'cleverencode:': tolf,
142 143 'cleverdecode:': tocrlf
143 144 }
144 145
145 146 class eolfile(object):
146 147 def __init__(self, ui, root, data):
147 148 self._decode = {'LF': 'to-lf', 'CRLF': 'to-crlf', 'BIN': 'is-binary'}
148 149 self._encode = {'LF': 'to-lf', 'CRLF': 'to-crlf', 'BIN': 'is-binary'}
149 150
150 151 self.cfg = config.config()
151 152 # Our files should not be touched. The pattern must be
152 153 # inserted first override a '** = native' pattern.
153 154 self.cfg.set('patterns', '.hg*', 'BIN')
154 155 # We can then parse the user's patterns.
155 156 self.cfg.parse('.hgeol', data)
156 157
157 158 isrepolf = self.cfg.get('repository', 'native') != 'CRLF'
158 159 self._encode['NATIVE'] = isrepolf and 'to-lf' or 'to-crlf'
159 160 iswdlf = ui.config('eol', 'native', os.linesep) in ('LF', '\n')
160 161 self._decode['NATIVE'] = iswdlf and 'to-lf' or 'to-crlf'
161 162
162 163 include = []
163 164 exclude = []
164 165 for pattern, style in self.cfg.items('patterns'):
165 166 key = style.upper()
166 167 if key == 'BIN':
167 168 exclude.append(pattern)
168 169 else:
169 170 include.append(pattern)
170 171 # This will match the files for which we need to care
171 172 # about inconsistent newlines.
172 173 self.match = match.match(root, '', [], include, exclude)
173 174
174 175 def copytoui(self, ui):
175 176 for pattern, style in self.cfg.items('patterns'):
176 177 key = style.upper()
177 178 try:
178 179 ui.setconfig('decode', pattern, self._decode[key])
179 180 ui.setconfig('encode', pattern, self._encode[key])
180 181 except KeyError:
181 182 ui.warn(_("ignoring unknown EOL style '%s' from %s\n")
182 183 % (style, self.cfg.source('patterns', pattern)))
183 184 # eol.only-consistent can be specified in ~/.hgrc or .hgeol
184 185 for k, v in self.cfg.items('eol'):
185 186 ui.setconfig('eol', k, v)
186 187
187 188 def checkrev(self, repo, ctx, files):
188 189 failed = []
189 190 for f in (files or ctx.files()):
190 191 if f not in ctx:
191 192 continue
192 193 for pattern, style in self.cfg.items('patterns'):
193 194 if not match.match(repo.root, '', [pattern])(f):
194 195 continue
195 196 target = self._encode[style.upper()]
196 197 data = ctx[f].data()
197 198 if (target == "to-lf" and "\r\n" in data
198 199 or target == "to-crlf" and singlelf.search(data)):
199 200 failed.append((str(ctx), target, f))
200 201 break
201 202 return failed
202 203
203 204 def parseeol(ui, repo, nodes):
204 205 try:
205 206 for node in nodes:
206 207 try:
207 208 if node is None:
208 209 # Cannot use workingctx.data() since it would load
209 210 # and cache the filters before we configure them.
210 211 data = repo.wfile('.hgeol').read()
211 212 else:
212 213 data = repo[node]['.hgeol'].data()
213 214 return eolfile(ui, repo.root, data)
214 215 except (IOError, LookupError):
215 216 pass
216 217 except error.ParseError, inst:
217 218 ui.warn(_("warning: ignoring .hgeol file due to parse error "
218 219 "at %s: %s\n") % (inst.args[1], inst.args[0]))
219 220 return None
220 221
221 222 def _checkhook(ui, repo, node, headsonly):
222 223 # Get revisions to check and touched files at the same time
223 224 files = set()
224 225 revs = set()
225 226 for rev in xrange(repo[node].rev(), len(repo)):
226 227 revs.add(rev)
227 228 if headsonly:
228 229 ctx = repo[rev]
229 230 files.update(ctx.files())
230 231 for pctx in ctx.parents():
231 232 revs.discard(pctx.rev())
232 233 failed = []
233 234 for rev in revs:
234 235 ctx = repo[rev]
235 236 eol = parseeol(ui, repo, [ctx.node()])
236 237 if eol:
237 238 failed.extend(eol.checkrev(repo, ctx, files))
238 239
239 240 if failed:
240 241 eols = {'to-lf': 'CRLF', 'to-crlf': 'LF'}
241 242 msgs = []
242 243 for node, target, f in failed:
243 244 msgs.append(_(" %s in %s should not have %s line endings") %
244 245 (f, node, eols[target]))
245 246 raise util.Abort(_("end-of-line check failed:\n") + "\n".join(msgs))
246 247
247 248 def checkallhook(ui, repo, node, hooktype, **kwargs):
248 249 """verify that files have expected EOLs"""
249 250 _checkhook(ui, repo, node, False)
250 251
251 252 def checkheadshook(ui, repo, node, hooktype, **kwargs):
252 253 """verify that files have expected EOLs"""
253 254 _checkhook(ui, repo, node, True)
254 255
255 256 # "checkheadshook" used to be called "hook"
256 257 hook = checkheadshook
257 258
258 259 def preupdate(ui, repo, hooktype, parent1, parent2):
259 260 repo.loadeol([parent1])
260 261 return False
261 262
262 263 def uisetup(ui):
263 264 ui.setconfig('hooks', 'preupdate.eol', preupdate)
264 265
265 266 def extsetup(ui):
266 267 try:
267 268 extensions.find('win32text')
268 269 ui.warn(_("the eol extension is incompatible with the "
269 270 "win32text extension\n"))
270 271 except KeyError:
271 272 pass
272 273
273 274
274 275 def reposetup(ui, repo):
275 276 uisetup(repo.ui)
276 277
277 278 if not repo.local():
278 279 return
279 280 for name, fn in filters.iteritems():
280 281 repo.adddatafilter(name, fn)
281 282
282 283 ui.setconfig('patch', 'eol', 'auto')
283 284
284 285 class eolrepo(repo.__class__):
285 286
286 287 def loadeol(self, nodes):
287 288 eol = parseeol(self.ui, self, nodes)
288 289 if eol is None:
289 290 return None
290 291 eol.copytoui(self.ui)
291 292 return eol.match
292 293
293 294 def _hgcleardirstate(self):
294 295 self._eolfile = self.loadeol([None, 'tip'])
295 296 if not self._eolfile:
296 297 self._eolfile = util.never
297 298 return
298 299
299 300 try:
300 301 cachemtime = os.path.getmtime(self.join("eol.cache"))
301 302 except OSError:
302 303 cachemtime = 0
303 304
304 305 try:
305 306 eolmtime = os.path.getmtime(self.wjoin(".hgeol"))
306 307 except OSError:
307 308 eolmtime = 0
308 309
309 310 if eolmtime > cachemtime:
310 311 self.ui.debug("eol: detected change in .hgeol\n")
311 312 wlock = None
312 313 try:
313 314 wlock = self.wlock()
314 315 for f in self.dirstate:
315 316 if self.dirstate[f] == 'n':
316 317 # all normal files need to be looked at
317 318 # again since the new .hgeol file might no
318 319 # longer match a file it matched before
319 320 self.dirstate.normallookup(f)
320 321 # Create or touch the cache to update mtime
321 322 self.opener("eol.cache", "w").close()
322 323 wlock.release()
323 324 except error.LockUnavailable:
324 325 # If we cannot lock the repository and clear the
325 326 # dirstate, then a commit might not see all files
326 327 # as modified. But if we cannot lock the
327 328 # repository, then we can also not make a commit,
328 329 # so ignore the error.
329 330 pass
330 331
331 332 def commitctx(self, ctx, error=False):
332 333 for f in sorted(ctx.added() + ctx.modified()):
333 334 if not self._eolfile(f):
334 335 continue
335 336 try:
336 337 data = ctx[f].data()
337 338 except IOError:
338 339 continue
339 340 if util.binary(data):
340 341 # We should not abort here, since the user should
341 342 # be able to say "** = native" to automatically
342 343 # have all non-binary files taken care of.
343 344 continue
344 345 if inconsistenteol(data):
345 346 raise util.Abort(_("inconsistent newline style "
346 347 "in %s\n" % f))
347 348 return super(eolrepo, self).commitctx(ctx, error)
348 349 repo.__class__ = eolrepo
349 350 repo._hgcleardirstate()
@@ -1,731 +1,732 b''
1 1 # keyword.py - $Keyword$ expansion for Mercurial
2 2 #
3 3 # Copyright 2007-2012 Christian Ebert <blacktrash@gmx.net>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7 #
8 8 # $Id$
9 9 #
10 10 # Keyword expansion hack against the grain of a Distributed SCM
11 11 #
12 12 # There are many good reasons why this is not needed in a distributed
13 13 # SCM, still it may be useful in very small projects based on single
14 14 # files (like LaTeX packages), that are mostly addressed to an
15 15 # audience not running a version control system.
16 16 #
17 17 # For in-depth discussion refer to
18 18 # <http://mercurial.selenic.com/wiki/KeywordPlan>.
19 19 #
20 20 # Keyword expansion is based on Mercurial's changeset template mappings.
21 21 #
22 22 # Binary files are not touched.
23 23 #
24 24 # Files to act upon/ignore are specified in the [keyword] section.
25 25 # Customized keyword template mappings in the [keywordmaps] section.
26 26 #
27 27 # Run "hg help keyword" and "hg kwdemo" to get info on configuration.
28 28
29 29 '''expand keywords in tracked files
30 30
31 31 This extension expands RCS/CVS-like or self-customized $Keywords$ in
32 32 tracked text files selected by your configuration.
33 33
34 34 Keywords are only expanded in local repositories and not stored in the
35 35 change history. The mechanism can be regarded as a convenience for the
36 36 current user or for archive distribution.
37 37
38 38 Keywords expand to the changeset data pertaining to the latest change
39 39 relative to the working directory parent of each file.
40 40
41 41 Configuration is done in the [keyword], [keywordset] and [keywordmaps]
42 42 sections of hgrc files.
43 43
44 44 Example::
45 45
46 46 [keyword]
47 47 # expand keywords in every python file except those matching "x*"
48 48 **.py =
49 49 x* = ignore
50 50
51 51 [keywordset]
52 52 # prefer svn- over cvs-like default keywordmaps
53 53 svn = True
54 54
55 55 .. note::
56
56 57 The more specific you are in your filename patterns the less you
57 58 lose speed in huge repositories.
58 59
59 60 For [keywordmaps] template mapping and expansion demonstration and
60 61 control run :hg:`kwdemo`. See :hg:`help templates` for a list of
61 62 available templates and filters.
62 63
63 64 Three additional date template filters are provided:
64 65
65 66 :``utcdate``: "2006/09/18 15:13:13"
66 67 :``svnutcdate``: "2006-09-18 15:13:13Z"
67 68 :``svnisodate``: "2006-09-18 08:13:13 -700 (Mon, 18 Sep 2006)"
68 69
69 70 The default template mappings (view with :hg:`kwdemo -d`) can be
70 71 replaced with customized keywords and templates. Again, run
71 72 :hg:`kwdemo` to control the results of your configuration changes.
72 73
73 74 Before changing/disabling active keywords, you must run :hg:`kwshrink`
74 75 to avoid storing expanded keywords in the change history.
75 76
76 77 To force expansion after enabling it, or a configuration change, run
77 78 :hg:`kwexpand`.
78 79
79 80 Expansions spanning more than one line and incremental expansions,
80 81 like CVS' $Log$, are not supported. A keyword template map "Log =
81 82 {desc}" expands to the first line of the changeset description.
82 83 '''
83 84
84 85 from mercurial import commands, context, cmdutil, dispatch, filelog, extensions
85 86 from mercurial import localrepo, match, patch, templatefilters, templater, util
86 87 from mercurial import scmutil
87 88 from mercurial.hgweb import webcommands
88 89 from mercurial.i18n import _
89 90 import os, re, shutil, tempfile
90 91
91 92 commands.optionalrepo += ' kwdemo'
92 93 commands.inferrepo += ' kwexpand kwfiles kwshrink'
93 94
94 95 cmdtable = {}
95 96 command = cmdutil.command(cmdtable)
96 97 testedwith = 'internal'
97 98
98 99 # hg commands that do not act on keywords
99 100 nokwcommands = ('add addremove annotate bundle export grep incoming init log'
100 101 ' outgoing push tip verify convert email glog')
101 102
102 103 # hg commands that trigger expansion only when writing to working dir,
103 104 # not when reading filelog, and unexpand when reading from working dir
104 105 restricted = 'merge kwexpand kwshrink record qrecord resolve transplant'
105 106
106 107 # names of extensions using dorecord
107 108 recordextensions = 'record'
108 109
109 110 colortable = {
110 111 'kwfiles.enabled': 'green bold',
111 112 'kwfiles.deleted': 'cyan bold underline',
112 113 'kwfiles.enabledunknown': 'green',
113 114 'kwfiles.ignored': 'bold',
114 115 'kwfiles.ignoredunknown': 'none'
115 116 }
116 117
117 118 # date like in cvs' $Date
118 119 def utcdate(text):
119 120 ''':utcdate: Date. Returns a UTC-date in this format: "2009/08/18 11:00:13".
120 121 '''
121 122 return util.datestr((util.parsedate(text)[0], 0), '%Y/%m/%d %H:%M:%S')
122 123 # date like in svn's $Date
123 124 def svnisodate(text):
124 125 ''':svnisodate: Date. Returns a date in this format: "2009-08-18 13:00:13
125 126 +0200 (Tue, 18 Aug 2009)".
126 127 '''
127 128 return util.datestr(text, '%Y-%m-%d %H:%M:%S %1%2 (%a, %d %b %Y)')
128 129 # date like in svn's $Id
129 130 def svnutcdate(text):
130 131 ''':svnutcdate: Date. Returns a UTC-date in this format: "2009-08-18
131 132 11:00:13Z".
132 133 '''
133 134 return util.datestr((util.parsedate(text)[0], 0), '%Y-%m-%d %H:%M:%SZ')
134 135
135 136 templatefilters.filters.update({'utcdate': utcdate,
136 137 'svnisodate': svnisodate,
137 138 'svnutcdate': svnutcdate})
138 139
139 140 # make keyword tools accessible
140 141 kwtools = {'templater': None, 'hgcmd': ''}
141 142
142 143 def _defaultkwmaps(ui):
143 144 '''Returns default keywordmaps according to keywordset configuration.'''
144 145 templates = {
145 146 'Revision': '{node|short}',
146 147 'Author': '{author|user}',
147 148 }
148 149 kwsets = ({
149 150 'Date': '{date|utcdate}',
150 151 'RCSfile': '{file|basename},v',
151 152 'RCSFile': '{file|basename},v', # kept for backwards compatibility
152 153 # with hg-keyword
153 154 'Source': '{root}/{file},v',
154 155 'Id': '{file|basename},v {node|short} {date|utcdate} {author|user}',
155 156 'Header': '{root}/{file},v {node|short} {date|utcdate} {author|user}',
156 157 }, {
157 158 'Date': '{date|svnisodate}',
158 159 'Id': '{file|basename},v {node|short} {date|svnutcdate} {author|user}',
159 160 'LastChangedRevision': '{node|short}',
160 161 'LastChangedBy': '{author|user}',
161 162 'LastChangedDate': '{date|svnisodate}',
162 163 })
163 164 templates.update(kwsets[ui.configbool('keywordset', 'svn')])
164 165 return templates
165 166
166 167 def _shrinktext(text, subfunc):
167 168 '''Helper for keyword expansion removal in text.
168 169 Depending on subfunc also returns number of substitutions.'''
169 170 return subfunc(r'$\1$', text)
170 171
171 172 def _preselect(wstatus, changed):
172 173 '''Retrieves modified and added files from a working directory state
173 174 and returns the subset of each contained in given changed files
174 175 retrieved from a change context.'''
175 176 modified, added = wstatus[:2]
176 177 modified = [f for f in modified if f in changed]
177 178 added = [f for f in added if f in changed]
178 179 return modified, added
179 180
180 181
181 182 class kwtemplater(object):
182 183 '''
183 184 Sets up keyword templates, corresponding keyword regex, and
184 185 provides keyword substitution functions.
185 186 '''
186 187
187 188 def __init__(self, ui, repo, inc, exc):
188 189 self.ui = ui
189 190 self.repo = repo
190 191 self.match = match.match(repo.root, '', [], inc, exc)
191 192 self.restrict = kwtools['hgcmd'] in restricted.split()
192 193 self.postcommit = False
193 194
194 195 kwmaps = self.ui.configitems('keywordmaps')
195 196 if kwmaps: # override default templates
196 197 self.templates = dict((k, templater.parsestring(v, False))
197 198 for k, v in kwmaps)
198 199 else:
199 200 self.templates = _defaultkwmaps(self.ui)
200 201
201 202 @util.propertycache
202 203 def escape(self):
203 204 '''Returns bar-separated and escaped keywords.'''
204 205 return '|'.join(map(re.escape, self.templates.keys()))
205 206
206 207 @util.propertycache
207 208 def rekw(self):
208 209 '''Returns regex for unexpanded keywords.'''
209 210 return re.compile(r'\$(%s)\$' % self.escape)
210 211
211 212 @util.propertycache
212 213 def rekwexp(self):
213 214 '''Returns regex for expanded keywords.'''
214 215 return re.compile(r'\$(%s): [^$\n\r]*? \$' % self.escape)
215 216
216 217 def substitute(self, data, path, ctx, subfunc):
217 218 '''Replaces keywords in data with expanded template.'''
218 219 def kwsub(mobj):
219 220 kw = mobj.group(1)
220 221 ct = cmdutil.changeset_templater(self.ui, self.repo,
221 222 False, None, '', False)
222 223 ct.use_template(self.templates[kw])
223 224 self.ui.pushbuffer()
224 225 ct.show(ctx, root=self.repo.root, file=path)
225 226 ekw = templatefilters.firstline(self.ui.popbuffer())
226 227 return '$%s: %s $' % (kw, ekw)
227 228 return subfunc(kwsub, data)
228 229
229 230 def linkctx(self, path, fileid):
230 231 '''Similar to filelog.linkrev, but returns a changectx.'''
231 232 return self.repo.filectx(path, fileid=fileid).changectx()
232 233
233 234 def expand(self, path, node, data):
234 235 '''Returns data with keywords expanded.'''
235 236 if not self.restrict and self.match(path) and not util.binary(data):
236 237 ctx = self.linkctx(path, node)
237 238 return self.substitute(data, path, ctx, self.rekw.sub)
238 239 return data
239 240
240 241 def iskwfile(self, cand, ctx):
241 242 '''Returns subset of candidates which are configured for keyword
242 243 expansion but are not symbolic links.'''
243 244 return [f for f in cand if self.match(f) and 'l' not in ctx.flags(f)]
244 245
245 246 def overwrite(self, ctx, candidates, lookup, expand, rekw=False):
246 247 '''Overwrites selected files expanding/shrinking keywords.'''
247 248 if self.restrict or lookup or self.postcommit: # exclude kw_copy
248 249 candidates = self.iskwfile(candidates, ctx)
249 250 if not candidates:
250 251 return
251 252 kwcmd = self.restrict and lookup # kwexpand/kwshrink
252 253 if self.restrict or expand and lookup:
253 254 mf = ctx.manifest()
254 255 if self.restrict or rekw:
255 256 re_kw = self.rekw
256 257 else:
257 258 re_kw = self.rekwexp
258 259 if expand:
259 260 msg = _('overwriting %s expanding keywords\n')
260 261 else:
261 262 msg = _('overwriting %s shrinking keywords\n')
262 263 for f in candidates:
263 264 if self.restrict:
264 265 data = self.repo.file(f).read(mf[f])
265 266 else:
266 267 data = self.repo.wread(f)
267 268 if util.binary(data):
268 269 continue
269 270 if expand:
270 271 if lookup:
271 272 ctx = self.linkctx(f, mf[f])
272 273 data, found = self.substitute(data, f, ctx, re_kw.subn)
273 274 elif self.restrict:
274 275 found = re_kw.search(data)
275 276 else:
276 277 data, found = _shrinktext(data, re_kw.subn)
277 278 if found:
278 279 self.ui.note(msg % f)
279 280 fp = self.repo.wopener(f, "wb", atomictemp=True)
280 281 fp.write(data)
281 282 fp.close()
282 283 if kwcmd:
283 284 self.repo.dirstate.normal(f)
284 285 elif self.postcommit:
285 286 self.repo.dirstate.normallookup(f)
286 287
287 288 def shrink(self, fname, text):
288 289 '''Returns text with all keyword substitutions removed.'''
289 290 if self.match(fname) and not util.binary(text):
290 291 return _shrinktext(text, self.rekwexp.sub)
291 292 return text
292 293
293 294 def shrinklines(self, fname, lines):
294 295 '''Returns lines with keyword substitutions removed.'''
295 296 if self.match(fname):
296 297 text = ''.join(lines)
297 298 if not util.binary(text):
298 299 return _shrinktext(text, self.rekwexp.sub).splitlines(True)
299 300 return lines
300 301
301 302 def wread(self, fname, data):
302 303 '''If in restricted mode returns data read from wdir with
303 304 keyword substitutions removed.'''
304 305 if self.restrict:
305 306 return self.shrink(fname, data)
306 307 return data
307 308
308 309 class kwfilelog(filelog.filelog):
309 310 '''
310 311 Subclass of filelog to hook into its read, add, cmp methods.
311 312 Keywords are "stored" unexpanded, and processed on reading.
312 313 '''
313 314 def __init__(self, opener, kwt, path):
314 315 super(kwfilelog, self).__init__(opener, path)
315 316 self.kwt = kwt
316 317 self.path = path
317 318
318 319 def read(self, node):
319 320 '''Expands keywords when reading filelog.'''
320 321 data = super(kwfilelog, self).read(node)
321 322 if self.renamed(node):
322 323 return data
323 324 return self.kwt.expand(self.path, node, data)
324 325
325 326 def add(self, text, meta, tr, link, p1=None, p2=None):
326 327 '''Removes keyword substitutions when adding to filelog.'''
327 328 text = self.kwt.shrink(self.path, text)
328 329 return super(kwfilelog, self).add(text, meta, tr, link, p1, p2)
329 330
330 331 def cmp(self, node, text):
331 332 '''Removes keyword substitutions for comparison.'''
332 333 text = self.kwt.shrink(self.path, text)
333 334 return super(kwfilelog, self).cmp(node, text)
334 335
335 336 def _status(ui, repo, wctx, kwt, *pats, **opts):
336 337 '''Bails out if [keyword] configuration is not active.
337 338 Returns status of working directory.'''
338 339 if kwt:
339 340 return repo.status(match=scmutil.match(wctx, pats, opts), clean=True,
340 341 unknown=opts.get('unknown') or opts.get('all'))
341 342 if ui.configitems('keyword'):
342 343 raise util.Abort(_('[keyword] patterns cannot match'))
343 344 raise util.Abort(_('no [keyword] patterns configured'))
344 345
345 346 def _kwfwrite(ui, repo, expand, *pats, **opts):
346 347 '''Selects files and passes them to kwtemplater.overwrite.'''
347 348 wctx = repo[None]
348 349 if len(wctx.parents()) > 1:
349 350 raise util.Abort(_('outstanding uncommitted merge'))
350 351 kwt = kwtools['templater']
351 352 wlock = repo.wlock()
352 353 try:
353 354 status = _status(ui, repo, wctx, kwt, *pats, **opts)
354 355 modified, added, removed, deleted, unknown, ignored, clean = status
355 356 if modified or added or removed or deleted:
356 357 raise util.Abort(_('outstanding uncommitted changes'))
357 358 kwt.overwrite(wctx, clean, True, expand)
358 359 finally:
359 360 wlock.release()
360 361
361 362 @command('kwdemo',
362 363 [('d', 'default', None, _('show default keyword template maps')),
363 364 ('f', 'rcfile', '',
364 365 _('read maps from rcfile'), _('FILE'))],
365 366 _('hg kwdemo [-d] [-f RCFILE] [TEMPLATEMAP]...'))
366 367 def demo(ui, repo, *args, **opts):
367 368 '''print [keywordmaps] configuration and an expansion example
368 369
369 370 Show current, custom, or default keyword template maps and their
370 371 expansions.
371 372
372 373 Extend the current configuration by specifying maps as arguments
373 374 and using -f/--rcfile to source an external hgrc file.
374 375
375 376 Use -d/--default to disable current configuration.
376 377
377 378 See :hg:`help templates` for information on templates and filters.
378 379 '''
379 380 def demoitems(section, items):
380 381 ui.write('[%s]\n' % section)
381 382 for k, v in sorted(items):
382 383 ui.write('%s = %s\n' % (k, v))
383 384
384 385 fn = 'demo.txt'
385 386 tmpdir = tempfile.mkdtemp('', 'kwdemo.')
386 387 ui.note(_('creating temporary repository at %s\n') % tmpdir)
387 388 repo = localrepo.localrepository(repo.baseui, tmpdir, True)
388 389 ui.setconfig('keyword', fn, '')
389 390 svn = ui.configbool('keywordset', 'svn')
390 391 # explicitly set keywordset for demo output
391 392 ui.setconfig('keywordset', 'svn', svn)
392 393
393 394 uikwmaps = ui.configitems('keywordmaps')
394 395 if args or opts.get('rcfile'):
395 396 ui.status(_('\n\tconfiguration using custom keyword template maps\n'))
396 397 if uikwmaps:
397 398 ui.status(_('\textending current template maps\n'))
398 399 if opts.get('default') or not uikwmaps:
399 400 if svn:
400 401 ui.status(_('\toverriding default svn keywordset\n'))
401 402 else:
402 403 ui.status(_('\toverriding default cvs keywordset\n'))
403 404 if opts.get('rcfile'):
404 405 ui.readconfig(opts.get('rcfile'))
405 406 if args:
406 407 # simulate hgrc parsing
407 408 rcmaps = ['[keywordmaps]\n'] + [a + '\n' for a in args]
408 409 fp = repo.opener('hgrc', 'w')
409 410 fp.writelines(rcmaps)
410 411 fp.close()
411 412 ui.readconfig(repo.join('hgrc'))
412 413 kwmaps = dict(ui.configitems('keywordmaps'))
413 414 elif opts.get('default'):
414 415 if svn:
415 416 ui.status(_('\n\tconfiguration using default svn keywordset\n'))
416 417 else:
417 418 ui.status(_('\n\tconfiguration using default cvs keywordset\n'))
418 419 kwmaps = _defaultkwmaps(ui)
419 420 if uikwmaps:
420 421 ui.status(_('\tdisabling current template maps\n'))
421 422 for k, v in kwmaps.iteritems():
422 423 ui.setconfig('keywordmaps', k, v)
423 424 else:
424 425 ui.status(_('\n\tconfiguration using current keyword template maps\n'))
425 426 if uikwmaps:
426 427 kwmaps = dict(uikwmaps)
427 428 else:
428 429 kwmaps = _defaultkwmaps(ui)
429 430
430 431 uisetup(ui)
431 432 reposetup(ui, repo)
432 433 ui.write('[extensions]\nkeyword =\n')
433 434 demoitems('keyword', ui.configitems('keyword'))
434 435 demoitems('keywordset', ui.configitems('keywordset'))
435 436 demoitems('keywordmaps', kwmaps.iteritems())
436 437 keywords = '$' + '$\n$'.join(sorted(kwmaps.keys())) + '$\n'
437 438 repo.wopener.write(fn, keywords)
438 439 repo[None].add([fn])
439 440 ui.note(_('\nkeywords written to %s:\n') % fn)
440 441 ui.note(keywords)
441 442 repo.dirstate.setbranch('demobranch')
442 443 for name, cmd in ui.configitems('hooks'):
443 444 if name.split('.', 1)[0].find('commit') > -1:
444 445 repo.ui.setconfig('hooks', name, '')
445 446 msg = _('hg keyword configuration and expansion example')
446 447 ui.note("hg ci -m '%s'\n" % msg) # check-code-ignore
447 448 repo.commit(text=msg)
448 449 ui.status(_('\n\tkeywords expanded\n'))
449 450 ui.write(repo.wread(fn))
450 451 shutil.rmtree(tmpdir, ignore_errors=True)
451 452
452 453 @command('kwexpand', commands.walkopts, _('hg kwexpand [OPTION]... [FILE]...'))
453 454 def expand(ui, repo, *pats, **opts):
454 455 '''expand keywords in the working directory
455 456
456 457 Run after (re)enabling keyword expansion.
457 458
458 459 kwexpand refuses to run if given files contain local changes.
459 460 '''
460 461 # 3rd argument sets expansion to True
461 462 _kwfwrite(ui, repo, True, *pats, **opts)
462 463
463 464 @command('kwfiles',
464 465 [('A', 'all', None, _('show keyword status flags of all files')),
465 466 ('i', 'ignore', None, _('show files excluded from expansion')),
466 467 ('u', 'unknown', None, _('only show unknown (not tracked) files')),
467 468 ] + commands.walkopts,
468 469 _('hg kwfiles [OPTION]... [FILE]...'))
469 470 def files(ui, repo, *pats, **opts):
470 471 '''show files configured for keyword expansion
471 472
472 473 List which files in the working directory are matched by the
473 474 [keyword] configuration patterns.
474 475
475 476 Useful to prevent inadvertent keyword expansion and to speed up
476 477 execution by including only files that are actual candidates for
477 478 expansion.
478 479
479 480 See :hg:`help keyword` on how to construct patterns both for
480 481 inclusion and exclusion of files.
481 482
482 483 With -A/--all and -v/--verbose the codes used to show the status
483 484 of files are::
484 485
485 486 K = keyword expansion candidate
486 487 k = keyword expansion candidate (not tracked)
487 488 I = ignored
488 489 i = ignored (not tracked)
489 490 '''
490 491 kwt = kwtools['templater']
491 492 wctx = repo[None]
492 493 status = _status(ui, repo, wctx, kwt, *pats, **opts)
493 494 cwd = pats and repo.getcwd() or ''
494 495 modified, added, removed, deleted, unknown, ignored, clean = status
495 496 files = []
496 497 if not opts.get('unknown') or opts.get('all'):
497 498 files = sorted(modified + added + clean)
498 499 kwfiles = kwt.iskwfile(files, wctx)
499 500 kwdeleted = kwt.iskwfile(deleted, wctx)
500 501 kwunknown = kwt.iskwfile(unknown, wctx)
501 502 if not opts.get('ignore') or opts.get('all'):
502 503 showfiles = kwfiles, kwdeleted, kwunknown
503 504 else:
504 505 showfiles = [], [], []
505 506 if opts.get('all') or opts.get('ignore'):
506 507 showfiles += ([f for f in files if f not in kwfiles],
507 508 [f for f in unknown if f not in kwunknown])
508 509 kwlabels = 'enabled deleted enabledunknown ignored ignoredunknown'.split()
509 510 kwstates = zip(kwlabels, 'K!kIi', showfiles)
510 511 fm = ui.formatter('kwfiles', opts)
511 512 fmt = '%.0s%s\n'
512 513 if opts.get('all') or ui.verbose:
513 514 fmt = '%s %s\n'
514 515 for kwstate, char, filenames in kwstates:
515 516 label = 'kwfiles.' + kwstate
516 517 for f in filenames:
517 518 fm.startitem()
518 519 fm.write('kwstatus path', fmt, char,
519 520 repo.pathto(f, cwd), label=label)
520 521 fm.end()
521 522
522 523 @command('kwshrink', commands.walkopts, _('hg kwshrink [OPTION]... [FILE]...'))
523 524 def shrink(ui, repo, *pats, **opts):
524 525 '''revert expanded keywords in the working directory
525 526
526 527 Must be run before changing/disabling active keywords.
527 528
528 529 kwshrink refuses to run if given files contain local changes.
529 530 '''
530 531 # 3rd argument sets expansion to False
531 532 _kwfwrite(ui, repo, False, *pats, **opts)
532 533
533 534
534 535 def uisetup(ui):
535 536 ''' Monkeypatches dispatch._parse to retrieve user command.'''
536 537
537 538 def kwdispatch_parse(orig, ui, args):
538 539 '''Monkeypatch dispatch._parse to obtain running hg command.'''
539 540 cmd, func, args, options, cmdoptions = orig(ui, args)
540 541 kwtools['hgcmd'] = cmd
541 542 return cmd, func, args, options, cmdoptions
542 543
543 544 extensions.wrapfunction(dispatch, '_parse', kwdispatch_parse)
544 545
545 546 def reposetup(ui, repo):
546 547 '''Sets up repo as kwrepo for keyword substitution.
547 548 Overrides file method to return kwfilelog instead of filelog
548 549 if file matches user configuration.
549 550 Wraps commit to overwrite configured files with updated
550 551 keyword substitutions.
551 552 Monkeypatches patch and webcommands.'''
552 553
553 554 try:
554 555 if (not repo.local() or kwtools['hgcmd'] in nokwcommands.split()
555 556 or '.hg' in util.splitpath(repo.root)
556 557 or repo._url.startswith('bundle:')):
557 558 return
558 559 except AttributeError:
559 560 pass
560 561
561 562 inc, exc = [], ['.hg*']
562 563 for pat, opt in ui.configitems('keyword'):
563 564 if opt != 'ignore':
564 565 inc.append(pat)
565 566 else:
566 567 exc.append(pat)
567 568 if not inc:
568 569 return
569 570
570 571 kwtools['templater'] = kwt = kwtemplater(ui, repo, inc, exc)
571 572
572 573 class kwrepo(repo.__class__):
573 574 def file(self, f):
574 575 if f[0] == '/':
575 576 f = f[1:]
576 577 return kwfilelog(self.sopener, kwt, f)
577 578
578 579 def wread(self, filename):
579 580 data = super(kwrepo, self).wread(filename)
580 581 return kwt.wread(filename, data)
581 582
582 583 def commit(self, *args, **opts):
583 584 # use custom commitctx for user commands
584 585 # other extensions can still wrap repo.commitctx directly
585 586 self.commitctx = self.kwcommitctx
586 587 try:
587 588 return super(kwrepo, self).commit(*args, **opts)
588 589 finally:
589 590 del self.commitctx
590 591
591 592 def kwcommitctx(self, ctx, error=False):
592 593 n = super(kwrepo, self).commitctx(ctx, error)
593 594 # no lock needed, only called from repo.commit() which already locks
594 595 if not kwt.postcommit:
595 596 restrict = kwt.restrict
596 597 kwt.restrict = True
597 598 kwt.overwrite(self[n], sorted(ctx.added() + ctx.modified()),
598 599 False, True)
599 600 kwt.restrict = restrict
600 601 return n
601 602
602 603 def rollback(self, dryrun=False, force=False):
603 604 wlock = self.wlock()
604 605 try:
605 606 if not dryrun:
606 607 changed = self['.'].files()
607 608 ret = super(kwrepo, self).rollback(dryrun, force)
608 609 if not dryrun:
609 610 ctx = self['.']
610 611 modified, added = _preselect(self[None].status(), changed)
611 612 kwt.overwrite(ctx, modified, True, True)
612 613 kwt.overwrite(ctx, added, True, False)
613 614 return ret
614 615 finally:
615 616 wlock.release()
616 617
617 618 # monkeypatches
618 619 def kwpatchfile_init(orig, self, ui, gp, backend, store, eolmode=None):
619 620 '''Monkeypatch/wrap patch.patchfile.__init__ to avoid
620 621 rejects or conflicts due to expanded keywords in working dir.'''
621 622 orig(self, ui, gp, backend, store, eolmode)
622 623 # shrink keywords read from working dir
623 624 self.lines = kwt.shrinklines(self.fname, self.lines)
624 625
625 626 def kw_diff(orig, repo, node1=None, node2=None, match=None, changes=None,
626 627 opts=None, prefix=''):
627 628 '''Monkeypatch patch.diff to avoid expansion.'''
628 629 kwt.restrict = True
629 630 return orig(repo, node1, node2, match, changes, opts, prefix)
630 631
631 632 def kwweb_skip(orig, web, req, tmpl):
632 633 '''Wraps webcommands.x turning off keyword expansion.'''
633 634 kwt.match = util.never
634 635 return orig(web, req, tmpl)
635 636
636 637 def kw_amend(orig, ui, repo, commitfunc, old, extra, pats, opts):
637 638 '''Wraps cmdutil.amend expanding keywords after amend.'''
638 639 wlock = repo.wlock()
639 640 try:
640 641 kwt.postcommit = True
641 642 newid = orig(ui, repo, commitfunc, old, extra, pats, opts)
642 643 if newid != old.node():
643 644 ctx = repo[newid]
644 645 kwt.restrict = True
645 646 kwt.overwrite(ctx, ctx.files(), False, True)
646 647 kwt.restrict = False
647 648 return newid
648 649 finally:
649 650 wlock.release()
650 651
651 652 def kw_copy(orig, ui, repo, pats, opts, rename=False):
652 653 '''Wraps cmdutil.copy so that copy/rename destinations do not
653 654 contain expanded keywords.
654 655 Note that the source of a regular file destination may also be a
655 656 symlink:
656 657 hg cp sym x -> x is symlink
657 658 cp sym x; hg cp -A sym x -> x is file (maybe expanded keywords)
658 659 For the latter we have to follow the symlink to find out whether its
659 660 target is configured for expansion and we therefore must unexpand the
660 661 keywords in the destination.'''
661 662 wlock = repo.wlock()
662 663 try:
663 664 orig(ui, repo, pats, opts, rename)
664 665 if opts.get('dry_run'):
665 666 return
666 667 wctx = repo[None]
667 668 cwd = repo.getcwd()
668 669
669 670 def haskwsource(dest):
670 671 '''Returns true if dest is a regular file and configured for
671 672 expansion or a symlink which points to a file configured for
672 673 expansion. '''
673 674 source = repo.dirstate.copied(dest)
674 675 if 'l' in wctx.flags(source):
675 676 source = scmutil.canonpath(repo.root, cwd,
676 677 os.path.realpath(source))
677 678 return kwt.match(source)
678 679
679 680 candidates = [f for f in repo.dirstate.copies() if
680 681 'l' not in wctx.flags(f) and haskwsource(f)]
681 682 kwt.overwrite(wctx, candidates, False, False)
682 683 finally:
683 684 wlock.release()
684 685
685 686 def kw_dorecord(orig, ui, repo, commitfunc, *pats, **opts):
686 687 '''Wraps record.dorecord expanding keywords after recording.'''
687 688 wlock = repo.wlock()
688 689 try:
689 690 # record returns 0 even when nothing has changed
690 691 # therefore compare nodes before and after
691 692 kwt.postcommit = True
692 693 ctx = repo['.']
693 694 wstatus = repo[None].status()
694 695 ret = orig(ui, repo, commitfunc, *pats, **opts)
695 696 recctx = repo['.']
696 697 if ctx != recctx:
697 698 modified, added = _preselect(wstatus, recctx.files())
698 699 kwt.restrict = False
699 700 kwt.overwrite(recctx, modified, False, True)
700 701 kwt.overwrite(recctx, added, False, True, True)
701 702 kwt.restrict = True
702 703 return ret
703 704 finally:
704 705 wlock.release()
705 706
706 707 def kwfilectx_cmp(orig, self, fctx):
707 708 # keyword affects data size, comparing wdir and filelog size does
708 709 # not make sense
709 710 if (fctx._filerev is None and
710 711 (self._repo._encodefilterpats or
711 712 kwt.match(fctx.path()) and 'l' not in fctx.flags() or
712 713 self.size() - 4 == fctx.size()) or
713 714 self.size() == fctx.size()):
714 715 return self._filelog.cmp(self._filenode, fctx.data())
715 716 return True
716 717
717 718 extensions.wrapfunction(context.filectx, 'cmp', kwfilectx_cmp)
718 719 extensions.wrapfunction(patch.patchfile, '__init__', kwpatchfile_init)
719 720 extensions.wrapfunction(patch, 'diff', kw_diff)
720 721 extensions.wrapfunction(cmdutil, 'amend', kw_amend)
721 722 extensions.wrapfunction(cmdutil, 'copy', kw_copy)
722 723 for c in 'annotate changeset rev filediff diff'.split():
723 724 extensions.wrapfunction(webcommands, c, kwweb_skip)
724 725 for name in recordextensions.split():
725 726 try:
726 727 record = extensions.find(name)
727 728 extensions.wrapfunction(record, 'dorecord', kw_dorecord)
728 729 except KeyError:
729 730 pass
730 731
731 732 repo.__class__ = kwrepo
@@ -1,3447 +1,3448 b''
1 1 # mq.py - patch queues for mercurial
2 2 #
3 3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 '''manage a stack of patches
9 9
10 10 This extension lets you work with a stack of patches in a Mercurial
11 11 repository. It manages two stacks of patches - all known patches, and
12 12 applied patches (subset of known patches).
13 13
14 14 Known patches are represented as patch files in the .hg/patches
15 15 directory. Applied patches are both patch files and changesets.
16 16
17 17 Common tasks (use :hg:`help command` for more details)::
18 18
19 19 create new patch qnew
20 20 import existing patch qimport
21 21
22 22 print patch series qseries
23 23 print applied patches qapplied
24 24
25 25 add known patch to applied stack qpush
26 26 remove patch from applied stack qpop
27 27 refresh contents of top applied patch qrefresh
28 28
29 29 By default, mq will automatically use git patches when required to
30 30 avoid losing file mode changes, copy records, binary files or empty
31 31 files creations or deletions. This behaviour can be configured with::
32 32
33 33 [mq]
34 34 git = auto/keep/yes/no
35 35
36 36 If set to 'keep', mq will obey the [diff] section configuration while
37 37 preserving existing git patches upon qrefresh. If set to 'yes' or
38 38 'no', mq will override the [diff] section and always generate git or
39 39 regular patches, possibly losing data in the second case.
40 40
41 41 It may be desirable for mq changesets to be kept in the secret phase (see
42 42 :hg:`help phases`), which can be enabled with the following setting::
43 43
44 44 [mq]
45 45 secret = True
46 46
47 47 You will by default be managing a patch queue named "patches". You can
48 48 create other, independent patch queues with the :hg:`qqueue` command.
49 49
50 50 If the working directory contains uncommitted files, qpush, qpop and
51 51 qgoto abort immediately. If -f/--force is used, the changes are
52 52 discarded. Setting::
53 53
54 54 [mq]
55 55 keepchanges = True
56 56
57 57 make them behave as if --keep-changes were passed, and non-conflicting
58 58 local changes will be tolerated and preserved. If incompatible options
59 59 such as -f/--force or --exact are passed, this setting is ignored.
60 60
61 61 This extension used to provide a strip command. This command now lives
62 62 in the strip extension.
63 63 '''
64 64
65 65 from mercurial.i18n import _
66 66 from mercurial.node import bin, hex, short, nullid, nullrev
67 67 from mercurial.lock import release
68 68 from mercurial import commands, cmdutil, hg, scmutil, util, revset
69 69 from mercurial import extensions, error, phases
70 70 from mercurial import patch as patchmod
71 71 from mercurial import localrepo
72 72 from mercurial import subrepo
73 73 import os, re, errno, shutil
74 74
75 75 commands.norepo += " qclone"
76 76
77 77 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
78 78
79 79 cmdtable = {}
80 80 command = cmdutil.command(cmdtable)
81 81 testedwith = 'internal'
82 82
83 83 # force load strip extension formerly included in mq and import some utility
84 84 try:
85 85 stripext = extensions.find('strip')
86 86 except KeyError:
87 87 # note: load is lazy so we could avoid the try-except,
88 88 # but I (marmoute) prefer this explicit code.
89 89 class dummyui(object):
90 90 def debug(self, msg):
91 91 pass
92 92 stripext = extensions.load(dummyui(), 'strip', '')
93 93
94 94 strip = stripext.strip
95 95 checksubstate = stripext.checksubstate
96 96 checklocalchanges = stripext.checklocalchanges
97 97
98 98
99 99 # Patch names looks like unix-file names.
100 100 # They must be joinable with queue directory and result in the patch path.
101 101 normname = util.normpath
102 102
103 103 class statusentry(object):
104 104 def __init__(self, node, name):
105 105 self.node, self.name = node, name
106 106 def __repr__(self):
107 107 return hex(self.node) + ':' + self.name
108 108
109 109 class patchheader(object):
110 110 def __init__(self, pf, plainmode=False):
111 111 def eatdiff(lines):
112 112 while lines:
113 113 l = lines[-1]
114 114 if (l.startswith("diff -") or
115 115 l.startswith("Index:") or
116 116 l.startswith("===========")):
117 117 del lines[-1]
118 118 else:
119 119 break
120 120 def eatempty(lines):
121 121 while lines:
122 122 if not lines[-1].strip():
123 123 del lines[-1]
124 124 else:
125 125 break
126 126
127 127 message = []
128 128 comments = []
129 129 user = None
130 130 date = None
131 131 parent = None
132 132 format = None
133 133 subject = None
134 134 branch = None
135 135 nodeid = None
136 136 diffstart = 0
137 137
138 138 for line in file(pf):
139 139 line = line.rstrip()
140 140 if (line.startswith('diff --git')
141 141 or (diffstart and line.startswith('+++ '))):
142 142 diffstart = 2
143 143 break
144 144 diffstart = 0 # reset
145 145 if line.startswith("--- "):
146 146 diffstart = 1
147 147 continue
148 148 elif format == "hgpatch":
149 149 # parse values when importing the result of an hg export
150 150 if line.startswith("# User "):
151 151 user = line[7:]
152 152 elif line.startswith("# Date "):
153 153 date = line[7:]
154 154 elif line.startswith("# Parent "):
155 155 parent = line[9:].lstrip()
156 156 elif line.startswith("# Branch "):
157 157 branch = line[9:]
158 158 elif line.startswith("# Node ID "):
159 159 nodeid = line[10:]
160 160 elif not line.startswith("# ") and line:
161 161 message.append(line)
162 162 format = None
163 163 elif line == '# HG changeset patch':
164 164 message = []
165 165 format = "hgpatch"
166 166 elif (format != "tagdone" and (line.startswith("Subject: ") or
167 167 line.startswith("subject: "))):
168 168 subject = line[9:]
169 169 format = "tag"
170 170 elif (format != "tagdone" and (line.startswith("From: ") or
171 171 line.startswith("from: "))):
172 172 user = line[6:]
173 173 format = "tag"
174 174 elif (format != "tagdone" and (line.startswith("Date: ") or
175 175 line.startswith("date: "))):
176 176 date = line[6:]
177 177 format = "tag"
178 178 elif format == "tag" and line == "":
179 179 # when looking for tags (subject: from: etc) they
180 180 # end once you find a blank line in the source
181 181 format = "tagdone"
182 182 elif message or line:
183 183 message.append(line)
184 184 comments.append(line)
185 185
186 186 eatdiff(message)
187 187 eatdiff(comments)
188 188 # Remember the exact starting line of the patch diffs before consuming
189 189 # empty lines, for external use by TortoiseHg and others
190 190 self.diffstartline = len(comments)
191 191 eatempty(message)
192 192 eatempty(comments)
193 193
194 194 # make sure message isn't empty
195 195 if format and format.startswith("tag") and subject:
196 196 message.insert(0, "")
197 197 message.insert(0, subject)
198 198
199 199 self.message = message
200 200 self.comments = comments
201 201 self.user = user
202 202 self.date = date
203 203 self.parent = parent
204 204 # nodeid and branch are for external use by TortoiseHg and others
205 205 self.nodeid = nodeid
206 206 self.branch = branch
207 207 self.haspatch = diffstart > 1
208 208 self.plainmode = plainmode
209 209
210 210 def setuser(self, user):
211 211 if not self.updateheader(['From: ', '# User '], user):
212 212 try:
213 213 patchheaderat = self.comments.index('# HG changeset patch')
214 214 self.comments.insert(patchheaderat + 1, '# User ' + user)
215 215 except ValueError:
216 216 if self.plainmode or self._hasheader(['Date: ']):
217 217 self.comments = ['From: ' + user] + self.comments
218 218 else:
219 219 tmp = ['# HG changeset patch', '# User ' + user, '']
220 220 self.comments = tmp + self.comments
221 221 self.user = user
222 222
223 223 def setdate(self, date):
224 224 if not self.updateheader(['Date: ', '# Date '], date):
225 225 try:
226 226 patchheaderat = self.comments.index('# HG changeset patch')
227 227 self.comments.insert(patchheaderat + 1, '# Date ' + date)
228 228 except ValueError:
229 229 if self.plainmode or self._hasheader(['From: ']):
230 230 self.comments = ['Date: ' + date] + self.comments
231 231 else:
232 232 tmp = ['# HG changeset patch', '# Date ' + date, '']
233 233 self.comments = tmp + self.comments
234 234 self.date = date
235 235
236 236 def setparent(self, parent):
237 237 if not self.updateheader(['# Parent '], parent):
238 238 try:
239 239 patchheaderat = self.comments.index('# HG changeset patch')
240 240 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
241 241 except ValueError:
242 242 pass
243 243 self.parent = parent
244 244
245 245 def setmessage(self, message):
246 246 if self.comments:
247 247 self._delmsg()
248 248 self.message = [message]
249 249 self.comments += self.message
250 250
251 251 def updateheader(self, prefixes, new):
252 252 '''Update all references to a field in the patch header.
253 253 Return whether the field is present.'''
254 254 res = False
255 255 for prefix in prefixes:
256 256 for i in xrange(len(self.comments)):
257 257 if self.comments[i].startswith(prefix):
258 258 self.comments[i] = prefix + new
259 259 res = True
260 260 break
261 261 return res
262 262
263 263 def _hasheader(self, prefixes):
264 264 '''Check if a header starts with any of the given prefixes.'''
265 265 for prefix in prefixes:
266 266 for comment in self.comments:
267 267 if comment.startswith(prefix):
268 268 return True
269 269 return False
270 270
271 271 def __str__(self):
272 272 if not self.comments:
273 273 return ''
274 274 return '\n'.join(self.comments) + '\n\n'
275 275
276 276 def _delmsg(self):
277 277 '''Remove existing message, keeping the rest of the comments fields.
278 278 If comments contains 'subject: ', message will prepend
279 279 the field and a blank line.'''
280 280 if self.message:
281 281 subj = 'subject: ' + self.message[0].lower()
282 282 for i in xrange(len(self.comments)):
283 283 if subj == self.comments[i].lower():
284 284 del self.comments[i]
285 285 self.message = self.message[2:]
286 286 break
287 287 ci = 0
288 288 for mi in self.message:
289 289 while mi != self.comments[ci]:
290 290 ci += 1
291 291 del self.comments[ci]
292 292
293 293 def newcommit(repo, phase, *args, **kwargs):
294 294 """helper dedicated to ensure a commit respect mq.secret setting
295 295
296 296 It should be used instead of repo.commit inside the mq source for operation
297 297 creating new changeset.
298 298 """
299 299 repo = repo.unfiltered()
300 300 if phase is None:
301 301 if repo.ui.configbool('mq', 'secret', False):
302 302 phase = phases.secret
303 303 if phase is not None:
304 304 backup = repo.ui.backupconfig('phases', 'new-commit')
305 305 try:
306 306 if phase is not None:
307 307 repo.ui.setconfig('phases', 'new-commit', phase)
308 308 return repo.commit(*args, **kwargs)
309 309 finally:
310 310 if phase is not None:
311 311 repo.ui.restoreconfig(backup)
312 312
313 313 class AbortNoCleanup(error.Abort):
314 314 pass
315 315
316 316 class queue(object):
317 317 def __init__(self, ui, baseui, path, patchdir=None):
318 318 self.basepath = path
319 319 try:
320 320 fh = open(os.path.join(path, 'patches.queue'))
321 321 cur = fh.read().rstrip()
322 322 fh.close()
323 323 if not cur:
324 324 curpath = os.path.join(path, 'patches')
325 325 else:
326 326 curpath = os.path.join(path, 'patches-' + cur)
327 327 except IOError:
328 328 curpath = os.path.join(path, 'patches')
329 329 self.path = patchdir or curpath
330 330 self.opener = scmutil.opener(self.path)
331 331 self.ui = ui
332 332 self.baseui = baseui
333 333 self.applieddirty = False
334 334 self.seriesdirty = False
335 335 self.added = []
336 336 self.seriespath = "series"
337 337 self.statuspath = "status"
338 338 self.guardspath = "guards"
339 339 self.activeguards = None
340 340 self.guardsdirty = False
341 341 # Handle mq.git as a bool with extended values
342 342 try:
343 343 gitmode = ui.configbool('mq', 'git', None)
344 344 if gitmode is None:
345 345 raise error.ConfigError
346 346 self.gitmode = gitmode and 'yes' or 'no'
347 347 except error.ConfigError:
348 348 self.gitmode = ui.config('mq', 'git', 'auto').lower()
349 349 self.plainmode = ui.configbool('mq', 'plain', False)
350 350 self.checkapplied = True
351 351
352 352 @util.propertycache
353 353 def applied(self):
354 354 def parselines(lines):
355 355 for l in lines:
356 356 entry = l.split(':', 1)
357 357 if len(entry) > 1:
358 358 n, name = entry
359 359 yield statusentry(bin(n), name)
360 360 elif l.strip():
361 361 self.ui.warn(_('malformated mq status line: %s\n') % entry)
362 362 # else we ignore empty lines
363 363 try:
364 364 lines = self.opener.read(self.statuspath).splitlines()
365 365 return list(parselines(lines))
366 366 except IOError, e:
367 367 if e.errno == errno.ENOENT:
368 368 return []
369 369 raise
370 370
371 371 @util.propertycache
372 372 def fullseries(self):
373 373 try:
374 374 return self.opener.read(self.seriespath).splitlines()
375 375 except IOError, e:
376 376 if e.errno == errno.ENOENT:
377 377 return []
378 378 raise
379 379
380 380 @util.propertycache
381 381 def series(self):
382 382 self.parseseries()
383 383 return self.series
384 384
385 385 @util.propertycache
386 386 def seriesguards(self):
387 387 self.parseseries()
388 388 return self.seriesguards
389 389
390 390 def invalidate(self):
391 391 for a in 'applied fullseries series seriesguards'.split():
392 392 if a in self.__dict__:
393 393 delattr(self, a)
394 394 self.applieddirty = False
395 395 self.seriesdirty = False
396 396 self.guardsdirty = False
397 397 self.activeguards = None
398 398
399 399 def diffopts(self, opts={}, patchfn=None):
400 400 diffopts = patchmod.diffopts(self.ui, opts)
401 401 if self.gitmode == 'auto':
402 402 diffopts.upgrade = True
403 403 elif self.gitmode == 'keep':
404 404 pass
405 405 elif self.gitmode in ('yes', 'no'):
406 406 diffopts.git = self.gitmode == 'yes'
407 407 else:
408 408 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
409 409 ' got %s') % self.gitmode)
410 410 if patchfn:
411 411 diffopts = self.patchopts(diffopts, patchfn)
412 412 return diffopts
413 413
414 414 def patchopts(self, diffopts, *patches):
415 415 """Return a copy of input diff options with git set to true if
416 416 referenced patch is a git patch and should be preserved as such.
417 417 """
418 418 diffopts = diffopts.copy()
419 419 if not diffopts.git and self.gitmode == 'keep':
420 420 for patchfn in patches:
421 421 patchf = self.opener(patchfn, 'r')
422 422 # if the patch was a git patch, refresh it as a git patch
423 423 for line in patchf:
424 424 if line.startswith('diff --git'):
425 425 diffopts.git = True
426 426 break
427 427 patchf.close()
428 428 return diffopts
429 429
430 430 def join(self, *p):
431 431 return os.path.join(self.path, *p)
432 432
433 433 def findseries(self, patch):
434 434 def matchpatch(l):
435 435 l = l.split('#', 1)[0]
436 436 return l.strip() == patch
437 437 for index, l in enumerate(self.fullseries):
438 438 if matchpatch(l):
439 439 return index
440 440 return None
441 441
442 442 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
443 443
444 444 def parseseries(self):
445 445 self.series = []
446 446 self.seriesguards = []
447 447 for l in self.fullseries:
448 448 h = l.find('#')
449 449 if h == -1:
450 450 patch = l
451 451 comment = ''
452 452 elif h == 0:
453 453 continue
454 454 else:
455 455 patch = l[:h]
456 456 comment = l[h:]
457 457 patch = patch.strip()
458 458 if patch:
459 459 if patch in self.series:
460 460 raise util.Abort(_('%s appears more than once in %s') %
461 461 (patch, self.join(self.seriespath)))
462 462 self.series.append(patch)
463 463 self.seriesguards.append(self.guard_re.findall(comment))
464 464
465 465 def checkguard(self, guard):
466 466 if not guard:
467 467 return _('guard cannot be an empty string')
468 468 bad_chars = '# \t\r\n\f'
469 469 first = guard[0]
470 470 if first in '-+':
471 471 return (_('guard %r starts with invalid character: %r') %
472 472 (guard, first))
473 473 for c in bad_chars:
474 474 if c in guard:
475 475 return _('invalid character in guard %r: %r') % (guard, c)
476 476
477 477 def setactive(self, guards):
478 478 for guard in guards:
479 479 bad = self.checkguard(guard)
480 480 if bad:
481 481 raise util.Abort(bad)
482 482 guards = sorted(set(guards))
483 483 self.ui.debug('active guards: %s\n' % ' '.join(guards))
484 484 self.activeguards = guards
485 485 self.guardsdirty = True
486 486
487 487 def active(self):
488 488 if self.activeguards is None:
489 489 self.activeguards = []
490 490 try:
491 491 guards = self.opener.read(self.guardspath).split()
492 492 except IOError, err:
493 493 if err.errno != errno.ENOENT:
494 494 raise
495 495 guards = []
496 496 for i, guard in enumerate(guards):
497 497 bad = self.checkguard(guard)
498 498 if bad:
499 499 self.ui.warn('%s:%d: %s\n' %
500 500 (self.join(self.guardspath), i + 1, bad))
501 501 else:
502 502 self.activeguards.append(guard)
503 503 return self.activeguards
504 504
505 505 def setguards(self, idx, guards):
506 506 for g in guards:
507 507 if len(g) < 2:
508 508 raise util.Abort(_('guard %r too short') % g)
509 509 if g[0] not in '-+':
510 510 raise util.Abort(_('guard %r starts with invalid char') % g)
511 511 bad = self.checkguard(g[1:])
512 512 if bad:
513 513 raise util.Abort(bad)
514 514 drop = self.guard_re.sub('', self.fullseries[idx])
515 515 self.fullseries[idx] = drop + ''.join([' #' + g for g in guards])
516 516 self.parseseries()
517 517 self.seriesdirty = True
518 518
519 519 def pushable(self, idx):
520 520 if isinstance(idx, str):
521 521 idx = self.series.index(idx)
522 522 patchguards = self.seriesguards[idx]
523 523 if not patchguards:
524 524 return True, None
525 525 guards = self.active()
526 526 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
527 527 if exactneg:
528 528 return False, repr(exactneg[0])
529 529 pos = [g for g in patchguards if g[0] == '+']
530 530 exactpos = [g for g in pos if g[1:] in guards]
531 531 if pos:
532 532 if exactpos:
533 533 return True, repr(exactpos[0])
534 534 return False, ' '.join(map(repr, pos))
535 535 return True, ''
536 536
537 537 def explainpushable(self, idx, all_patches=False):
538 538 write = all_patches and self.ui.write or self.ui.warn
539 539 if all_patches or self.ui.verbose:
540 540 if isinstance(idx, str):
541 541 idx = self.series.index(idx)
542 542 pushable, why = self.pushable(idx)
543 543 if all_patches and pushable:
544 544 if why is None:
545 545 write(_('allowing %s - no guards in effect\n') %
546 546 self.series[idx])
547 547 else:
548 548 if not why:
549 549 write(_('allowing %s - no matching negative guards\n') %
550 550 self.series[idx])
551 551 else:
552 552 write(_('allowing %s - guarded by %s\n') %
553 553 (self.series[idx], why))
554 554 if not pushable:
555 555 if why:
556 556 write(_('skipping %s - guarded by %s\n') %
557 557 (self.series[idx], why))
558 558 else:
559 559 write(_('skipping %s - no matching guards\n') %
560 560 self.series[idx])
561 561
562 562 def savedirty(self):
563 563 def writelist(items, path):
564 564 fp = self.opener(path, 'w')
565 565 for i in items:
566 566 fp.write("%s\n" % i)
567 567 fp.close()
568 568 if self.applieddirty:
569 569 writelist(map(str, self.applied), self.statuspath)
570 570 self.applieddirty = False
571 571 if self.seriesdirty:
572 572 writelist(self.fullseries, self.seriespath)
573 573 self.seriesdirty = False
574 574 if self.guardsdirty:
575 575 writelist(self.activeguards, self.guardspath)
576 576 self.guardsdirty = False
577 577 if self.added:
578 578 qrepo = self.qrepo()
579 579 if qrepo:
580 580 qrepo[None].add(f for f in self.added if f not in qrepo[None])
581 581 self.added = []
582 582
583 583 def removeundo(self, repo):
584 584 undo = repo.sjoin('undo')
585 585 if not os.path.exists(undo):
586 586 return
587 587 try:
588 588 os.unlink(undo)
589 589 except OSError, inst:
590 590 self.ui.warn(_('error removing undo: %s\n') % str(inst))
591 591
592 592 def backup(self, repo, files, copy=False):
593 593 # backup local changes in --force case
594 594 for f in sorted(files):
595 595 absf = repo.wjoin(f)
596 596 if os.path.lexists(absf):
597 597 self.ui.note(_('saving current version of %s as %s\n') %
598 598 (f, f + '.orig'))
599 599 if copy:
600 600 util.copyfile(absf, absf + '.orig')
601 601 else:
602 602 util.rename(absf, absf + '.orig')
603 603
604 604 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
605 605 fp=None, changes=None, opts={}):
606 606 stat = opts.get('stat')
607 607 m = scmutil.match(repo[node1], files, opts)
608 608 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
609 609 changes, stat, fp)
610 610
611 611 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
612 612 # first try just applying the patch
613 613 (err, n) = self.apply(repo, [patch], update_status=False,
614 614 strict=True, merge=rev)
615 615
616 616 if err == 0:
617 617 return (err, n)
618 618
619 619 if n is None:
620 620 raise util.Abort(_("apply failed for patch %s") % patch)
621 621
622 622 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
623 623
624 624 # apply failed, strip away that rev and merge.
625 625 hg.clean(repo, head)
626 626 strip(self.ui, repo, [n], update=False, backup='strip')
627 627
628 628 ctx = repo[rev]
629 629 ret = hg.merge(repo, rev)
630 630 if ret:
631 631 raise util.Abort(_("update returned %d") % ret)
632 632 n = newcommit(repo, None, ctx.description(), ctx.user(), force=True)
633 633 if n is None:
634 634 raise util.Abort(_("repo commit failed"))
635 635 try:
636 636 ph = patchheader(mergeq.join(patch), self.plainmode)
637 637 except Exception:
638 638 raise util.Abort(_("unable to read %s") % patch)
639 639
640 640 diffopts = self.patchopts(diffopts, patch)
641 641 patchf = self.opener(patch, "w")
642 642 comments = str(ph)
643 643 if comments:
644 644 patchf.write(comments)
645 645 self.printdiff(repo, diffopts, head, n, fp=patchf)
646 646 patchf.close()
647 647 self.removeundo(repo)
648 648 return (0, n)
649 649
650 650 def qparents(self, repo, rev=None):
651 651 """return the mq handled parent or p1
652 652
653 653 In some case where mq get himself in being the parent of a merge the
654 654 appropriate parent may be p2.
655 655 (eg: an in progress merge started with mq disabled)
656 656
657 657 If no parent are managed by mq, p1 is returned.
658 658 """
659 659 if rev is None:
660 660 (p1, p2) = repo.dirstate.parents()
661 661 if p2 == nullid:
662 662 return p1
663 663 if not self.applied:
664 664 return None
665 665 return self.applied[-1].node
666 666 p1, p2 = repo.changelog.parents(rev)
667 667 if p2 != nullid and p2 in [x.node for x in self.applied]:
668 668 return p2
669 669 return p1
670 670
671 671 def mergepatch(self, repo, mergeq, series, diffopts):
672 672 if not self.applied:
673 673 # each of the patches merged in will have two parents. This
674 674 # can confuse the qrefresh, qdiff, and strip code because it
675 675 # needs to know which parent is actually in the patch queue.
676 676 # so, we insert a merge marker with only one parent. This way
677 677 # the first patch in the queue is never a merge patch
678 678 #
679 679 pname = ".hg.patches.merge.marker"
680 680 n = newcommit(repo, None, '[mq]: merge marker', force=True)
681 681 self.removeundo(repo)
682 682 self.applied.append(statusentry(n, pname))
683 683 self.applieddirty = True
684 684
685 685 head = self.qparents(repo)
686 686
687 687 for patch in series:
688 688 patch = mergeq.lookup(patch, strict=True)
689 689 if not patch:
690 690 self.ui.warn(_("patch %s does not exist\n") % patch)
691 691 return (1, None)
692 692 pushable, reason = self.pushable(patch)
693 693 if not pushable:
694 694 self.explainpushable(patch, all_patches=True)
695 695 continue
696 696 info = mergeq.isapplied(patch)
697 697 if not info:
698 698 self.ui.warn(_("patch %s is not applied\n") % patch)
699 699 return (1, None)
700 700 rev = info[1]
701 701 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
702 702 if head:
703 703 self.applied.append(statusentry(head, patch))
704 704 self.applieddirty = True
705 705 if err:
706 706 return (err, head)
707 707 self.savedirty()
708 708 return (0, head)
709 709
710 710 def patch(self, repo, patchfile):
711 711 '''Apply patchfile to the working directory.
712 712 patchfile: name of patch file'''
713 713 files = set()
714 714 try:
715 715 fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
716 716 files=files, eolmode=None)
717 717 return (True, list(files), fuzz)
718 718 except Exception, inst:
719 719 self.ui.note(str(inst) + '\n')
720 720 if not self.ui.verbose:
721 721 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
722 722 self.ui.traceback()
723 723 return (False, list(files), False)
724 724
725 725 def apply(self, repo, series, list=False, update_status=True,
726 726 strict=False, patchdir=None, merge=None, all_files=None,
727 727 tobackup=None, keepchanges=False):
728 728 wlock = lock = tr = None
729 729 try:
730 730 wlock = repo.wlock()
731 731 lock = repo.lock()
732 732 tr = repo.transaction("qpush")
733 733 try:
734 734 ret = self._apply(repo, series, list, update_status,
735 735 strict, patchdir, merge, all_files=all_files,
736 736 tobackup=tobackup, keepchanges=keepchanges)
737 737 tr.close()
738 738 self.savedirty()
739 739 return ret
740 740 except AbortNoCleanup:
741 741 tr.close()
742 742 self.savedirty()
743 743 return 2, repo.dirstate.p1()
744 744 except: # re-raises
745 745 try:
746 746 tr.abort()
747 747 finally:
748 748 repo.invalidate()
749 749 repo.dirstate.invalidate()
750 750 self.invalidate()
751 751 raise
752 752 finally:
753 753 release(tr, lock, wlock)
754 754 self.removeundo(repo)
755 755
756 756 def _apply(self, repo, series, list=False, update_status=True,
757 757 strict=False, patchdir=None, merge=None, all_files=None,
758 758 tobackup=None, keepchanges=False):
759 759 """returns (error, hash)
760 760
761 761 error = 1 for unable to read, 2 for patch failed, 3 for patch
762 762 fuzz. tobackup is None or a set of files to backup before they
763 763 are modified by a patch.
764 764 """
765 765 # TODO unify with commands.py
766 766 if not patchdir:
767 767 patchdir = self.path
768 768 err = 0
769 769 n = None
770 770 for patchname in series:
771 771 pushable, reason = self.pushable(patchname)
772 772 if not pushable:
773 773 self.explainpushable(patchname, all_patches=True)
774 774 continue
775 775 self.ui.status(_("applying %s\n") % patchname)
776 776 pf = os.path.join(patchdir, patchname)
777 777
778 778 try:
779 779 ph = patchheader(self.join(patchname), self.plainmode)
780 780 except IOError:
781 781 self.ui.warn(_("unable to read %s\n") % patchname)
782 782 err = 1
783 783 break
784 784
785 785 message = ph.message
786 786 if not message:
787 787 # The commit message should not be translated
788 788 message = "imported patch %s\n" % patchname
789 789 else:
790 790 if list:
791 791 # The commit message should not be translated
792 792 message.append("\nimported patch %s" % patchname)
793 793 message = '\n'.join(message)
794 794
795 795 if ph.haspatch:
796 796 if tobackup:
797 797 touched = patchmod.changedfiles(self.ui, repo, pf)
798 798 touched = set(touched) & tobackup
799 799 if touched and keepchanges:
800 800 raise AbortNoCleanup(
801 801 _("local changes found, refresh first"))
802 802 self.backup(repo, touched, copy=True)
803 803 tobackup = tobackup - touched
804 804 (patcherr, files, fuzz) = self.patch(repo, pf)
805 805 if all_files is not None:
806 806 all_files.update(files)
807 807 patcherr = not patcherr
808 808 else:
809 809 self.ui.warn(_("patch %s is empty\n") % patchname)
810 810 patcherr, files, fuzz = 0, [], 0
811 811
812 812 if merge and files:
813 813 # Mark as removed/merged and update dirstate parent info
814 814 removed = []
815 815 merged = []
816 816 for f in files:
817 817 if os.path.lexists(repo.wjoin(f)):
818 818 merged.append(f)
819 819 else:
820 820 removed.append(f)
821 821 for f in removed:
822 822 repo.dirstate.remove(f)
823 823 for f in merged:
824 824 repo.dirstate.merge(f)
825 825 p1, p2 = repo.dirstate.parents()
826 826 repo.setparents(p1, merge)
827 827
828 828 if all_files and '.hgsubstate' in all_files:
829 829 wctx = repo['.']
830 830 mctx = actx = repo[None]
831 831 overwrite = False
832 832 mergedsubstate = subrepo.submerge(repo, wctx, mctx, actx,
833 833 overwrite)
834 834 files += mergedsubstate.keys()
835 835
836 836 match = scmutil.matchfiles(repo, files or [])
837 837 oldtip = repo['tip']
838 838 n = newcommit(repo, None, message, ph.user, ph.date, match=match,
839 839 force=True)
840 840 if repo['tip'] == oldtip:
841 841 raise util.Abort(_("qpush exactly duplicates child changeset"))
842 842 if n is None:
843 843 raise util.Abort(_("repository commit failed"))
844 844
845 845 if update_status:
846 846 self.applied.append(statusentry(n, patchname))
847 847
848 848 if patcherr:
849 849 self.ui.warn(_("patch failed, rejects left in working dir\n"))
850 850 err = 2
851 851 break
852 852
853 853 if fuzz and strict:
854 854 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
855 855 err = 3
856 856 break
857 857 return (err, n)
858 858
859 859 def _cleanup(self, patches, numrevs, keep=False):
860 860 if not keep:
861 861 r = self.qrepo()
862 862 if r:
863 863 r[None].forget(patches)
864 864 for p in patches:
865 865 try:
866 866 os.unlink(self.join(p))
867 867 except OSError, inst:
868 868 if inst.errno != errno.ENOENT:
869 869 raise
870 870
871 871 qfinished = []
872 872 if numrevs:
873 873 qfinished = self.applied[:numrevs]
874 874 del self.applied[:numrevs]
875 875 self.applieddirty = True
876 876
877 877 unknown = []
878 878
879 879 for (i, p) in sorted([(self.findseries(p), p) for p in patches],
880 880 reverse=True):
881 881 if i is not None:
882 882 del self.fullseries[i]
883 883 else:
884 884 unknown.append(p)
885 885
886 886 if unknown:
887 887 if numrevs:
888 888 rev = dict((entry.name, entry.node) for entry in qfinished)
889 889 for p in unknown:
890 890 msg = _('revision %s refers to unknown patches: %s\n')
891 891 self.ui.warn(msg % (short(rev[p]), p))
892 892 else:
893 893 msg = _('unknown patches: %s\n')
894 894 raise util.Abort(''.join(msg % p for p in unknown))
895 895
896 896 self.parseseries()
897 897 self.seriesdirty = True
898 898 return [entry.node for entry in qfinished]
899 899
900 900 def _revpatches(self, repo, revs):
901 901 firstrev = repo[self.applied[0].node].rev()
902 902 patches = []
903 903 for i, rev in enumerate(revs):
904 904
905 905 if rev < firstrev:
906 906 raise util.Abort(_('revision %d is not managed') % rev)
907 907
908 908 ctx = repo[rev]
909 909 base = self.applied[i].node
910 910 if ctx.node() != base:
911 911 msg = _('cannot delete revision %d above applied patches')
912 912 raise util.Abort(msg % rev)
913 913
914 914 patch = self.applied[i].name
915 915 for fmt in ('[mq]: %s', 'imported patch %s'):
916 916 if ctx.description() == fmt % patch:
917 917 msg = _('patch %s finalized without changeset message\n')
918 918 repo.ui.status(msg % patch)
919 919 break
920 920
921 921 patches.append(patch)
922 922 return patches
923 923
924 924 def finish(self, repo, revs):
925 925 # Manually trigger phase computation to ensure phasedefaults is
926 926 # executed before we remove the patches.
927 927 repo._phasecache
928 928 patches = self._revpatches(repo, sorted(revs))
929 929 qfinished = self._cleanup(patches, len(patches))
930 930 if qfinished and repo.ui.configbool('mq', 'secret', False):
931 931 # only use this logic when the secret option is added
932 932 oldqbase = repo[qfinished[0]]
933 933 tphase = repo.ui.config('phases', 'new-commit', phases.draft)
934 934 if oldqbase.phase() > tphase and oldqbase.p1().phase() <= tphase:
935 935 phases.advanceboundary(repo, tphase, qfinished)
936 936
937 937 def delete(self, repo, patches, opts):
938 938 if not patches and not opts.get('rev'):
939 939 raise util.Abort(_('qdelete requires at least one revision or '
940 940 'patch name'))
941 941
942 942 realpatches = []
943 943 for patch in patches:
944 944 patch = self.lookup(patch, strict=True)
945 945 info = self.isapplied(patch)
946 946 if info:
947 947 raise util.Abort(_("cannot delete applied patch %s") % patch)
948 948 if patch not in self.series:
949 949 raise util.Abort(_("patch %s not in series file") % patch)
950 950 if patch not in realpatches:
951 951 realpatches.append(patch)
952 952
953 953 numrevs = 0
954 954 if opts.get('rev'):
955 955 if not self.applied:
956 956 raise util.Abort(_('no patches applied'))
957 957 revs = scmutil.revrange(repo, opts.get('rev'))
958 958 if len(revs) > 1 and revs[0] > revs[1]:
959 959 revs.reverse()
960 960 revpatches = self._revpatches(repo, revs)
961 961 realpatches += revpatches
962 962 numrevs = len(revpatches)
963 963
964 964 self._cleanup(realpatches, numrevs, opts.get('keep'))
965 965
966 966 def checktoppatch(self, repo):
967 967 '''check that working directory is at qtip'''
968 968 if self.applied:
969 969 top = self.applied[-1].node
970 970 patch = self.applied[-1].name
971 971 if repo.dirstate.p1() != top:
972 972 raise util.Abort(_("working directory revision is not qtip"))
973 973 return top, patch
974 974 return None, None
975 975
976 976 def putsubstate2changes(self, substatestate, changes):
977 977 for files in changes[:3]:
978 978 if '.hgsubstate' in files:
979 979 return # already listed up
980 980 # not yet listed up
981 981 if substatestate in 'a?':
982 982 changes[1].append('.hgsubstate')
983 983 elif substatestate in 'r':
984 984 changes[2].append('.hgsubstate')
985 985 else: # modified
986 986 changes[0].append('.hgsubstate')
987 987
988 988 def checklocalchanges(self, repo, force=False, refresh=True):
989 989 excsuffix = ''
990 990 if refresh:
991 991 excsuffix = ', refresh first'
992 992 # plain versions for i18n tool to detect them
993 993 _("local changes found, refresh first")
994 994 _("local changed subrepos found, refresh first")
995 995 return checklocalchanges(repo, force, excsuffix)
996 996
997 997 _reserved = ('series', 'status', 'guards', '.', '..')
998 998 def checkreservedname(self, name):
999 999 if name in self._reserved:
1000 1000 raise util.Abort(_('"%s" cannot be used as the name of a patch')
1001 1001 % name)
1002 1002 for prefix in ('.hg', '.mq'):
1003 1003 if name.startswith(prefix):
1004 1004 raise util.Abort(_('patch name cannot begin with "%s"')
1005 1005 % prefix)
1006 1006 for c in ('#', ':'):
1007 1007 if c in name:
1008 1008 raise util.Abort(_('"%s" cannot be used in the name of a patch')
1009 1009 % c)
1010 1010
1011 1011 def checkpatchname(self, name, force=False):
1012 1012 self.checkreservedname(name)
1013 1013 if not force and os.path.exists(self.join(name)):
1014 1014 if os.path.isdir(self.join(name)):
1015 1015 raise util.Abort(_('"%s" already exists as a directory')
1016 1016 % name)
1017 1017 else:
1018 1018 raise util.Abort(_('patch "%s" already exists') % name)
1019 1019
1020 1020 def checkkeepchanges(self, keepchanges, force):
1021 1021 if force and keepchanges:
1022 1022 raise util.Abort(_('cannot use both --force and --keep-changes'))
1023 1023
1024 1024 def new(self, repo, patchfn, *pats, **opts):
1025 1025 """options:
1026 1026 msg: a string or a no-argument function returning a string
1027 1027 """
1028 1028 msg = opts.get('msg')
1029 1029 user = opts.get('user')
1030 1030 date = opts.get('date')
1031 1031 if date:
1032 1032 date = util.parsedate(date)
1033 1033 diffopts = self.diffopts({'git': opts.get('git')})
1034 1034 if opts.get('checkname', True):
1035 1035 self.checkpatchname(patchfn)
1036 1036 inclsubs = checksubstate(repo)
1037 1037 if inclsubs:
1038 1038 inclsubs.append('.hgsubstate')
1039 1039 substatestate = repo.dirstate['.hgsubstate']
1040 1040 if opts.get('include') or opts.get('exclude') or pats:
1041 1041 if inclsubs:
1042 1042 pats = list(pats or []) + inclsubs
1043 1043 match = scmutil.match(repo[None], pats, opts)
1044 1044 # detect missing files in pats
1045 1045 def badfn(f, msg):
1046 1046 if f != '.hgsubstate': # .hgsubstate is auto-created
1047 1047 raise util.Abort('%s: %s' % (f, msg))
1048 1048 match.bad = badfn
1049 1049 changes = repo.status(match=match)
1050 1050 m, a, r, d = changes[:4]
1051 1051 else:
1052 1052 changes = self.checklocalchanges(repo, force=True)
1053 1053 m, a, r, d = changes
1054 1054 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
1055 1055 if len(repo[None].parents()) > 1:
1056 1056 raise util.Abort(_('cannot manage merge changesets'))
1057 1057 commitfiles = m + a + r
1058 1058 self.checktoppatch(repo)
1059 1059 insert = self.fullseriesend()
1060 1060 wlock = repo.wlock()
1061 1061 try:
1062 1062 try:
1063 1063 # if patch file write fails, abort early
1064 1064 p = self.opener(patchfn, "w")
1065 1065 except IOError, e:
1066 1066 raise util.Abort(_('cannot write patch "%s": %s')
1067 1067 % (patchfn, e.strerror))
1068 1068 try:
1069 1069 if self.plainmode:
1070 1070 if user:
1071 1071 p.write("From: " + user + "\n")
1072 1072 if not date:
1073 1073 p.write("\n")
1074 1074 if date:
1075 1075 p.write("Date: %d %d\n\n" % date)
1076 1076 else:
1077 1077 p.write("# HG changeset patch\n")
1078 1078 p.write("# Parent "
1079 1079 + hex(repo[None].p1().node()) + "\n")
1080 1080 if user:
1081 1081 p.write("# User " + user + "\n")
1082 1082 if date:
1083 1083 p.write("# Date %s %s\n\n" % date)
1084 1084 if util.safehasattr(msg, '__call__'):
1085 1085 msg = msg()
1086 1086 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
1087 1087 n = newcommit(repo, None, commitmsg, user, date, match=match,
1088 1088 force=True)
1089 1089 if n is None:
1090 1090 raise util.Abort(_("repo commit failed"))
1091 1091 try:
1092 1092 self.fullseries[insert:insert] = [patchfn]
1093 1093 self.applied.append(statusentry(n, patchfn))
1094 1094 self.parseseries()
1095 1095 self.seriesdirty = True
1096 1096 self.applieddirty = True
1097 1097 if msg:
1098 1098 msg = msg + "\n\n"
1099 1099 p.write(msg)
1100 1100 if commitfiles:
1101 1101 parent = self.qparents(repo, n)
1102 1102 if inclsubs:
1103 1103 self.putsubstate2changes(substatestate, changes)
1104 1104 chunks = patchmod.diff(repo, node1=parent, node2=n,
1105 1105 changes=changes, opts=diffopts)
1106 1106 for chunk in chunks:
1107 1107 p.write(chunk)
1108 1108 p.close()
1109 1109 r = self.qrepo()
1110 1110 if r:
1111 1111 r[None].add([patchfn])
1112 1112 except: # re-raises
1113 1113 repo.rollback()
1114 1114 raise
1115 1115 except Exception:
1116 1116 patchpath = self.join(patchfn)
1117 1117 try:
1118 1118 os.unlink(patchpath)
1119 1119 except OSError:
1120 1120 self.ui.warn(_('error unlinking %s\n') % patchpath)
1121 1121 raise
1122 1122 self.removeundo(repo)
1123 1123 finally:
1124 1124 release(wlock)
1125 1125
1126 1126 def isapplied(self, patch):
1127 1127 """returns (index, rev, patch)"""
1128 1128 for i, a in enumerate(self.applied):
1129 1129 if a.name == patch:
1130 1130 return (i, a.node, a.name)
1131 1131 return None
1132 1132
1133 1133 # if the exact patch name does not exist, we try a few
1134 1134 # variations. If strict is passed, we try only #1
1135 1135 #
1136 1136 # 1) a number (as string) to indicate an offset in the series file
1137 1137 # 2) a unique substring of the patch name was given
1138 1138 # 3) patchname[-+]num to indicate an offset in the series file
1139 1139 def lookup(self, patch, strict=False):
1140 1140 def partialname(s):
1141 1141 if s in self.series:
1142 1142 return s
1143 1143 matches = [x for x in self.series if s in x]
1144 1144 if len(matches) > 1:
1145 1145 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1146 1146 for m in matches:
1147 1147 self.ui.warn(' %s\n' % m)
1148 1148 return None
1149 1149 if matches:
1150 1150 return matches[0]
1151 1151 if self.series and self.applied:
1152 1152 if s == 'qtip':
1153 1153 return self.series[self.seriesend(True) - 1]
1154 1154 if s == 'qbase':
1155 1155 return self.series[0]
1156 1156 return None
1157 1157
1158 1158 if patch in self.series:
1159 1159 return patch
1160 1160
1161 1161 if not os.path.isfile(self.join(patch)):
1162 1162 try:
1163 1163 sno = int(patch)
1164 1164 except (ValueError, OverflowError):
1165 1165 pass
1166 1166 else:
1167 1167 if -len(self.series) <= sno < len(self.series):
1168 1168 return self.series[sno]
1169 1169
1170 1170 if not strict:
1171 1171 res = partialname(patch)
1172 1172 if res:
1173 1173 return res
1174 1174 minus = patch.rfind('-')
1175 1175 if minus >= 0:
1176 1176 res = partialname(patch[:minus])
1177 1177 if res:
1178 1178 i = self.series.index(res)
1179 1179 try:
1180 1180 off = int(patch[minus + 1:] or 1)
1181 1181 except (ValueError, OverflowError):
1182 1182 pass
1183 1183 else:
1184 1184 if i - off >= 0:
1185 1185 return self.series[i - off]
1186 1186 plus = patch.rfind('+')
1187 1187 if plus >= 0:
1188 1188 res = partialname(patch[:plus])
1189 1189 if res:
1190 1190 i = self.series.index(res)
1191 1191 try:
1192 1192 off = int(patch[plus + 1:] or 1)
1193 1193 except (ValueError, OverflowError):
1194 1194 pass
1195 1195 else:
1196 1196 if i + off < len(self.series):
1197 1197 return self.series[i + off]
1198 1198 raise util.Abort(_("patch %s not in series") % patch)
1199 1199
1200 1200 def push(self, repo, patch=None, force=False, list=False, mergeq=None,
1201 1201 all=False, move=False, exact=False, nobackup=False,
1202 1202 keepchanges=False):
1203 1203 self.checkkeepchanges(keepchanges, force)
1204 1204 diffopts = self.diffopts()
1205 1205 wlock = repo.wlock()
1206 1206 try:
1207 1207 heads = [h for hs in repo.branchmap().itervalues() for h in hs]
1208 1208 if not heads:
1209 1209 heads = [nullid]
1210 1210 if repo.dirstate.p1() not in heads and not exact:
1211 1211 self.ui.status(_("(working directory not at a head)\n"))
1212 1212
1213 1213 if not self.series:
1214 1214 self.ui.warn(_('no patches in series\n'))
1215 1215 return 0
1216 1216
1217 1217 # Suppose our series file is: A B C and the current 'top'
1218 1218 # patch is B. qpush C should be performed (moving forward)
1219 1219 # qpush B is a NOP (no change) qpush A is an error (can't
1220 1220 # go backwards with qpush)
1221 1221 if patch:
1222 1222 patch = self.lookup(patch)
1223 1223 info = self.isapplied(patch)
1224 1224 if info and info[0] >= len(self.applied) - 1:
1225 1225 self.ui.warn(
1226 1226 _('qpush: %s is already at the top\n') % patch)
1227 1227 return 0
1228 1228
1229 1229 pushable, reason = self.pushable(patch)
1230 1230 if pushable:
1231 1231 if self.series.index(patch) < self.seriesend():
1232 1232 raise util.Abort(
1233 1233 _("cannot push to a previous patch: %s") % patch)
1234 1234 else:
1235 1235 if reason:
1236 1236 reason = _('guarded by %s') % reason
1237 1237 else:
1238 1238 reason = _('no matching guards')
1239 1239 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1240 1240 return 1
1241 1241 elif all:
1242 1242 patch = self.series[-1]
1243 1243 if self.isapplied(patch):
1244 1244 self.ui.warn(_('all patches are currently applied\n'))
1245 1245 return 0
1246 1246
1247 1247 # Following the above example, starting at 'top' of B:
1248 1248 # qpush should be performed (pushes C), but a subsequent
1249 1249 # qpush without an argument is an error (nothing to
1250 1250 # apply). This allows a loop of "...while hg qpush..." to
1251 1251 # work as it detects an error when done
1252 1252 start = self.seriesend()
1253 1253 if start == len(self.series):
1254 1254 self.ui.warn(_('patch series already fully applied\n'))
1255 1255 return 1
1256 1256 if not force and not keepchanges:
1257 1257 self.checklocalchanges(repo, refresh=self.applied)
1258 1258
1259 1259 if exact:
1260 1260 if keepchanges:
1261 1261 raise util.Abort(
1262 1262 _("cannot use --exact and --keep-changes together"))
1263 1263 if move:
1264 1264 raise util.Abort(_('cannot use --exact and --move '
1265 1265 'together'))
1266 1266 if self.applied:
1267 1267 raise util.Abort(_('cannot push --exact with applied '
1268 1268 'patches'))
1269 1269 root = self.series[start]
1270 1270 target = patchheader(self.join(root), self.plainmode).parent
1271 1271 if not target:
1272 1272 raise util.Abort(
1273 1273 _("%s does not have a parent recorded") % root)
1274 1274 if not repo[target] == repo['.']:
1275 1275 hg.update(repo, target)
1276 1276
1277 1277 if move:
1278 1278 if not patch:
1279 1279 raise util.Abort(_("please specify the patch to move"))
1280 1280 for fullstart, rpn in enumerate(self.fullseries):
1281 1281 # strip markers for patch guards
1282 1282 if self.guard_re.split(rpn, 1)[0] == self.series[start]:
1283 1283 break
1284 1284 for i, rpn in enumerate(self.fullseries[fullstart:]):
1285 1285 # strip markers for patch guards
1286 1286 if self.guard_re.split(rpn, 1)[0] == patch:
1287 1287 break
1288 1288 index = fullstart + i
1289 1289 assert index < len(self.fullseries)
1290 1290 fullpatch = self.fullseries[index]
1291 1291 del self.fullseries[index]
1292 1292 self.fullseries.insert(fullstart, fullpatch)
1293 1293 self.parseseries()
1294 1294 self.seriesdirty = True
1295 1295
1296 1296 self.applieddirty = True
1297 1297 if start > 0:
1298 1298 self.checktoppatch(repo)
1299 1299 if not patch:
1300 1300 patch = self.series[start]
1301 1301 end = start + 1
1302 1302 else:
1303 1303 end = self.series.index(patch, start) + 1
1304 1304
1305 1305 tobackup = set()
1306 1306 if (not nobackup and force) or keepchanges:
1307 1307 m, a, r, d = self.checklocalchanges(repo, force=True)
1308 1308 if keepchanges:
1309 1309 tobackup.update(m + a + r + d)
1310 1310 else:
1311 1311 tobackup.update(m + a)
1312 1312
1313 1313 s = self.series[start:end]
1314 1314 all_files = set()
1315 1315 try:
1316 1316 if mergeq:
1317 1317 ret = self.mergepatch(repo, mergeq, s, diffopts)
1318 1318 else:
1319 1319 ret = self.apply(repo, s, list, all_files=all_files,
1320 1320 tobackup=tobackup, keepchanges=keepchanges)
1321 1321 except: # re-raises
1322 1322 self.ui.warn(_('cleaning up working directory...'))
1323 1323 node = repo.dirstate.p1()
1324 1324 hg.revert(repo, node, None)
1325 1325 # only remove unknown files that we know we touched or
1326 1326 # created while patching
1327 1327 for f in all_files:
1328 1328 if f not in repo.dirstate:
1329 1329 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
1330 1330 self.ui.warn(_('done\n'))
1331 1331 raise
1332 1332
1333 1333 if not self.applied:
1334 1334 return ret[0]
1335 1335 top = self.applied[-1].name
1336 1336 if ret[0] and ret[0] > 1:
1337 1337 msg = _("errors during apply, please fix and refresh %s\n")
1338 1338 self.ui.write(msg % top)
1339 1339 else:
1340 1340 self.ui.write(_("now at: %s\n") % top)
1341 1341 return ret[0]
1342 1342
1343 1343 finally:
1344 1344 wlock.release()
1345 1345
1346 1346 def pop(self, repo, patch=None, force=False, update=True, all=False,
1347 1347 nobackup=False, keepchanges=False):
1348 1348 self.checkkeepchanges(keepchanges, force)
1349 1349 wlock = repo.wlock()
1350 1350 try:
1351 1351 if patch:
1352 1352 # index, rev, patch
1353 1353 info = self.isapplied(patch)
1354 1354 if not info:
1355 1355 patch = self.lookup(patch)
1356 1356 info = self.isapplied(patch)
1357 1357 if not info:
1358 1358 raise util.Abort(_("patch %s is not applied") % patch)
1359 1359
1360 1360 if not self.applied:
1361 1361 # Allow qpop -a to work repeatedly,
1362 1362 # but not qpop without an argument
1363 1363 self.ui.warn(_("no patches applied\n"))
1364 1364 return not all
1365 1365
1366 1366 if all:
1367 1367 start = 0
1368 1368 elif patch:
1369 1369 start = info[0] + 1
1370 1370 else:
1371 1371 start = len(self.applied) - 1
1372 1372
1373 1373 if start >= len(self.applied):
1374 1374 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1375 1375 return
1376 1376
1377 1377 if not update:
1378 1378 parents = repo.dirstate.parents()
1379 1379 rr = [x.node for x in self.applied]
1380 1380 for p in parents:
1381 1381 if p in rr:
1382 1382 self.ui.warn(_("qpop: forcing dirstate update\n"))
1383 1383 update = True
1384 1384 else:
1385 1385 parents = [p.node() for p in repo[None].parents()]
1386 1386 needupdate = False
1387 1387 for entry in self.applied[start:]:
1388 1388 if entry.node in parents:
1389 1389 needupdate = True
1390 1390 break
1391 1391 update = needupdate
1392 1392
1393 1393 tobackup = set()
1394 1394 if update:
1395 1395 m, a, r, d = self.checklocalchanges(
1396 1396 repo, force=force or keepchanges)
1397 1397 if force:
1398 1398 if not nobackup:
1399 1399 tobackup.update(m + a)
1400 1400 elif keepchanges:
1401 1401 tobackup.update(m + a + r + d)
1402 1402
1403 1403 self.applieddirty = True
1404 1404 end = len(self.applied)
1405 1405 rev = self.applied[start].node
1406 1406
1407 1407 try:
1408 1408 heads = repo.changelog.heads(rev)
1409 1409 except error.LookupError:
1410 1410 node = short(rev)
1411 1411 raise util.Abort(_('trying to pop unknown node %s') % node)
1412 1412
1413 1413 if heads != [self.applied[-1].node]:
1414 1414 raise util.Abort(_("popping would remove a revision not "
1415 1415 "managed by this patch queue"))
1416 1416 if not repo[self.applied[-1].node].mutable():
1417 1417 raise util.Abort(
1418 1418 _("popping would remove an immutable revision"),
1419 1419 hint=_('see "hg help phases" for details'))
1420 1420
1421 1421 # we know there are no local changes, so we can make a simplified
1422 1422 # form of hg.update.
1423 1423 if update:
1424 1424 qp = self.qparents(repo, rev)
1425 1425 ctx = repo[qp]
1426 1426 m, a, r, d = repo.status(qp, '.')[:4]
1427 1427 if d:
1428 1428 raise util.Abort(_("deletions found between repo revs"))
1429 1429
1430 1430 tobackup = set(a + m + r) & tobackup
1431 1431 if keepchanges and tobackup:
1432 1432 raise util.Abort(_("local changes found, refresh first"))
1433 1433 self.backup(repo, tobackup)
1434 1434
1435 1435 for f in a:
1436 1436 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
1437 1437 repo.dirstate.drop(f)
1438 1438 for f in m + r:
1439 1439 fctx = ctx[f]
1440 1440 repo.wwrite(f, fctx.data(), fctx.flags())
1441 1441 repo.dirstate.normal(f)
1442 1442 repo.setparents(qp, nullid)
1443 1443 for patch in reversed(self.applied[start:end]):
1444 1444 self.ui.status(_("popping %s\n") % patch.name)
1445 1445 del self.applied[start:end]
1446 1446 strip(self.ui, repo, [rev], update=False, backup='strip')
1447 1447 for s, state in repo['.'].substate.items():
1448 1448 repo['.'].sub(s).get(state)
1449 1449 if self.applied:
1450 1450 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1451 1451 else:
1452 1452 self.ui.write(_("patch queue now empty\n"))
1453 1453 finally:
1454 1454 wlock.release()
1455 1455
1456 1456 def diff(self, repo, pats, opts):
1457 1457 top, patch = self.checktoppatch(repo)
1458 1458 if not top:
1459 1459 self.ui.write(_("no patches applied\n"))
1460 1460 return
1461 1461 qp = self.qparents(repo, top)
1462 1462 if opts.get('reverse'):
1463 1463 node1, node2 = None, qp
1464 1464 else:
1465 1465 node1, node2 = qp, None
1466 1466 diffopts = self.diffopts(opts, patch)
1467 1467 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1468 1468
1469 1469 def refresh(self, repo, pats=None, **opts):
1470 1470 if not self.applied:
1471 1471 self.ui.write(_("no patches applied\n"))
1472 1472 return 1
1473 1473 msg = opts.get('msg', '').rstrip()
1474 1474 newuser = opts.get('user')
1475 1475 newdate = opts.get('date')
1476 1476 if newdate:
1477 1477 newdate = '%d %d' % util.parsedate(newdate)
1478 1478 wlock = repo.wlock()
1479 1479
1480 1480 try:
1481 1481 self.checktoppatch(repo)
1482 1482 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1483 1483 if repo.changelog.heads(top) != [top]:
1484 1484 raise util.Abort(_("cannot refresh a revision with children"))
1485 1485 if not repo[top].mutable():
1486 1486 raise util.Abort(_("cannot refresh immutable revision"),
1487 1487 hint=_('see "hg help phases" for details'))
1488 1488
1489 1489 cparents = repo.changelog.parents(top)
1490 1490 patchparent = self.qparents(repo, top)
1491 1491
1492 1492 inclsubs = checksubstate(repo, hex(patchparent))
1493 1493 if inclsubs:
1494 1494 inclsubs.append('.hgsubstate')
1495 1495 substatestate = repo.dirstate['.hgsubstate']
1496 1496
1497 1497 ph = patchheader(self.join(patchfn), self.plainmode)
1498 1498 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1499 1499 if msg:
1500 1500 ph.setmessage(msg)
1501 1501 if newuser:
1502 1502 ph.setuser(newuser)
1503 1503 if newdate:
1504 1504 ph.setdate(newdate)
1505 1505 ph.setparent(hex(patchparent))
1506 1506
1507 1507 # only commit new patch when write is complete
1508 1508 patchf = self.opener(patchfn, 'w', atomictemp=True)
1509 1509
1510 1510 comments = str(ph)
1511 1511 if comments:
1512 1512 patchf.write(comments)
1513 1513
1514 1514 # update the dirstate in place, strip off the qtip commit
1515 1515 # and then commit.
1516 1516 #
1517 1517 # this should really read:
1518 1518 # mm, dd, aa = repo.status(top, patchparent)[:3]
1519 1519 # but we do it backwards to take advantage of manifest/changelog
1520 1520 # caching against the next repo.status call
1521 1521 mm, aa, dd = repo.status(patchparent, top)[:3]
1522 1522 changes = repo.changelog.read(top)
1523 1523 man = repo.manifest.read(changes[0])
1524 1524 aaa = aa[:]
1525 1525 matchfn = scmutil.match(repo[None], pats, opts)
1526 1526 # in short mode, we only diff the files included in the
1527 1527 # patch already plus specified files
1528 1528 if opts.get('short'):
1529 1529 # if amending a patch, we start with existing
1530 1530 # files plus specified files - unfiltered
1531 1531 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1532 1532 # filter with include/exclude options
1533 1533 matchfn = scmutil.match(repo[None], opts=opts)
1534 1534 else:
1535 1535 match = scmutil.matchall(repo)
1536 1536 m, a, r, d = repo.status(match=match)[:4]
1537 1537 mm = set(mm)
1538 1538 aa = set(aa)
1539 1539 dd = set(dd)
1540 1540
1541 1541 # we might end up with files that were added between
1542 1542 # qtip and the dirstate parent, but then changed in the
1543 1543 # local dirstate. in this case, we want them to only
1544 1544 # show up in the added section
1545 1545 for x in m:
1546 1546 if x not in aa:
1547 1547 mm.add(x)
1548 1548 # we might end up with files added by the local dirstate that
1549 1549 # were deleted by the patch. In this case, they should only
1550 1550 # show up in the changed section.
1551 1551 for x in a:
1552 1552 if x in dd:
1553 1553 dd.remove(x)
1554 1554 mm.add(x)
1555 1555 else:
1556 1556 aa.add(x)
1557 1557 # make sure any files deleted in the local dirstate
1558 1558 # are not in the add or change column of the patch
1559 1559 forget = []
1560 1560 for x in d + r:
1561 1561 if x in aa:
1562 1562 aa.remove(x)
1563 1563 forget.append(x)
1564 1564 continue
1565 1565 else:
1566 1566 mm.discard(x)
1567 1567 dd.add(x)
1568 1568
1569 1569 m = list(mm)
1570 1570 r = list(dd)
1571 1571 a = list(aa)
1572 1572
1573 1573 # create 'match' that includes the files to be recommitted.
1574 1574 # apply matchfn via repo.status to ensure correct case handling.
1575 1575 cm, ca, cr, cd = repo.status(patchparent, match=matchfn)[:4]
1576 1576 allmatches = set(cm + ca + cr + cd)
1577 1577 refreshchanges = [x.intersection(allmatches) for x in (mm, aa, dd)]
1578 1578
1579 1579 files = set(inclsubs)
1580 1580 for x in refreshchanges:
1581 1581 files.update(x)
1582 1582 match = scmutil.matchfiles(repo, files)
1583 1583
1584 1584 bmlist = repo[top].bookmarks()
1585 1585
1586 1586 try:
1587 1587 if diffopts.git or diffopts.upgrade:
1588 1588 copies = {}
1589 1589 for dst in a:
1590 1590 src = repo.dirstate.copied(dst)
1591 1591 # during qfold, the source file for copies may
1592 1592 # be removed. Treat this as a simple add.
1593 1593 if src is not None and src in repo.dirstate:
1594 1594 copies.setdefault(src, []).append(dst)
1595 1595 repo.dirstate.add(dst)
1596 1596 # remember the copies between patchparent and qtip
1597 1597 for dst in aaa:
1598 1598 f = repo.file(dst)
1599 1599 src = f.renamed(man[dst])
1600 1600 if src:
1601 1601 copies.setdefault(src[0], []).extend(
1602 1602 copies.get(dst, []))
1603 1603 if dst in a:
1604 1604 copies[src[0]].append(dst)
1605 1605 # we can't copy a file created by the patch itself
1606 1606 if dst in copies:
1607 1607 del copies[dst]
1608 1608 for src, dsts in copies.iteritems():
1609 1609 for dst in dsts:
1610 1610 repo.dirstate.copy(src, dst)
1611 1611 else:
1612 1612 for dst in a:
1613 1613 repo.dirstate.add(dst)
1614 1614 # Drop useless copy information
1615 1615 for f in list(repo.dirstate.copies()):
1616 1616 repo.dirstate.copy(None, f)
1617 1617 for f in r:
1618 1618 repo.dirstate.remove(f)
1619 1619 # if the patch excludes a modified file, mark that
1620 1620 # file with mtime=0 so status can see it.
1621 1621 mm = []
1622 1622 for i in xrange(len(m) - 1, -1, -1):
1623 1623 if not matchfn(m[i]):
1624 1624 mm.append(m[i])
1625 1625 del m[i]
1626 1626 for f in m:
1627 1627 repo.dirstate.normal(f)
1628 1628 for f in mm:
1629 1629 repo.dirstate.normallookup(f)
1630 1630 for f in forget:
1631 1631 repo.dirstate.drop(f)
1632 1632
1633 1633 if not msg:
1634 1634 if not ph.message:
1635 1635 message = "[mq]: %s\n" % patchfn
1636 1636 else:
1637 1637 message = "\n".join(ph.message)
1638 1638 else:
1639 1639 message = msg
1640 1640
1641 1641 user = ph.user or changes[1]
1642 1642
1643 1643 oldphase = repo[top].phase()
1644 1644
1645 1645 # assumes strip can roll itself back if interrupted
1646 1646 repo.setparents(*cparents)
1647 1647 self.applied.pop()
1648 1648 self.applieddirty = True
1649 1649 strip(self.ui, repo, [top], update=False, backup='strip')
1650 1650 except: # re-raises
1651 1651 repo.dirstate.invalidate()
1652 1652 raise
1653 1653
1654 1654 try:
1655 1655 # might be nice to attempt to roll back strip after this
1656 1656
1657 1657 # Ensure we create a new changeset in the same phase than
1658 1658 # the old one.
1659 1659 n = newcommit(repo, oldphase, message, user, ph.date,
1660 1660 match=match, force=True)
1661 1661 # only write patch after a successful commit
1662 1662 c = [list(x) for x in refreshchanges]
1663 1663 if inclsubs:
1664 1664 self.putsubstate2changes(substatestate, c)
1665 1665 chunks = patchmod.diff(repo, patchparent,
1666 1666 changes=c, opts=diffopts)
1667 1667 for chunk in chunks:
1668 1668 patchf.write(chunk)
1669 1669 patchf.close()
1670 1670
1671 1671 marks = repo._bookmarks
1672 1672 for bm in bmlist:
1673 1673 marks[bm] = n
1674 1674 marks.write()
1675 1675
1676 1676 self.applied.append(statusentry(n, patchfn))
1677 1677 except: # re-raises
1678 1678 ctx = repo[cparents[0]]
1679 1679 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1680 1680 self.savedirty()
1681 1681 self.ui.warn(_('refresh interrupted while patch was popped! '
1682 1682 '(revert --all, qpush to recover)\n'))
1683 1683 raise
1684 1684 finally:
1685 1685 wlock.release()
1686 1686 self.removeundo(repo)
1687 1687
1688 1688 def init(self, repo, create=False):
1689 1689 if not create and os.path.isdir(self.path):
1690 1690 raise util.Abort(_("patch queue directory already exists"))
1691 1691 try:
1692 1692 os.mkdir(self.path)
1693 1693 except OSError, inst:
1694 1694 if inst.errno != errno.EEXIST or not create:
1695 1695 raise
1696 1696 if create:
1697 1697 return self.qrepo(create=True)
1698 1698
1699 1699 def unapplied(self, repo, patch=None):
1700 1700 if patch and patch not in self.series:
1701 1701 raise util.Abort(_("patch %s is not in series file") % patch)
1702 1702 if not patch:
1703 1703 start = self.seriesend()
1704 1704 else:
1705 1705 start = self.series.index(patch) + 1
1706 1706 unapplied = []
1707 1707 for i in xrange(start, len(self.series)):
1708 1708 pushable, reason = self.pushable(i)
1709 1709 if pushable:
1710 1710 unapplied.append((i, self.series[i]))
1711 1711 self.explainpushable(i)
1712 1712 return unapplied
1713 1713
1714 1714 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1715 1715 summary=False):
1716 1716 def displayname(pfx, patchname, state):
1717 1717 if pfx:
1718 1718 self.ui.write(pfx)
1719 1719 if summary:
1720 1720 ph = patchheader(self.join(patchname), self.plainmode)
1721 1721 msg = ph.message and ph.message[0] or ''
1722 1722 if self.ui.formatted():
1723 1723 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1724 1724 if width > 0:
1725 1725 msg = util.ellipsis(msg, width)
1726 1726 else:
1727 1727 msg = ''
1728 1728 self.ui.write(patchname, label='qseries.' + state)
1729 1729 self.ui.write(': ')
1730 1730 self.ui.write(msg, label='qseries.message.' + state)
1731 1731 else:
1732 1732 self.ui.write(patchname, label='qseries.' + state)
1733 1733 self.ui.write('\n')
1734 1734
1735 1735 applied = set([p.name for p in self.applied])
1736 1736 if length is None:
1737 1737 length = len(self.series) - start
1738 1738 if not missing:
1739 1739 if self.ui.verbose:
1740 1740 idxwidth = len(str(start + length - 1))
1741 1741 for i in xrange(start, start + length):
1742 1742 patch = self.series[i]
1743 1743 if patch in applied:
1744 1744 char, state = 'A', 'applied'
1745 1745 elif self.pushable(i)[0]:
1746 1746 char, state = 'U', 'unapplied'
1747 1747 else:
1748 1748 char, state = 'G', 'guarded'
1749 1749 pfx = ''
1750 1750 if self.ui.verbose:
1751 1751 pfx = '%*d %s ' % (idxwidth, i, char)
1752 1752 elif status and status != char:
1753 1753 continue
1754 1754 displayname(pfx, patch, state)
1755 1755 else:
1756 1756 msng_list = []
1757 1757 for root, dirs, files in os.walk(self.path):
1758 1758 d = root[len(self.path) + 1:]
1759 1759 for f in files:
1760 1760 fl = os.path.join(d, f)
1761 1761 if (fl not in self.series and
1762 1762 fl not in (self.statuspath, self.seriespath,
1763 1763 self.guardspath)
1764 1764 and not fl.startswith('.')):
1765 1765 msng_list.append(fl)
1766 1766 for x in sorted(msng_list):
1767 1767 pfx = self.ui.verbose and ('D ') or ''
1768 1768 displayname(pfx, x, 'missing')
1769 1769
1770 1770 def issaveline(self, l):
1771 1771 if l.name == '.hg.patches.save.line':
1772 1772 return True
1773 1773
1774 1774 def qrepo(self, create=False):
1775 1775 ui = self.baseui.copy()
1776 1776 if create or os.path.isdir(self.join(".hg")):
1777 1777 return hg.repository(ui, path=self.path, create=create)
1778 1778
1779 1779 def restore(self, repo, rev, delete=None, qupdate=None):
1780 1780 desc = repo[rev].description().strip()
1781 1781 lines = desc.splitlines()
1782 1782 i = 0
1783 1783 datastart = None
1784 1784 series = []
1785 1785 applied = []
1786 1786 qpp = None
1787 1787 for i, line in enumerate(lines):
1788 1788 if line == 'Patch Data:':
1789 1789 datastart = i + 1
1790 1790 elif line.startswith('Dirstate:'):
1791 1791 l = line.rstrip()
1792 1792 l = l[10:].split(' ')
1793 1793 qpp = [bin(x) for x in l]
1794 1794 elif datastart is not None:
1795 1795 l = line.rstrip()
1796 1796 n, name = l.split(':', 1)
1797 1797 if n:
1798 1798 applied.append(statusentry(bin(n), name))
1799 1799 else:
1800 1800 series.append(l)
1801 1801 if datastart is None:
1802 1802 self.ui.warn(_("no saved patch data found\n"))
1803 1803 return 1
1804 1804 self.ui.warn(_("restoring status: %s\n") % lines[0])
1805 1805 self.fullseries = series
1806 1806 self.applied = applied
1807 1807 self.parseseries()
1808 1808 self.seriesdirty = True
1809 1809 self.applieddirty = True
1810 1810 heads = repo.changelog.heads()
1811 1811 if delete:
1812 1812 if rev not in heads:
1813 1813 self.ui.warn(_("save entry has children, leaving it alone\n"))
1814 1814 else:
1815 1815 self.ui.warn(_("removing save entry %s\n") % short(rev))
1816 1816 pp = repo.dirstate.parents()
1817 1817 if rev in pp:
1818 1818 update = True
1819 1819 else:
1820 1820 update = False
1821 1821 strip(self.ui, repo, [rev], update=update, backup='strip')
1822 1822 if qpp:
1823 1823 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1824 1824 (short(qpp[0]), short(qpp[1])))
1825 1825 if qupdate:
1826 1826 self.ui.status(_("updating queue directory\n"))
1827 1827 r = self.qrepo()
1828 1828 if not r:
1829 1829 self.ui.warn(_("unable to load queue repository\n"))
1830 1830 return 1
1831 1831 hg.clean(r, qpp[0])
1832 1832
1833 1833 def save(self, repo, msg=None):
1834 1834 if not self.applied:
1835 1835 self.ui.warn(_("save: no patches applied, exiting\n"))
1836 1836 return 1
1837 1837 if self.issaveline(self.applied[-1]):
1838 1838 self.ui.warn(_("status is already saved\n"))
1839 1839 return 1
1840 1840
1841 1841 if not msg:
1842 1842 msg = _("hg patches saved state")
1843 1843 else:
1844 1844 msg = "hg patches: " + msg.rstrip('\r\n')
1845 1845 r = self.qrepo()
1846 1846 if r:
1847 1847 pp = r.dirstate.parents()
1848 1848 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1849 1849 msg += "\n\nPatch Data:\n"
1850 1850 msg += ''.join('%s\n' % x for x in self.applied)
1851 1851 msg += ''.join(':%s\n' % x for x in self.fullseries)
1852 1852 n = repo.commit(msg, force=True)
1853 1853 if not n:
1854 1854 self.ui.warn(_("repo commit failed\n"))
1855 1855 return 1
1856 1856 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1857 1857 self.applieddirty = True
1858 1858 self.removeundo(repo)
1859 1859
1860 1860 def fullseriesend(self):
1861 1861 if self.applied:
1862 1862 p = self.applied[-1].name
1863 1863 end = self.findseries(p)
1864 1864 if end is None:
1865 1865 return len(self.fullseries)
1866 1866 return end + 1
1867 1867 return 0
1868 1868
1869 1869 def seriesend(self, all_patches=False):
1870 1870 """If all_patches is False, return the index of the next pushable patch
1871 1871 in the series, or the series length. If all_patches is True, return the
1872 1872 index of the first patch past the last applied one.
1873 1873 """
1874 1874 end = 0
1875 1875 def nextpatch(start):
1876 1876 if all_patches or start >= len(self.series):
1877 1877 return start
1878 1878 for i in xrange(start, len(self.series)):
1879 1879 p, reason = self.pushable(i)
1880 1880 if p:
1881 1881 return i
1882 1882 self.explainpushable(i)
1883 1883 return len(self.series)
1884 1884 if self.applied:
1885 1885 p = self.applied[-1].name
1886 1886 try:
1887 1887 end = self.series.index(p)
1888 1888 except ValueError:
1889 1889 return 0
1890 1890 return nextpatch(end + 1)
1891 1891 return nextpatch(end)
1892 1892
1893 1893 def appliedname(self, index):
1894 1894 pname = self.applied[index].name
1895 1895 if not self.ui.verbose:
1896 1896 p = pname
1897 1897 else:
1898 1898 p = str(self.series.index(pname)) + " " + pname
1899 1899 return p
1900 1900
1901 1901 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1902 1902 force=None, git=False):
1903 1903 def checkseries(patchname):
1904 1904 if patchname in self.series:
1905 1905 raise util.Abort(_('patch %s is already in the series file')
1906 1906 % patchname)
1907 1907
1908 1908 if rev:
1909 1909 if files:
1910 1910 raise util.Abort(_('option "-r" not valid when importing '
1911 1911 'files'))
1912 1912 rev = scmutil.revrange(repo, rev)
1913 1913 rev.sort(reverse=True)
1914 1914 elif not files:
1915 1915 raise util.Abort(_('no files or revisions specified'))
1916 1916 if (len(files) > 1 or len(rev) > 1) and patchname:
1917 1917 raise util.Abort(_('option "-n" not valid when importing multiple '
1918 1918 'patches'))
1919 1919 imported = []
1920 1920 if rev:
1921 1921 # If mq patches are applied, we can only import revisions
1922 1922 # that form a linear path to qbase.
1923 1923 # Otherwise, they should form a linear path to a head.
1924 1924 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1925 1925 if len(heads) > 1:
1926 1926 raise util.Abort(_('revision %d is the root of more than one '
1927 1927 'branch') % rev[-1])
1928 1928 if self.applied:
1929 1929 base = repo.changelog.node(rev[0])
1930 1930 if base in [n.node for n in self.applied]:
1931 1931 raise util.Abort(_('revision %d is already managed')
1932 1932 % rev[0])
1933 1933 if heads != [self.applied[-1].node]:
1934 1934 raise util.Abort(_('revision %d is not the parent of '
1935 1935 'the queue') % rev[0])
1936 1936 base = repo.changelog.rev(self.applied[0].node)
1937 1937 lastparent = repo.changelog.parentrevs(base)[0]
1938 1938 else:
1939 1939 if heads != [repo.changelog.node(rev[0])]:
1940 1940 raise util.Abort(_('revision %d has unmanaged children')
1941 1941 % rev[0])
1942 1942 lastparent = None
1943 1943
1944 1944 diffopts = self.diffopts({'git': git})
1945 1945 for r in rev:
1946 1946 if not repo[r].mutable():
1947 1947 raise util.Abort(_('revision %d is not mutable') % r,
1948 1948 hint=_('see "hg help phases" for details'))
1949 1949 p1, p2 = repo.changelog.parentrevs(r)
1950 1950 n = repo.changelog.node(r)
1951 1951 if p2 != nullrev:
1952 1952 raise util.Abort(_('cannot import merge revision %d') % r)
1953 1953 if lastparent and lastparent != r:
1954 1954 raise util.Abort(_('revision %d is not the parent of %d')
1955 1955 % (r, lastparent))
1956 1956 lastparent = p1
1957 1957
1958 1958 if not patchname:
1959 1959 patchname = normname('%d.diff' % r)
1960 1960 checkseries(patchname)
1961 1961 self.checkpatchname(patchname, force)
1962 1962 self.fullseries.insert(0, patchname)
1963 1963
1964 1964 patchf = self.opener(patchname, "w")
1965 1965 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1966 1966 patchf.close()
1967 1967
1968 1968 se = statusentry(n, patchname)
1969 1969 self.applied.insert(0, se)
1970 1970
1971 1971 self.added.append(patchname)
1972 1972 imported.append(patchname)
1973 1973 patchname = None
1974 1974 if rev and repo.ui.configbool('mq', 'secret', False):
1975 1975 # if we added anything with --rev, we must move the secret root
1976 1976 phases.retractboundary(repo, phases.secret, [n])
1977 1977 self.parseseries()
1978 1978 self.applieddirty = True
1979 1979 self.seriesdirty = True
1980 1980
1981 1981 for i, filename in enumerate(files):
1982 1982 if existing:
1983 1983 if filename == '-':
1984 1984 raise util.Abort(_('-e is incompatible with import from -'))
1985 1985 filename = normname(filename)
1986 1986 self.checkreservedname(filename)
1987 1987 originpath = self.join(filename)
1988 1988 if not os.path.isfile(originpath):
1989 1989 raise util.Abort(_("patch %s does not exist") % filename)
1990 1990
1991 1991 if patchname:
1992 1992 self.checkpatchname(patchname, force)
1993 1993
1994 1994 self.ui.write(_('renaming %s to %s\n')
1995 1995 % (filename, patchname))
1996 1996 util.rename(originpath, self.join(patchname))
1997 1997 else:
1998 1998 patchname = filename
1999 1999
2000 2000 else:
2001 2001 if filename == '-' and not patchname:
2002 2002 raise util.Abort(_('need --name to import a patch from -'))
2003 2003 elif not patchname:
2004 2004 patchname = normname(os.path.basename(filename.rstrip('/')))
2005 2005 self.checkpatchname(patchname, force)
2006 2006 try:
2007 2007 if filename == '-':
2008 2008 text = self.ui.fin.read()
2009 2009 else:
2010 2010 fp = hg.openpath(self.ui, filename)
2011 2011 text = fp.read()
2012 2012 fp.close()
2013 2013 except (OSError, IOError):
2014 2014 raise util.Abort(_("unable to read file %s") % filename)
2015 2015 patchf = self.opener(patchname, "w")
2016 2016 patchf.write(text)
2017 2017 patchf.close()
2018 2018 if not force:
2019 2019 checkseries(patchname)
2020 2020 if patchname not in self.series:
2021 2021 index = self.fullseriesend() + i
2022 2022 self.fullseries[index:index] = [patchname]
2023 2023 self.parseseries()
2024 2024 self.seriesdirty = True
2025 2025 self.ui.warn(_("adding %s to series file\n") % patchname)
2026 2026 self.added.append(patchname)
2027 2027 imported.append(patchname)
2028 2028 patchname = None
2029 2029
2030 2030 self.removeundo(repo)
2031 2031 return imported
2032 2032
2033 2033 def fixkeepchangesopts(ui, opts):
2034 2034 if (not ui.configbool('mq', 'keepchanges') or opts.get('force')
2035 2035 or opts.get('exact')):
2036 2036 return opts
2037 2037 opts = dict(opts)
2038 2038 opts['keep_changes'] = True
2039 2039 return opts
2040 2040
2041 2041 @command("qdelete|qremove|qrm",
2042 2042 [('k', 'keep', None, _('keep patch file')),
2043 2043 ('r', 'rev', [],
2044 2044 _('stop managing a revision (DEPRECATED)'), _('REV'))],
2045 2045 _('hg qdelete [-k] [PATCH]...'))
2046 2046 def delete(ui, repo, *patches, **opts):
2047 2047 """remove patches from queue
2048 2048
2049 2049 The patches must not be applied, and at least one patch is required. Exact
2050 2050 patch identifiers must be given. With -k/--keep, the patch files are
2051 2051 preserved in the patch directory.
2052 2052
2053 2053 To stop managing a patch and move it into permanent history,
2054 2054 use the :hg:`qfinish` command."""
2055 2055 q = repo.mq
2056 2056 q.delete(repo, patches, opts)
2057 2057 q.savedirty()
2058 2058 return 0
2059 2059
2060 2060 @command("qapplied",
2061 2061 [('1', 'last', None, _('show only the preceding applied patch'))
2062 2062 ] + seriesopts,
2063 2063 _('hg qapplied [-1] [-s] [PATCH]'))
2064 2064 def applied(ui, repo, patch=None, **opts):
2065 2065 """print the patches already applied
2066 2066
2067 2067 Returns 0 on success."""
2068 2068
2069 2069 q = repo.mq
2070 2070
2071 2071 if patch:
2072 2072 if patch not in q.series:
2073 2073 raise util.Abort(_("patch %s is not in series file") % patch)
2074 2074 end = q.series.index(patch) + 1
2075 2075 else:
2076 2076 end = q.seriesend(True)
2077 2077
2078 2078 if opts.get('last') and not end:
2079 2079 ui.write(_("no patches applied\n"))
2080 2080 return 1
2081 2081 elif opts.get('last') and end == 1:
2082 2082 ui.write(_("only one patch applied\n"))
2083 2083 return 1
2084 2084 elif opts.get('last'):
2085 2085 start = end - 2
2086 2086 end = 1
2087 2087 else:
2088 2088 start = 0
2089 2089
2090 2090 q.qseries(repo, length=end, start=start, status='A',
2091 2091 summary=opts.get('summary'))
2092 2092
2093 2093
2094 2094 @command("qunapplied",
2095 2095 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
2096 2096 _('hg qunapplied [-1] [-s] [PATCH]'))
2097 2097 def unapplied(ui, repo, patch=None, **opts):
2098 2098 """print the patches not yet applied
2099 2099
2100 2100 Returns 0 on success."""
2101 2101
2102 2102 q = repo.mq
2103 2103 if patch:
2104 2104 if patch not in q.series:
2105 2105 raise util.Abort(_("patch %s is not in series file") % patch)
2106 2106 start = q.series.index(patch) + 1
2107 2107 else:
2108 2108 start = q.seriesend(True)
2109 2109
2110 2110 if start == len(q.series) and opts.get('first'):
2111 2111 ui.write(_("all patches applied\n"))
2112 2112 return 1
2113 2113
2114 2114 length = opts.get('first') and 1 or None
2115 2115 q.qseries(repo, start=start, length=length, status='U',
2116 2116 summary=opts.get('summary'))
2117 2117
2118 2118 @command("qimport",
2119 2119 [('e', 'existing', None, _('import file in patch directory')),
2120 2120 ('n', 'name', '',
2121 2121 _('name of patch file'), _('NAME')),
2122 2122 ('f', 'force', None, _('overwrite existing files')),
2123 2123 ('r', 'rev', [],
2124 2124 _('place existing revisions under mq control'), _('REV')),
2125 2125 ('g', 'git', None, _('use git extended diff format')),
2126 2126 ('P', 'push', None, _('qpush after importing'))],
2127 2127 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... [FILE]...'))
2128 2128 def qimport(ui, repo, *filename, **opts):
2129 2129 """import a patch or existing changeset
2130 2130
2131 2131 The patch is inserted into the series after the last applied
2132 2132 patch. If no patches have been applied, qimport prepends the patch
2133 2133 to the series.
2134 2134
2135 2135 The patch will have the same name as its source file unless you
2136 2136 give it a new one with -n/--name.
2137 2137
2138 2138 You can register an existing patch inside the patch directory with
2139 2139 the -e/--existing flag.
2140 2140
2141 2141 With -f/--force, an existing patch of the same name will be
2142 2142 overwritten.
2143 2143
2144 2144 An existing changeset may be placed under mq control with -r/--rev
2145 2145 (e.g. qimport --rev . -n patch will place the current revision
2146 2146 under mq control). With -g/--git, patches imported with --rev will
2147 2147 use the git diff format. See the diffs help topic for information
2148 2148 on why this is important for preserving rename/copy information
2149 2149 and permission changes. Use :hg:`qfinish` to remove changesets
2150 2150 from mq control.
2151 2151
2152 2152 To import a patch from standard input, pass - as the patch file.
2153 2153 When importing from standard input, a patch name must be specified
2154 2154 using the --name flag.
2155 2155
2156 2156 To import an existing patch while renaming it::
2157 2157
2158 2158 hg qimport -e existing-patch -n new-name
2159 2159
2160 2160 Returns 0 if import succeeded.
2161 2161 """
2162 2162 lock = repo.lock() # cause this may move phase
2163 2163 try:
2164 2164 q = repo.mq
2165 2165 try:
2166 2166 imported = q.qimport(
2167 2167 repo, filename, patchname=opts.get('name'),
2168 2168 existing=opts.get('existing'), force=opts.get('force'),
2169 2169 rev=opts.get('rev'), git=opts.get('git'))
2170 2170 finally:
2171 2171 q.savedirty()
2172 2172 finally:
2173 2173 lock.release()
2174 2174
2175 2175 if imported and opts.get('push') and not opts.get('rev'):
2176 2176 return q.push(repo, imported[-1])
2177 2177 return 0
2178 2178
2179 2179 def qinit(ui, repo, create):
2180 2180 """initialize a new queue repository
2181 2181
2182 2182 This command also creates a series file for ordering patches, and
2183 2183 an mq-specific .hgignore file in the queue repository, to exclude
2184 2184 the status and guards files (these contain mostly transient state).
2185 2185
2186 2186 Returns 0 if initialization succeeded."""
2187 2187 q = repo.mq
2188 2188 r = q.init(repo, create)
2189 2189 q.savedirty()
2190 2190 if r:
2191 2191 if not os.path.exists(r.wjoin('.hgignore')):
2192 2192 fp = r.wopener('.hgignore', 'w')
2193 2193 fp.write('^\\.hg\n')
2194 2194 fp.write('^\\.mq\n')
2195 2195 fp.write('syntax: glob\n')
2196 2196 fp.write('status\n')
2197 2197 fp.write('guards\n')
2198 2198 fp.close()
2199 2199 if not os.path.exists(r.wjoin('series')):
2200 2200 r.wopener('series', 'w').close()
2201 2201 r[None].add(['.hgignore', 'series'])
2202 2202 commands.add(ui, r)
2203 2203 return 0
2204 2204
2205 2205 @command("^qinit",
2206 2206 [('c', 'create-repo', None, _('create queue repository'))],
2207 2207 _('hg qinit [-c]'))
2208 2208 def init(ui, repo, **opts):
2209 2209 """init a new queue repository (DEPRECATED)
2210 2210
2211 2211 The queue repository is unversioned by default. If
2212 2212 -c/--create-repo is specified, qinit will create a separate nested
2213 2213 repository for patches (qinit -c may also be run later to convert
2214 2214 an unversioned patch repository into a versioned one). You can use
2215 2215 qcommit to commit changes to this queue repository.
2216 2216
2217 2217 This command is deprecated. Without -c, it's implied by other relevant
2218 2218 commands. With -c, use :hg:`init --mq` instead."""
2219 2219 return qinit(ui, repo, create=opts.get('create_repo'))
2220 2220
2221 2221 @command("qclone",
2222 2222 [('', 'pull', None, _('use pull protocol to copy metadata')),
2223 2223 ('U', 'noupdate', None,
2224 2224 _('do not update the new working directories')),
2225 2225 ('', 'uncompressed', None,
2226 2226 _('use uncompressed transfer (fast over LAN)')),
2227 2227 ('p', 'patches', '',
2228 2228 _('location of source patch repository'), _('REPO')),
2229 2229 ] + commands.remoteopts,
2230 2230 _('hg qclone [OPTION]... SOURCE [DEST]'))
2231 2231 def clone(ui, source, dest=None, **opts):
2232 2232 '''clone main and patch repository at same time
2233 2233
2234 2234 If source is local, destination will have no patches applied. If
2235 2235 source is remote, this command can not check if patches are
2236 2236 applied in source, so cannot guarantee that patches are not
2237 2237 applied in destination. If you clone remote repository, be sure
2238 2238 before that it has no patches applied.
2239 2239
2240 2240 Source patch repository is looked for in <src>/.hg/patches by
2241 2241 default. Use -p <url> to change.
2242 2242
2243 2243 The patch directory must be a nested Mercurial repository, as
2244 2244 would be created by :hg:`init --mq`.
2245 2245
2246 2246 Return 0 on success.
2247 2247 '''
2248 2248 def patchdir(repo):
2249 2249 """compute a patch repo url from a repo object"""
2250 2250 url = repo.url()
2251 2251 if url.endswith('/'):
2252 2252 url = url[:-1]
2253 2253 return url + '/.hg/patches'
2254 2254
2255 2255 # main repo (destination and sources)
2256 2256 if dest is None:
2257 2257 dest = hg.defaultdest(source)
2258 2258 sr = hg.peer(ui, opts, ui.expandpath(source))
2259 2259
2260 2260 # patches repo (source only)
2261 2261 if opts.get('patches'):
2262 2262 patchespath = ui.expandpath(opts.get('patches'))
2263 2263 else:
2264 2264 patchespath = patchdir(sr)
2265 2265 try:
2266 2266 hg.peer(ui, opts, patchespath)
2267 2267 except error.RepoError:
2268 2268 raise util.Abort(_('versioned patch repository not found'
2269 2269 ' (see init --mq)'))
2270 2270 qbase, destrev = None, None
2271 2271 if sr.local():
2272 2272 repo = sr.local()
2273 2273 if repo.mq.applied and repo[qbase].phase() != phases.secret:
2274 2274 qbase = repo.mq.applied[0].node
2275 2275 if not hg.islocal(dest):
2276 2276 heads = set(repo.heads())
2277 2277 destrev = list(heads.difference(repo.heads(qbase)))
2278 2278 destrev.append(repo.changelog.parents(qbase)[0])
2279 2279 elif sr.capable('lookup'):
2280 2280 try:
2281 2281 qbase = sr.lookup('qbase')
2282 2282 except error.RepoError:
2283 2283 pass
2284 2284
2285 2285 ui.note(_('cloning main repository\n'))
2286 2286 sr, dr = hg.clone(ui, opts, sr.url(), dest,
2287 2287 pull=opts.get('pull'),
2288 2288 rev=destrev,
2289 2289 update=False,
2290 2290 stream=opts.get('uncompressed'))
2291 2291
2292 2292 ui.note(_('cloning patch repository\n'))
2293 2293 hg.clone(ui, opts, opts.get('patches') or patchdir(sr), patchdir(dr),
2294 2294 pull=opts.get('pull'), update=not opts.get('noupdate'),
2295 2295 stream=opts.get('uncompressed'))
2296 2296
2297 2297 if dr.local():
2298 2298 repo = dr.local()
2299 2299 if qbase:
2300 2300 ui.note(_('stripping applied patches from destination '
2301 2301 'repository\n'))
2302 2302 strip(ui, repo, [qbase], update=False, backup=None)
2303 2303 if not opts.get('noupdate'):
2304 2304 ui.note(_('updating destination repository\n'))
2305 2305 hg.update(repo, repo.changelog.tip())
2306 2306
2307 2307 @command("qcommit|qci",
2308 2308 commands.table["^commit|ci"][1],
2309 2309 _('hg qcommit [OPTION]... [FILE]...'))
2310 2310 def commit(ui, repo, *pats, **opts):
2311 2311 """commit changes in the queue repository (DEPRECATED)
2312 2312
2313 2313 This command is deprecated; use :hg:`commit --mq` instead."""
2314 2314 q = repo.mq
2315 2315 r = q.qrepo()
2316 2316 if not r:
2317 2317 raise util.Abort('no queue repository')
2318 2318 commands.commit(r.ui, r, *pats, **opts)
2319 2319
2320 2320 @command("qseries",
2321 2321 [('m', 'missing', None, _('print patches not in series')),
2322 2322 ] + seriesopts,
2323 2323 _('hg qseries [-ms]'))
2324 2324 def series(ui, repo, **opts):
2325 2325 """print the entire series file
2326 2326
2327 2327 Returns 0 on success."""
2328 2328 repo.mq.qseries(repo, missing=opts.get('missing'),
2329 2329 summary=opts.get('summary'))
2330 2330 return 0
2331 2331
2332 2332 @command("qtop", seriesopts, _('hg qtop [-s]'))
2333 2333 def top(ui, repo, **opts):
2334 2334 """print the name of the current patch
2335 2335
2336 2336 Returns 0 on success."""
2337 2337 q = repo.mq
2338 2338 t = q.applied and q.seriesend(True) or 0
2339 2339 if t:
2340 2340 q.qseries(repo, start=t - 1, length=1, status='A',
2341 2341 summary=opts.get('summary'))
2342 2342 else:
2343 2343 ui.write(_("no patches applied\n"))
2344 2344 return 1
2345 2345
2346 2346 @command("qnext", seriesopts, _('hg qnext [-s]'))
2347 2347 def next(ui, repo, **opts):
2348 2348 """print the name of the next pushable patch
2349 2349
2350 2350 Returns 0 on success."""
2351 2351 q = repo.mq
2352 2352 end = q.seriesend()
2353 2353 if end == len(q.series):
2354 2354 ui.write(_("all patches applied\n"))
2355 2355 return 1
2356 2356 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2357 2357
2358 2358 @command("qprev", seriesopts, _('hg qprev [-s]'))
2359 2359 def prev(ui, repo, **opts):
2360 2360 """print the name of the preceding applied patch
2361 2361
2362 2362 Returns 0 on success."""
2363 2363 q = repo.mq
2364 2364 l = len(q.applied)
2365 2365 if l == 1:
2366 2366 ui.write(_("only one patch applied\n"))
2367 2367 return 1
2368 2368 if not l:
2369 2369 ui.write(_("no patches applied\n"))
2370 2370 return 1
2371 2371 idx = q.series.index(q.applied[-2].name)
2372 2372 q.qseries(repo, start=idx, length=1, status='A',
2373 2373 summary=opts.get('summary'))
2374 2374
2375 2375 def setupheaderopts(ui, opts):
2376 2376 if not opts.get('user') and opts.get('currentuser'):
2377 2377 opts['user'] = ui.username()
2378 2378 if not opts.get('date') and opts.get('currentdate'):
2379 2379 opts['date'] = "%d %d" % util.makedate()
2380 2380
2381 2381 @command("^qnew",
2382 2382 [('e', 'edit', None, _('edit commit message')),
2383 2383 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2384 2384 ('g', 'git', None, _('use git extended diff format')),
2385 2385 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2386 2386 ('u', 'user', '',
2387 2387 _('add "From: <USER>" to patch'), _('USER')),
2388 2388 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2389 2389 ('d', 'date', '',
2390 2390 _('add "Date: <DATE>" to patch'), _('DATE'))
2391 2391 ] + commands.walkopts + commands.commitopts,
2392 2392 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2393 2393 def new(ui, repo, patch, *args, **opts):
2394 2394 """create a new patch
2395 2395
2396 2396 qnew creates a new patch on top of the currently-applied patch (if
2397 2397 any). The patch will be initialized with any outstanding changes
2398 2398 in the working directory. You may also use -I/--include,
2399 2399 -X/--exclude, and/or a list of files after the patch name to add
2400 2400 only changes to matching files to the new patch, leaving the rest
2401 2401 as uncommitted modifications.
2402 2402
2403 2403 -u/--user and -d/--date can be used to set the (given) user and
2404 2404 date, respectively. -U/--currentuser and -D/--currentdate set user
2405 2405 to current user and date to current date.
2406 2406
2407 2407 -e/--edit, -m/--message or -l/--logfile set the patch header as
2408 2408 well as the commit message. If none is specified, the header is
2409 2409 empty and the commit message is '[mq]: PATCH'.
2410 2410
2411 2411 Use the -g/--git option to keep the patch in the git extended diff
2412 2412 format. Read the diffs help topic for more information on why this
2413 2413 is important for preserving permission changes and copy/rename
2414 2414 information.
2415 2415
2416 2416 Returns 0 on successful creation of a new patch.
2417 2417 """
2418 2418 msg = cmdutil.logmessage(ui, opts)
2419 2419 def getmsg():
2420 2420 return ui.edit(msg, opts.get('user') or ui.username())
2421 2421 q = repo.mq
2422 2422 opts['msg'] = msg
2423 2423 if opts.get('edit'):
2424 2424 opts['msg'] = getmsg
2425 2425 else:
2426 2426 opts['msg'] = msg
2427 2427 setupheaderopts(ui, opts)
2428 2428 q.new(repo, patch, *args, **opts)
2429 2429 q.savedirty()
2430 2430 return 0
2431 2431
2432 2432 @command("^qrefresh",
2433 2433 [('e', 'edit', None, _('edit commit message')),
2434 2434 ('g', 'git', None, _('use git extended diff format')),
2435 2435 ('s', 'short', None,
2436 2436 _('refresh only files already in the patch and specified files')),
2437 2437 ('U', 'currentuser', None,
2438 2438 _('add/update author field in patch with current user')),
2439 2439 ('u', 'user', '',
2440 2440 _('add/update author field in patch with given user'), _('USER')),
2441 2441 ('D', 'currentdate', None,
2442 2442 _('add/update date field in patch with current date')),
2443 2443 ('d', 'date', '',
2444 2444 _('add/update date field in patch with given date'), _('DATE'))
2445 2445 ] + commands.walkopts + commands.commitopts,
2446 2446 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2447 2447 def refresh(ui, repo, *pats, **opts):
2448 2448 """update the current patch
2449 2449
2450 2450 If any file patterns are provided, the refreshed patch will
2451 2451 contain only the modifications that match those patterns; the
2452 2452 remaining modifications will remain in the working directory.
2453 2453
2454 2454 If -s/--short is specified, files currently included in the patch
2455 2455 will be refreshed just like matched files and remain in the patch.
2456 2456
2457 2457 If -e/--edit is specified, Mercurial will start your configured editor for
2458 2458 you to enter a message. In case qrefresh fails, you will find a backup of
2459 2459 your message in ``.hg/last-message.txt``.
2460 2460
2461 2461 hg add/remove/copy/rename work as usual, though you might want to
2462 2462 use git-style patches (-g/--git or [diff] git=1) to track copies
2463 2463 and renames. See the diffs help topic for more information on the
2464 2464 git diff format.
2465 2465
2466 2466 Returns 0 on success.
2467 2467 """
2468 2468 q = repo.mq
2469 2469 message = cmdutil.logmessage(ui, opts)
2470 2470 if opts.get('edit'):
2471 2471 if not q.applied:
2472 2472 ui.write(_("no patches applied\n"))
2473 2473 return 1
2474 2474 if message:
2475 2475 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2476 2476 patch = q.applied[-1].name
2477 2477 ph = patchheader(q.join(patch), q.plainmode)
2478 2478 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2479 2479 # We don't want to lose the patch message if qrefresh fails (issue2062)
2480 2480 repo.savecommitmessage(message)
2481 2481 setupheaderopts(ui, opts)
2482 2482 wlock = repo.wlock()
2483 2483 try:
2484 2484 ret = q.refresh(repo, pats, msg=message, **opts)
2485 2485 q.savedirty()
2486 2486 return ret
2487 2487 finally:
2488 2488 wlock.release()
2489 2489
2490 2490 @command("^qdiff",
2491 2491 commands.diffopts + commands.diffopts2 + commands.walkopts,
2492 2492 _('hg qdiff [OPTION]... [FILE]...'))
2493 2493 def diff(ui, repo, *pats, **opts):
2494 2494 """diff of the current patch and subsequent modifications
2495 2495
2496 2496 Shows a diff which includes the current patch as well as any
2497 2497 changes which have been made in the working directory since the
2498 2498 last refresh (thus showing what the current patch would become
2499 2499 after a qrefresh).
2500 2500
2501 2501 Use :hg:`diff` if you only want to see the changes made since the
2502 2502 last qrefresh, or :hg:`export qtip` if you want to see changes
2503 2503 made by the current patch without including changes made since the
2504 2504 qrefresh.
2505 2505
2506 2506 Returns 0 on success.
2507 2507 """
2508 2508 repo.mq.diff(repo, pats, opts)
2509 2509 return 0
2510 2510
2511 2511 @command('qfold',
2512 2512 [('e', 'edit', None, _('edit patch header')),
2513 2513 ('k', 'keep', None, _('keep folded patch files')),
2514 2514 ] + commands.commitopts,
2515 2515 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2516 2516 def fold(ui, repo, *files, **opts):
2517 2517 """fold the named patches into the current patch
2518 2518
2519 2519 Patches must not yet be applied. Each patch will be successively
2520 2520 applied to the current patch in the order given. If all the
2521 2521 patches apply successfully, the current patch will be refreshed
2522 2522 with the new cumulative patch, and the folded patches will be
2523 2523 deleted. With -k/--keep, the folded patch files will not be
2524 2524 removed afterwards.
2525 2525
2526 2526 The header for each folded patch will be concatenated with the
2527 2527 current patch header, separated by a line of ``* * *``.
2528 2528
2529 2529 Returns 0 on success."""
2530 2530 q = repo.mq
2531 2531 if not files:
2532 2532 raise util.Abort(_('qfold requires at least one patch name'))
2533 2533 if not q.checktoppatch(repo)[0]:
2534 2534 raise util.Abort(_('no patches applied'))
2535 2535 q.checklocalchanges(repo)
2536 2536
2537 2537 message = cmdutil.logmessage(ui, opts)
2538 2538 if opts.get('edit'):
2539 2539 if message:
2540 2540 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2541 2541
2542 2542 parent = q.lookup('qtip')
2543 2543 patches = []
2544 2544 messages = []
2545 2545 for f in files:
2546 2546 p = q.lookup(f)
2547 2547 if p in patches or p == parent:
2548 2548 ui.warn(_('skipping already folded patch %s\n') % p)
2549 2549 if q.isapplied(p):
2550 2550 raise util.Abort(_('qfold cannot fold already applied patch %s')
2551 2551 % p)
2552 2552 patches.append(p)
2553 2553
2554 2554 for p in patches:
2555 2555 if not message:
2556 2556 ph = patchheader(q.join(p), q.plainmode)
2557 2557 if ph.message:
2558 2558 messages.append(ph.message)
2559 2559 pf = q.join(p)
2560 2560 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2561 2561 if not patchsuccess:
2562 2562 raise util.Abort(_('error folding patch %s') % p)
2563 2563
2564 2564 if not message:
2565 2565 ph = patchheader(q.join(parent), q.plainmode)
2566 2566 message, user = ph.message, ph.user
2567 2567 for msg in messages:
2568 2568 message.append('* * *')
2569 2569 message.extend(msg)
2570 2570 message = '\n'.join(message)
2571 2571
2572 2572 if opts.get('edit'):
2573 2573 message = ui.edit(message, user or ui.username())
2574 2574
2575 2575 diffopts = q.patchopts(q.diffopts(), *patches)
2576 2576 wlock = repo.wlock()
2577 2577 try:
2578 2578 q.refresh(repo, msg=message, git=diffopts.git)
2579 2579 q.delete(repo, patches, opts)
2580 2580 q.savedirty()
2581 2581 finally:
2582 2582 wlock.release()
2583 2583
2584 2584 @command("qgoto",
2585 2585 [('', 'keep-changes', None,
2586 2586 _('tolerate non-conflicting local changes')),
2587 2587 ('f', 'force', None, _('overwrite any local changes')),
2588 2588 ('', 'no-backup', None, _('do not save backup copies of files'))],
2589 2589 _('hg qgoto [OPTION]... PATCH'))
2590 2590 def goto(ui, repo, patch, **opts):
2591 2591 '''push or pop patches until named patch is at top of stack
2592 2592
2593 2593 Returns 0 on success.'''
2594 2594 opts = fixkeepchangesopts(ui, opts)
2595 2595 q = repo.mq
2596 2596 patch = q.lookup(patch)
2597 2597 nobackup = opts.get('no_backup')
2598 2598 keepchanges = opts.get('keep_changes')
2599 2599 if q.isapplied(patch):
2600 2600 ret = q.pop(repo, patch, force=opts.get('force'), nobackup=nobackup,
2601 2601 keepchanges=keepchanges)
2602 2602 else:
2603 2603 ret = q.push(repo, patch, force=opts.get('force'), nobackup=nobackup,
2604 2604 keepchanges=keepchanges)
2605 2605 q.savedirty()
2606 2606 return ret
2607 2607
2608 2608 @command("qguard",
2609 2609 [('l', 'list', None, _('list all patches and guards')),
2610 2610 ('n', 'none', None, _('drop all guards'))],
2611 2611 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2612 2612 def guard(ui, repo, *args, **opts):
2613 2613 '''set or print guards for a patch
2614 2614
2615 2615 Guards control whether a patch can be pushed. A patch with no
2616 2616 guards is always pushed. A patch with a positive guard ("+foo") is
2617 2617 pushed only if the :hg:`qselect` command has activated it. A patch with
2618 2618 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2619 2619 has activated it.
2620 2620
2621 2621 With no arguments, print the currently active guards.
2622 2622 With arguments, set guards for the named patch.
2623 2623
2624 2624 .. note::
2625
2625 2626 Specifying negative guards now requires '--'.
2626 2627
2627 2628 To set guards on another patch::
2628 2629
2629 2630 hg qguard other.patch -- +2.6.17 -stable
2630 2631
2631 2632 Returns 0 on success.
2632 2633 '''
2633 2634 def status(idx):
2634 2635 guards = q.seriesguards[idx] or ['unguarded']
2635 2636 if q.series[idx] in applied:
2636 2637 state = 'applied'
2637 2638 elif q.pushable(idx)[0]:
2638 2639 state = 'unapplied'
2639 2640 else:
2640 2641 state = 'guarded'
2641 2642 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2642 2643 ui.write('%s: ' % ui.label(q.series[idx], label))
2643 2644
2644 2645 for i, guard in enumerate(guards):
2645 2646 if guard.startswith('+'):
2646 2647 ui.write(guard, label='qguard.positive')
2647 2648 elif guard.startswith('-'):
2648 2649 ui.write(guard, label='qguard.negative')
2649 2650 else:
2650 2651 ui.write(guard, label='qguard.unguarded')
2651 2652 if i != len(guards) - 1:
2652 2653 ui.write(' ')
2653 2654 ui.write('\n')
2654 2655 q = repo.mq
2655 2656 applied = set(p.name for p in q.applied)
2656 2657 patch = None
2657 2658 args = list(args)
2658 2659 if opts.get('list'):
2659 2660 if args or opts.get('none'):
2660 2661 raise util.Abort(_('cannot mix -l/--list with options or '
2661 2662 'arguments'))
2662 2663 for i in xrange(len(q.series)):
2663 2664 status(i)
2664 2665 return
2665 2666 if not args or args[0][0:1] in '-+':
2666 2667 if not q.applied:
2667 2668 raise util.Abort(_('no patches applied'))
2668 2669 patch = q.applied[-1].name
2669 2670 if patch is None and args[0][0:1] not in '-+':
2670 2671 patch = args.pop(0)
2671 2672 if patch is None:
2672 2673 raise util.Abort(_('no patch to work with'))
2673 2674 if args or opts.get('none'):
2674 2675 idx = q.findseries(patch)
2675 2676 if idx is None:
2676 2677 raise util.Abort(_('no patch named %s') % patch)
2677 2678 q.setguards(idx, args)
2678 2679 q.savedirty()
2679 2680 else:
2680 2681 status(q.series.index(q.lookup(patch)))
2681 2682
2682 2683 @command("qheader", [], _('hg qheader [PATCH]'))
2683 2684 def header(ui, repo, patch=None):
2684 2685 """print the header of the topmost or specified patch
2685 2686
2686 2687 Returns 0 on success."""
2687 2688 q = repo.mq
2688 2689
2689 2690 if patch:
2690 2691 patch = q.lookup(patch)
2691 2692 else:
2692 2693 if not q.applied:
2693 2694 ui.write(_('no patches applied\n'))
2694 2695 return 1
2695 2696 patch = q.lookup('qtip')
2696 2697 ph = patchheader(q.join(patch), q.plainmode)
2697 2698
2698 2699 ui.write('\n'.join(ph.message) + '\n')
2699 2700
2700 2701 def lastsavename(path):
2701 2702 (directory, base) = os.path.split(path)
2702 2703 names = os.listdir(directory)
2703 2704 namere = re.compile("%s.([0-9]+)" % base)
2704 2705 maxindex = None
2705 2706 maxname = None
2706 2707 for f in names:
2707 2708 m = namere.match(f)
2708 2709 if m:
2709 2710 index = int(m.group(1))
2710 2711 if maxindex is None or index > maxindex:
2711 2712 maxindex = index
2712 2713 maxname = f
2713 2714 if maxname:
2714 2715 return (os.path.join(directory, maxname), maxindex)
2715 2716 return (None, None)
2716 2717
2717 2718 def savename(path):
2718 2719 (last, index) = lastsavename(path)
2719 2720 if last is None:
2720 2721 index = 0
2721 2722 newpath = path + ".%d" % (index + 1)
2722 2723 return newpath
2723 2724
2724 2725 @command("^qpush",
2725 2726 [('', 'keep-changes', None,
2726 2727 _('tolerate non-conflicting local changes')),
2727 2728 ('f', 'force', None, _('apply on top of local changes')),
2728 2729 ('e', 'exact', None,
2729 2730 _('apply the target patch to its recorded parent')),
2730 2731 ('l', 'list', None, _('list patch name in commit text')),
2731 2732 ('a', 'all', None, _('apply all patches')),
2732 2733 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2733 2734 ('n', 'name', '',
2734 2735 _('merge queue name (DEPRECATED)'), _('NAME')),
2735 2736 ('', 'move', None,
2736 2737 _('reorder patch series and apply only the patch')),
2737 2738 ('', 'no-backup', None, _('do not save backup copies of files'))],
2738 2739 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2739 2740 def push(ui, repo, patch=None, **opts):
2740 2741 """push the next patch onto the stack
2741 2742
2742 2743 By default, abort if the working directory contains uncommitted
2743 2744 changes. With --keep-changes, abort only if the uncommitted files
2744 2745 overlap with patched files. With -f/--force, backup and patch over
2745 2746 uncommitted changes.
2746 2747
2747 2748 Return 0 on success.
2748 2749 """
2749 2750 q = repo.mq
2750 2751 mergeq = None
2751 2752
2752 2753 opts = fixkeepchangesopts(ui, opts)
2753 2754 if opts.get('merge'):
2754 2755 if opts.get('name'):
2755 2756 newpath = repo.join(opts.get('name'))
2756 2757 else:
2757 2758 newpath, i = lastsavename(q.path)
2758 2759 if not newpath:
2759 2760 ui.warn(_("no saved queues found, please use -n\n"))
2760 2761 return 1
2761 2762 mergeq = queue(ui, repo.baseui, repo.path, newpath)
2762 2763 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2763 2764 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2764 2765 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2765 2766 exact=opts.get('exact'), nobackup=opts.get('no_backup'),
2766 2767 keepchanges=opts.get('keep_changes'))
2767 2768 return ret
2768 2769
2769 2770 @command("^qpop",
2770 2771 [('a', 'all', None, _('pop all patches')),
2771 2772 ('n', 'name', '',
2772 2773 _('queue name to pop (DEPRECATED)'), _('NAME')),
2773 2774 ('', 'keep-changes', None,
2774 2775 _('tolerate non-conflicting local changes')),
2775 2776 ('f', 'force', None, _('forget any local changes to patched files')),
2776 2777 ('', 'no-backup', None, _('do not save backup copies of files'))],
2777 2778 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2778 2779 def pop(ui, repo, patch=None, **opts):
2779 2780 """pop the current patch off the stack
2780 2781
2781 2782 Without argument, pops off the top of the patch stack. If given a
2782 2783 patch name, keeps popping off patches until the named patch is at
2783 2784 the top of the stack.
2784 2785
2785 2786 By default, abort if the working directory contains uncommitted
2786 2787 changes. With --keep-changes, abort only if the uncommitted files
2787 2788 overlap with patched files. With -f/--force, backup and discard
2788 2789 changes made to such files.
2789 2790
2790 2791 Return 0 on success.
2791 2792 """
2792 2793 opts = fixkeepchangesopts(ui, opts)
2793 2794 localupdate = True
2794 2795 if opts.get('name'):
2795 2796 q = queue(ui, repo.baseui, repo.path, repo.join(opts.get('name')))
2796 2797 ui.warn(_('using patch queue: %s\n') % q.path)
2797 2798 localupdate = False
2798 2799 else:
2799 2800 q = repo.mq
2800 2801 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2801 2802 all=opts.get('all'), nobackup=opts.get('no_backup'),
2802 2803 keepchanges=opts.get('keep_changes'))
2803 2804 q.savedirty()
2804 2805 return ret
2805 2806
2806 2807 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2807 2808 def rename(ui, repo, patch, name=None, **opts):
2808 2809 """rename a patch
2809 2810
2810 2811 With one argument, renames the current patch to PATCH1.
2811 2812 With two arguments, renames PATCH1 to PATCH2.
2812 2813
2813 2814 Returns 0 on success."""
2814 2815 q = repo.mq
2815 2816 if not name:
2816 2817 name = patch
2817 2818 patch = None
2818 2819
2819 2820 if patch:
2820 2821 patch = q.lookup(patch)
2821 2822 else:
2822 2823 if not q.applied:
2823 2824 ui.write(_('no patches applied\n'))
2824 2825 return
2825 2826 patch = q.lookup('qtip')
2826 2827 absdest = q.join(name)
2827 2828 if os.path.isdir(absdest):
2828 2829 name = normname(os.path.join(name, os.path.basename(patch)))
2829 2830 absdest = q.join(name)
2830 2831 q.checkpatchname(name)
2831 2832
2832 2833 ui.note(_('renaming %s to %s\n') % (patch, name))
2833 2834 i = q.findseries(patch)
2834 2835 guards = q.guard_re.findall(q.fullseries[i])
2835 2836 q.fullseries[i] = name + ''.join([' #' + g for g in guards])
2836 2837 q.parseseries()
2837 2838 q.seriesdirty = True
2838 2839
2839 2840 info = q.isapplied(patch)
2840 2841 if info:
2841 2842 q.applied[info[0]] = statusentry(info[1], name)
2842 2843 q.applieddirty = True
2843 2844
2844 2845 destdir = os.path.dirname(absdest)
2845 2846 if not os.path.isdir(destdir):
2846 2847 os.makedirs(destdir)
2847 2848 util.rename(q.join(patch), absdest)
2848 2849 r = q.qrepo()
2849 2850 if r and patch in r.dirstate:
2850 2851 wctx = r[None]
2851 2852 wlock = r.wlock()
2852 2853 try:
2853 2854 if r.dirstate[patch] == 'a':
2854 2855 r.dirstate.drop(patch)
2855 2856 r.dirstate.add(name)
2856 2857 else:
2857 2858 wctx.copy(patch, name)
2858 2859 wctx.forget([patch])
2859 2860 finally:
2860 2861 wlock.release()
2861 2862
2862 2863 q.savedirty()
2863 2864
2864 2865 @command("qrestore",
2865 2866 [('d', 'delete', None, _('delete save entry')),
2866 2867 ('u', 'update', None, _('update queue working directory'))],
2867 2868 _('hg qrestore [-d] [-u] REV'))
2868 2869 def restore(ui, repo, rev, **opts):
2869 2870 """restore the queue state saved by a revision (DEPRECATED)
2870 2871
2871 2872 This command is deprecated, use :hg:`rebase` instead."""
2872 2873 rev = repo.lookup(rev)
2873 2874 q = repo.mq
2874 2875 q.restore(repo, rev, delete=opts.get('delete'),
2875 2876 qupdate=opts.get('update'))
2876 2877 q.savedirty()
2877 2878 return 0
2878 2879
2879 2880 @command("qsave",
2880 2881 [('c', 'copy', None, _('copy patch directory')),
2881 2882 ('n', 'name', '',
2882 2883 _('copy directory name'), _('NAME')),
2883 2884 ('e', 'empty', None, _('clear queue status file')),
2884 2885 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2885 2886 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2886 2887 def save(ui, repo, **opts):
2887 2888 """save current queue state (DEPRECATED)
2888 2889
2889 2890 This command is deprecated, use :hg:`rebase` instead."""
2890 2891 q = repo.mq
2891 2892 message = cmdutil.logmessage(ui, opts)
2892 2893 ret = q.save(repo, msg=message)
2893 2894 if ret:
2894 2895 return ret
2895 2896 q.savedirty() # save to .hg/patches before copying
2896 2897 if opts.get('copy'):
2897 2898 path = q.path
2898 2899 if opts.get('name'):
2899 2900 newpath = os.path.join(q.basepath, opts.get('name'))
2900 2901 if os.path.exists(newpath):
2901 2902 if not os.path.isdir(newpath):
2902 2903 raise util.Abort(_('destination %s exists and is not '
2903 2904 'a directory') % newpath)
2904 2905 if not opts.get('force'):
2905 2906 raise util.Abort(_('destination %s exists, '
2906 2907 'use -f to force') % newpath)
2907 2908 else:
2908 2909 newpath = savename(path)
2909 2910 ui.warn(_("copy %s to %s\n") % (path, newpath))
2910 2911 util.copyfiles(path, newpath)
2911 2912 if opts.get('empty'):
2912 2913 del q.applied[:]
2913 2914 q.applieddirty = True
2914 2915 q.savedirty()
2915 2916 return 0
2916 2917
2917 2918
2918 2919 @command("qselect",
2919 2920 [('n', 'none', None, _('disable all guards')),
2920 2921 ('s', 'series', None, _('list all guards in series file')),
2921 2922 ('', 'pop', None, _('pop to before first guarded applied patch')),
2922 2923 ('', 'reapply', None, _('pop, then reapply patches'))],
2923 2924 _('hg qselect [OPTION]... [GUARD]...'))
2924 2925 def select(ui, repo, *args, **opts):
2925 2926 '''set or print guarded patches to push
2926 2927
2927 2928 Use the :hg:`qguard` command to set or print guards on patch, then use
2928 2929 qselect to tell mq which guards to use. A patch will be pushed if
2929 2930 it has no guards or any positive guards match the currently
2930 2931 selected guard, but will not be pushed if any negative guards
2931 2932 match the current guard. For example::
2932 2933
2933 2934 qguard foo.patch -- -stable (negative guard)
2934 2935 qguard bar.patch +stable (positive guard)
2935 2936 qselect stable
2936 2937
2937 2938 This activates the "stable" guard. mq will skip foo.patch (because
2938 2939 it has a negative match) but push bar.patch (because it has a
2939 2940 positive match).
2940 2941
2941 2942 With no arguments, prints the currently active guards.
2942 2943 With one argument, sets the active guard.
2943 2944
2944 2945 Use -n/--none to deactivate guards (no other arguments needed).
2945 2946 When no guards are active, patches with positive guards are
2946 2947 skipped and patches with negative guards are pushed.
2947 2948
2948 2949 qselect can change the guards on applied patches. It does not pop
2949 2950 guarded patches by default. Use --pop to pop back to the last
2950 2951 applied patch that is not guarded. Use --reapply (which implies
2951 2952 --pop) to push back to the current patch afterwards, but skip
2952 2953 guarded patches.
2953 2954
2954 2955 Use -s/--series to print a list of all guards in the series file
2955 2956 (no other arguments needed). Use -v for more information.
2956 2957
2957 2958 Returns 0 on success.'''
2958 2959
2959 2960 q = repo.mq
2960 2961 guards = q.active()
2961 2962 if args or opts.get('none'):
2962 2963 old_unapplied = q.unapplied(repo)
2963 2964 old_guarded = [i for i in xrange(len(q.applied)) if
2964 2965 not q.pushable(i)[0]]
2965 2966 q.setactive(args)
2966 2967 q.savedirty()
2967 2968 if not args:
2968 2969 ui.status(_('guards deactivated\n'))
2969 2970 if not opts.get('pop') and not opts.get('reapply'):
2970 2971 unapplied = q.unapplied(repo)
2971 2972 guarded = [i for i in xrange(len(q.applied))
2972 2973 if not q.pushable(i)[0]]
2973 2974 if len(unapplied) != len(old_unapplied):
2974 2975 ui.status(_('number of unguarded, unapplied patches has '
2975 2976 'changed from %d to %d\n') %
2976 2977 (len(old_unapplied), len(unapplied)))
2977 2978 if len(guarded) != len(old_guarded):
2978 2979 ui.status(_('number of guarded, applied patches has changed '
2979 2980 'from %d to %d\n') %
2980 2981 (len(old_guarded), len(guarded)))
2981 2982 elif opts.get('series'):
2982 2983 guards = {}
2983 2984 noguards = 0
2984 2985 for gs in q.seriesguards:
2985 2986 if not gs:
2986 2987 noguards += 1
2987 2988 for g in gs:
2988 2989 guards.setdefault(g, 0)
2989 2990 guards[g] += 1
2990 2991 if ui.verbose:
2991 2992 guards['NONE'] = noguards
2992 2993 guards = guards.items()
2993 2994 guards.sort(key=lambda x: x[0][1:])
2994 2995 if guards:
2995 2996 ui.note(_('guards in series file:\n'))
2996 2997 for guard, count in guards:
2997 2998 ui.note('%2d ' % count)
2998 2999 ui.write(guard, '\n')
2999 3000 else:
3000 3001 ui.note(_('no guards in series file\n'))
3001 3002 else:
3002 3003 if guards:
3003 3004 ui.note(_('active guards:\n'))
3004 3005 for g in guards:
3005 3006 ui.write(g, '\n')
3006 3007 else:
3007 3008 ui.write(_('no active guards\n'))
3008 3009 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
3009 3010 popped = False
3010 3011 if opts.get('pop') or opts.get('reapply'):
3011 3012 for i in xrange(len(q.applied)):
3012 3013 pushable, reason = q.pushable(i)
3013 3014 if not pushable:
3014 3015 ui.status(_('popping guarded patches\n'))
3015 3016 popped = True
3016 3017 if i == 0:
3017 3018 q.pop(repo, all=True)
3018 3019 else:
3019 3020 q.pop(repo, str(i - 1))
3020 3021 break
3021 3022 if popped:
3022 3023 try:
3023 3024 if reapply:
3024 3025 ui.status(_('reapplying unguarded patches\n'))
3025 3026 q.push(repo, reapply)
3026 3027 finally:
3027 3028 q.savedirty()
3028 3029
3029 3030 @command("qfinish",
3030 3031 [('a', 'applied', None, _('finish all applied changesets'))],
3031 3032 _('hg qfinish [-a] [REV]...'))
3032 3033 def finish(ui, repo, *revrange, **opts):
3033 3034 """move applied patches into repository history
3034 3035
3035 3036 Finishes the specified revisions (corresponding to applied
3036 3037 patches) by moving them out of mq control into regular repository
3037 3038 history.
3038 3039
3039 3040 Accepts a revision range or the -a/--applied option. If --applied
3040 3041 is specified, all applied mq revisions are removed from mq
3041 3042 control. Otherwise, the given revisions must be at the base of the
3042 3043 stack of applied patches.
3043 3044
3044 3045 This can be especially useful if your changes have been applied to
3045 3046 an upstream repository, or if you are about to push your changes
3046 3047 to upstream.
3047 3048
3048 3049 Returns 0 on success.
3049 3050 """
3050 3051 if not opts.get('applied') and not revrange:
3051 3052 raise util.Abort(_('no revisions specified'))
3052 3053 elif opts.get('applied'):
3053 3054 revrange = ('qbase::qtip',) + revrange
3054 3055
3055 3056 q = repo.mq
3056 3057 if not q.applied:
3057 3058 ui.status(_('no patches applied\n'))
3058 3059 return 0
3059 3060
3060 3061 revs = scmutil.revrange(repo, revrange)
3061 3062 if repo['.'].rev() in revs and repo[None].files():
3062 3063 ui.warn(_('warning: uncommitted changes in the working directory\n'))
3063 3064 # queue.finish may changes phases but leave the responsibility to lock the
3064 3065 # repo to the caller to avoid deadlock with wlock. This command code is
3065 3066 # responsibility for this locking.
3066 3067 lock = repo.lock()
3067 3068 try:
3068 3069 q.finish(repo, revs)
3069 3070 q.savedirty()
3070 3071 finally:
3071 3072 lock.release()
3072 3073 return 0
3073 3074
3074 3075 @command("qqueue",
3075 3076 [('l', 'list', False, _('list all available queues')),
3076 3077 ('', 'active', False, _('print name of active queue')),
3077 3078 ('c', 'create', False, _('create new queue')),
3078 3079 ('', 'rename', False, _('rename active queue')),
3079 3080 ('', 'delete', False, _('delete reference to queue')),
3080 3081 ('', 'purge', False, _('delete queue, and remove patch dir')),
3081 3082 ],
3082 3083 _('[OPTION] [QUEUE]'))
3083 3084 def qqueue(ui, repo, name=None, **opts):
3084 3085 '''manage multiple patch queues
3085 3086
3086 3087 Supports switching between different patch queues, as well as creating
3087 3088 new patch queues and deleting existing ones.
3088 3089
3089 3090 Omitting a queue name or specifying -l/--list will show you the registered
3090 3091 queues - by default the "normal" patches queue is registered. The currently
3091 3092 active queue will be marked with "(active)". Specifying --active will print
3092 3093 only the name of the active queue.
3093 3094
3094 3095 To create a new queue, use -c/--create. The queue is automatically made
3095 3096 active, except in the case where there are applied patches from the
3096 3097 currently active queue in the repository. Then the queue will only be
3097 3098 created and switching will fail.
3098 3099
3099 3100 To delete an existing queue, use --delete. You cannot delete the currently
3100 3101 active queue.
3101 3102
3102 3103 Returns 0 on success.
3103 3104 '''
3104 3105 q = repo.mq
3105 3106 _defaultqueue = 'patches'
3106 3107 _allqueues = 'patches.queues'
3107 3108 _activequeue = 'patches.queue'
3108 3109
3109 3110 def _getcurrent():
3110 3111 cur = os.path.basename(q.path)
3111 3112 if cur.startswith('patches-'):
3112 3113 cur = cur[8:]
3113 3114 return cur
3114 3115
3115 3116 def _noqueues():
3116 3117 try:
3117 3118 fh = repo.opener(_allqueues, 'r')
3118 3119 fh.close()
3119 3120 except IOError:
3120 3121 return True
3121 3122
3122 3123 return False
3123 3124
3124 3125 def _getqueues():
3125 3126 current = _getcurrent()
3126 3127
3127 3128 try:
3128 3129 fh = repo.opener(_allqueues, 'r')
3129 3130 queues = [queue.strip() for queue in fh if queue.strip()]
3130 3131 fh.close()
3131 3132 if current not in queues:
3132 3133 queues.append(current)
3133 3134 except IOError:
3134 3135 queues = [_defaultqueue]
3135 3136
3136 3137 return sorted(queues)
3137 3138
3138 3139 def _setactive(name):
3139 3140 if q.applied:
3140 3141 raise util.Abort(_('new queue created, but cannot make active '
3141 3142 'as patches are applied'))
3142 3143 _setactivenocheck(name)
3143 3144
3144 3145 def _setactivenocheck(name):
3145 3146 fh = repo.opener(_activequeue, 'w')
3146 3147 if name != 'patches':
3147 3148 fh.write(name)
3148 3149 fh.close()
3149 3150
3150 3151 def _addqueue(name):
3151 3152 fh = repo.opener(_allqueues, 'a')
3152 3153 fh.write('%s\n' % (name,))
3153 3154 fh.close()
3154 3155
3155 3156 def _queuedir(name):
3156 3157 if name == 'patches':
3157 3158 return repo.join('patches')
3158 3159 else:
3159 3160 return repo.join('patches-' + name)
3160 3161
3161 3162 def _validname(name):
3162 3163 for n in name:
3163 3164 if n in ':\\/.':
3164 3165 return False
3165 3166 return True
3166 3167
3167 3168 def _delete(name):
3168 3169 if name not in existing:
3169 3170 raise util.Abort(_('cannot delete queue that does not exist'))
3170 3171
3171 3172 current = _getcurrent()
3172 3173
3173 3174 if name == current:
3174 3175 raise util.Abort(_('cannot delete currently active queue'))
3175 3176
3176 3177 fh = repo.opener('patches.queues.new', 'w')
3177 3178 for queue in existing:
3178 3179 if queue == name:
3179 3180 continue
3180 3181 fh.write('%s\n' % (queue,))
3181 3182 fh.close()
3182 3183 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3183 3184
3184 3185 if not name or opts.get('list') or opts.get('active'):
3185 3186 current = _getcurrent()
3186 3187 if opts.get('active'):
3187 3188 ui.write('%s\n' % (current,))
3188 3189 return
3189 3190 for queue in _getqueues():
3190 3191 ui.write('%s' % (queue,))
3191 3192 if queue == current and not ui.quiet:
3192 3193 ui.write(_(' (active)\n'))
3193 3194 else:
3194 3195 ui.write('\n')
3195 3196 return
3196 3197
3197 3198 if not _validname(name):
3198 3199 raise util.Abort(
3199 3200 _('invalid queue name, may not contain the characters ":\\/."'))
3200 3201
3201 3202 existing = _getqueues()
3202 3203
3203 3204 if opts.get('create'):
3204 3205 if name in existing:
3205 3206 raise util.Abort(_('queue "%s" already exists') % name)
3206 3207 if _noqueues():
3207 3208 _addqueue(_defaultqueue)
3208 3209 _addqueue(name)
3209 3210 _setactive(name)
3210 3211 elif opts.get('rename'):
3211 3212 current = _getcurrent()
3212 3213 if name == current:
3213 3214 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3214 3215 if name in existing:
3215 3216 raise util.Abort(_('queue "%s" already exists') % name)
3216 3217
3217 3218 olddir = _queuedir(current)
3218 3219 newdir = _queuedir(name)
3219 3220
3220 3221 if os.path.exists(newdir):
3221 3222 raise util.Abort(_('non-queue directory "%s" already exists') %
3222 3223 newdir)
3223 3224
3224 3225 fh = repo.opener('patches.queues.new', 'w')
3225 3226 for queue in existing:
3226 3227 if queue == current:
3227 3228 fh.write('%s\n' % (name,))
3228 3229 if os.path.exists(olddir):
3229 3230 util.rename(olddir, newdir)
3230 3231 else:
3231 3232 fh.write('%s\n' % (queue,))
3232 3233 fh.close()
3233 3234 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3234 3235 _setactivenocheck(name)
3235 3236 elif opts.get('delete'):
3236 3237 _delete(name)
3237 3238 elif opts.get('purge'):
3238 3239 if name in existing:
3239 3240 _delete(name)
3240 3241 qdir = _queuedir(name)
3241 3242 if os.path.exists(qdir):
3242 3243 shutil.rmtree(qdir)
3243 3244 else:
3244 3245 if name not in existing:
3245 3246 raise util.Abort(_('use --create to create a new queue'))
3246 3247 _setactive(name)
3247 3248
3248 3249 def mqphasedefaults(repo, roots):
3249 3250 """callback used to set mq changeset as secret when no phase data exists"""
3250 3251 if repo.mq.applied:
3251 3252 if repo.ui.configbool('mq', 'secret', False):
3252 3253 mqphase = phases.secret
3253 3254 else:
3254 3255 mqphase = phases.draft
3255 3256 qbase = repo[repo.mq.applied[0].node]
3256 3257 roots[mqphase].add(qbase.node())
3257 3258 return roots
3258 3259
3259 3260 def reposetup(ui, repo):
3260 3261 class mqrepo(repo.__class__):
3261 3262 @localrepo.unfilteredpropertycache
3262 3263 def mq(self):
3263 3264 return queue(self.ui, self.baseui, self.path)
3264 3265
3265 3266 def abortifwdirpatched(self, errmsg, force=False):
3266 3267 if self.mq.applied and self.mq.checkapplied and not force:
3267 3268 parents = self.dirstate.parents()
3268 3269 patches = [s.node for s in self.mq.applied]
3269 3270 if parents[0] in patches or parents[1] in patches:
3270 3271 raise util.Abort(errmsg)
3271 3272
3272 3273 def commit(self, text="", user=None, date=None, match=None,
3273 3274 force=False, editor=False, extra={}):
3274 3275 self.abortifwdirpatched(
3275 3276 _('cannot commit over an applied mq patch'),
3276 3277 force)
3277 3278
3278 3279 return super(mqrepo, self).commit(text, user, date, match, force,
3279 3280 editor, extra)
3280 3281
3281 3282 def checkpush(self, force, revs):
3282 3283 if self.mq.applied and self.mq.checkapplied and not force:
3283 3284 outapplied = [e.node for e in self.mq.applied]
3284 3285 if revs:
3285 3286 # Assume applied patches have no non-patch descendants and
3286 3287 # are not on remote already. Filtering any changeset not
3287 3288 # pushed.
3288 3289 heads = set(revs)
3289 3290 for node in reversed(outapplied):
3290 3291 if node in heads:
3291 3292 break
3292 3293 else:
3293 3294 outapplied.pop()
3294 3295 # looking for pushed and shared changeset
3295 3296 for node in outapplied:
3296 3297 if self[node].phase() < phases.secret:
3297 3298 raise util.Abort(_('source has mq patches applied'))
3298 3299 # no non-secret patches pushed
3299 3300 super(mqrepo, self).checkpush(force, revs)
3300 3301
3301 3302 def _findtags(self):
3302 3303 '''augment tags from base class with patch tags'''
3303 3304 result = super(mqrepo, self)._findtags()
3304 3305
3305 3306 q = self.mq
3306 3307 if not q.applied:
3307 3308 return result
3308 3309
3309 3310 mqtags = [(patch.node, patch.name) for patch in q.applied]
3310 3311
3311 3312 try:
3312 3313 # for now ignore filtering business
3313 3314 self.unfiltered().changelog.rev(mqtags[-1][0])
3314 3315 except error.LookupError:
3315 3316 self.ui.warn(_('mq status file refers to unknown node %s\n')
3316 3317 % short(mqtags[-1][0]))
3317 3318 return result
3318 3319
3319 3320 # do not add fake tags for filtered revisions
3320 3321 included = self.changelog.hasnode
3321 3322 mqtags = [mqt for mqt in mqtags if included(mqt[0])]
3322 3323 if not mqtags:
3323 3324 return result
3324 3325
3325 3326 mqtags.append((mqtags[-1][0], 'qtip'))
3326 3327 mqtags.append((mqtags[0][0], 'qbase'))
3327 3328 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3328 3329 tags = result[0]
3329 3330 for patch in mqtags:
3330 3331 if patch[1] in tags:
3331 3332 self.ui.warn(_('tag %s overrides mq patch of the same '
3332 3333 'name\n') % patch[1])
3333 3334 else:
3334 3335 tags[patch[1]] = patch[0]
3335 3336
3336 3337 return result
3337 3338
3338 3339 if repo.local():
3339 3340 repo.__class__ = mqrepo
3340 3341
3341 3342 repo._phasedefaults.append(mqphasedefaults)
3342 3343
3343 3344 def mqimport(orig, ui, repo, *args, **kwargs):
3344 3345 if (util.safehasattr(repo, 'abortifwdirpatched')
3345 3346 and not kwargs.get('no_commit', False)):
3346 3347 repo.abortifwdirpatched(_('cannot import over an applied patch'),
3347 3348 kwargs.get('force'))
3348 3349 return orig(ui, repo, *args, **kwargs)
3349 3350
3350 3351 def mqinit(orig, ui, *args, **kwargs):
3351 3352 mq = kwargs.pop('mq', None)
3352 3353
3353 3354 if not mq:
3354 3355 return orig(ui, *args, **kwargs)
3355 3356
3356 3357 if args:
3357 3358 repopath = args[0]
3358 3359 if not hg.islocal(repopath):
3359 3360 raise util.Abort(_('only a local queue repository '
3360 3361 'may be initialized'))
3361 3362 else:
3362 3363 repopath = cmdutil.findrepo(os.getcwd())
3363 3364 if not repopath:
3364 3365 raise util.Abort(_('there is no Mercurial repository here '
3365 3366 '(.hg not found)'))
3366 3367 repo = hg.repository(ui, repopath)
3367 3368 return qinit(ui, repo, True)
3368 3369
3369 3370 def mqcommand(orig, ui, repo, *args, **kwargs):
3370 3371 """Add --mq option to operate on patch repository instead of main"""
3371 3372
3372 3373 # some commands do not like getting unknown options
3373 3374 mq = kwargs.pop('mq', None)
3374 3375
3375 3376 if not mq:
3376 3377 return orig(ui, repo, *args, **kwargs)
3377 3378
3378 3379 q = repo.mq
3379 3380 r = q.qrepo()
3380 3381 if not r:
3381 3382 raise util.Abort(_('no queue repository'))
3382 3383 return orig(r.ui, r, *args, **kwargs)
3383 3384
3384 3385 def summaryhook(ui, repo):
3385 3386 q = repo.mq
3386 3387 m = []
3387 3388 a, u = len(q.applied), len(q.unapplied(repo))
3388 3389 if a:
3389 3390 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3390 3391 if u:
3391 3392 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3392 3393 if m:
3393 3394 # i18n: column positioning for "hg summary"
3394 3395 ui.write(_("mq: %s\n") % ', '.join(m))
3395 3396 else:
3396 3397 # i18n: column positioning for "hg summary"
3397 3398 ui.note(_("mq: (empty queue)\n"))
3398 3399
3399 3400 def revsetmq(repo, subset, x):
3400 3401 """``mq()``
3401 3402 Changesets managed by MQ.
3402 3403 """
3403 3404 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3404 3405 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3405 3406 return [r for r in subset if r in applied]
3406 3407
3407 3408 # tell hggettext to extract docstrings from these functions:
3408 3409 i18nfunctions = [revsetmq]
3409 3410
3410 3411 def extsetup(ui):
3411 3412 # Ensure mq wrappers are called first, regardless of extension load order by
3412 3413 # NOT wrapping in uisetup() and instead deferring to init stage two here.
3413 3414 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3414 3415
3415 3416 extensions.wrapcommand(commands.table, 'import', mqimport)
3416 3417 cmdutil.summaryhooks.add('mq', summaryhook)
3417 3418
3418 3419 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3419 3420 entry[1].extend(mqopt)
3420 3421
3421 3422 nowrap = set(commands.norepo.split(" "))
3422 3423
3423 3424 def dotable(cmdtable):
3424 3425 for cmd in cmdtable.keys():
3425 3426 cmd = cmdutil.parsealiases(cmd)[0]
3426 3427 if cmd in nowrap:
3427 3428 continue
3428 3429 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3429 3430 entry[1].extend(mqopt)
3430 3431
3431 3432 dotable(commands.table)
3432 3433
3433 3434 for extname, extmodule in extensions.extensions():
3434 3435 if extmodule.__file__ != __file__:
3435 3436 dotable(getattr(extmodule, 'cmdtable', {}))
3436 3437
3437 3438 revset.symbols['mq'] = revsetmq
3438 3439
3439 3440 colortable = {'qguard.negative': 'red',
3440 3441 'qguard.positive': 'yellow',
3441 3442 'qguard.unguarded': 'green',
3442 3443 'qseries.applied': 'blue bold underline',
3443 3444 'qseries.guarded': 'black bold',
3444 3445 'qseries.missing': 'red bold',
3445 3446 'qseries.unapplied': 'black bold'}
3446 3447
3447 3448 commands.inferrepo += " qnew qrefresh qdiff qcommit"
@@ -1,74 +1,75 b''
1 1 # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
2 2 #
3 3 # This software may be used and distributed according to the terms of the
4 4 # GNU General Public License version 2 or any later version.
5 5
6 6 '''share a common history between several working directories'''
7 7
8 8 from mercurial.i18n import _
9 9 from mercurial import hg, commands, util
10 10
11 11 testedwith = 'internal'
12 12
13 13 def share(ui, source, dest=None, noupdate=False):
14 14 """create a new shared repository
15 15
16 16 Initialize a new repository and working directory that shares its
17 17 history with another repository.
18 18
19 19 .. note::
20
20 21 using rollback or extensions that destroy/modify history (mq,
21 22 rebase, etc.) can cause considerable confusion with shared
22 23 clones. In particular, if two shared clones are both updated to
23 24 the same changeset, and one of them destroys that changeset
24 25 with rollback, the other clone will suddenly stop working: all
25 26 operations will fail with "abort: working directory has unknown
26 27 parent". The only known workaround is to use debugsetparents on
27 28 the broken clone to reset it to a changeset that still exists.
28 29 """
29 30
30 31 return hg.share(ui, source, dest, not noupdate)
31 32
32 33 def unshare(ui, repo):
33 34 """convert a shared repository to a normal one
34 35
35 36 Copy the store data to the repo and remove the sharedpath data.
36 37 """
37 38
38 39 if repo.sharedpath == repo.path:
39 40 raise util.Abort(_("this is not a shared repo"))
40 41
41 42 destlock = lock = None
42 43 lock = repo.lock()
43 44 try:
44 45 # we use locks here because if we race with commit, we
45 46 # can end up with extra data in the cloned revlogs that's
46 47 # not pointed to by changesets, thus causing verify to
47 48 # fail
48 49
49 50 destlock = hg.copystore(ui, repo, repo.path)
50 51
51 52 sharefile = repo.join('sharedpath')
52 53 util.rename(sharefile, sharefile + '.old')
53 54
54 55 repo.requirements.discard('sharedpath')
55 56 repo._writerequirements()
56 57 finally:
57 58 destlock and destlock.release()
58 59 lock and lock.release()
59 60
60 61 # update store, spath, sopener and sjoin of repo
61 62 repo.__init__(repo.baseui, repo.root)
62 63
63 64 cmdtable = {
64 65 "share":
65 66 (share,
66 67 [('U', 'noupdate', None, _('do not create a working copy'))],
67 68 _('[-U] SOURCE [DEST]')),
68 69 "unshare":
69 70 (unshare,
70 71 [],
71 72 ''),
72 73 }
73 74
74 75 commands.norepo += " share"
@@ -1,5918 +1,5928 b''
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import hex, bin, nullid, nullrev, short
9 9 from lock import release
10 10 from i18n import _
11 11 import os, re, difflib, time, tempfile, errno
12 12 import hg, scmutil, util, revlog, copies, error, bookmarks
13 13 import patch, help, encoding, templatekw, discovery
14 14 import archival, changegroup, cmdutil, hbisect
15 15 import sshserver, hgweb, commandserver
16 16 from hgweb import server as hgweb_server
17 17 import merge as mergemod
18 18 import minirst, revset, fileset
19 19 import dagparser, context, simplemerge, graphmod
20 20 import random, setdiscovery, treediscovery, dagutil, pvec, localrepo
21 21 import phases, obsolete
22 22
23 23 table = {}
24 24
25 25 command = cmdutil.command(table)
26 26
27 27 # common command options
28 28
29 29 globalopts = [
30 30 ('R', 'repository', '',
31 31 _('repository root directory or name of overlay bundle file'),
32 32 _('REPO')),
33 33 ('', 'cwd', '',
34 34 _('change working directory'), _('DIR')),
35 35 ('y', 'noninteractive', None,
36 36 _('do not prompt, automatically pick the first choice for all prompts')),
37 37 ('q', 'quiet', None, _('suppress output')),
38 38 ('v', 'verbose', None, _('enable additional output')),
39 39 ('', 'config', [],
40 40 _('set/override config option (use \'section.name=value\')'),
41 41 _('CONFIG')),
42 42 ('', 'debug', None, _('enable debugging output')),
43 43 ('', 'debugger', None, _('start debugger')),
44 44 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
45 45 _('ENCODE')),
46 46 ('', 'encodingmode', encoding.encodingmode,
47 47 _('set the charset encoding mode'), _('MODE')),
48 48 ('', 'traceback', None, _('always print a traceback on exception')),
49 49 ('', 'time', None, _('time how long the command takes')),
50 50 ('', 'profile', None, _('print command execution profile')),
51 51 ('', 'version', None, _('output version information and exit')),
52 52 ('h', 'help', None, _('display help and exit')),
53 53 ('', 'hidden', False, _('consider hidden changesets')),
54 54 ]
55 55
56 56 dryrunopts = [('n', 'dry-run', None,
57 57 _('do not perform actions, just print output'))]
58 58
59 59 remoteopts = [
60 60 ('e', 'ssh', '',
61 61 _('specify ssh command to use'), _('CMD')),
62 62 ('', 'remotecmd', '',
63 63 _('specify hg command to run on the remote side'), _('CMD')),
64 64 ('', 'insecure', None,
65 65 _('do not verify server certificate (ignoring web.cacerts config)')),
66 66 ]
67 67
68 68 walkopts = [
69 69 ('I', 'include', [],
70 70 _('include names matching the given patterns'), _('PATTERN')),
71 71 ('X', 'exclude', [],
72 72 _('exclude names matching the given patterns'), _('PATTERN')),
73 73 ]
74 74
75 75 commitopts = [
76 76 ('m', 'message', '',
77 77 _('use text as commit message'), _('TEXT')),
78 78 ('l', 'logfile', '',
79 79 _('read commit message from file'), _('FILE')),
80 80 ]
81 81
82 82 commitopts2 = [
83 83 ('d', 'date', '',
84 84 _('record the specified date as commit date'), _('DATE')),
85 85 ('u', 'user', '',
86 86 _('record the specified user as committer'), _('USER')),
87 87 ]
88 88
89 89 templateopts = [
90 90 ('', 'style', '',
91 91 _('display using template map file'), _('STYLE')),
92 92 ('', 'template', '',
93 93 _('display with template'), _('TEMPLATE')),
94 94 ]
95 95
96 96 logopts = [
97 97 ('p', 'patch', None, _('show patch')),
98 98 ('g', 'git', None, _('use git extended diff format')),
99 99 ('l', 'limit', '',
100 100 _('limit number of changes displayed'), _('NUM')),
101 101 ('M', 'no-merges', None, _('do not show merges')),
102 102 ('', 'stat', None, _('output diffstat-style summary of changes')),
103 103 ('G', 'graph', None, _("show the revision DAG")),
104 104 ] + templateopts
105 105
106 106 diffopts = [
107 107 ('a', 'text', None, _('treat all files as text')),
108 108 ('g', 'git', None, _('use git extended diff format')),
109 109 ('', 'nodates', None, _('omit dates from diff headers'))
110 110 ]
111 111
112 112 diffwsopts = [
113 113 ('w', 'ignore-all-space', None,
114 114 _('ignore white space when comparing lines')),
115 115 ('b', 'ignore-space-change', None,
116 116 _('ignore changes in the amount of white space')),
117 117 ('B', 'ignore-blank-lines', None,
118 118 _('ignore changes whose lines are all blank')),
119 119 ]
120 120
121 121 diffopts2 = [
122 122 ('p', 'show-function', None, _('show which function each change is in')),
123 123 ('', 'reverse', None, _('produce a diff that undoes the changes')),
124 124 ] + diffwsopts + [
125 125 ('U', 'unified', '',
126 126 _('number of lines of context to show'), _('NUM')),
127 127 ('', 'stat', None, _('output diffstat-style summary of changes')),
128 128 ]
129 129
130 130 mergetoolopts = [
131 131 ('t', 'tool', '', _('specify merge tool')),
132 132 ]
133 133
134 134 similarityopts = [
135 135 ('s', 'similarity', '',
136 136 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
137 137 ]
138 138
139 139 subrepoopts = [
140 140 ('S', 'subrepos', None,
141 141 _('recurse into subrepositories'))
142 142 ]
143 143
144 144 # Commands start here, listed alphabetically
145 145
146 146 @command('^add',
147 147 walkopts + subrepoopts + dryrunopts,
148 148 _('[OPTION]... [FILE]...'))
149 149 def add(ui, repo, *pats, **opts):
150 150 """add the specified files on the next commit
151 151
152 152 Schedule files to be version controlled and added to the
153 153 repository.
154 154
155 155 The files will be added to the repository at the next commit. To
156 156 undo an add before that, see :hg:`forget`.
157 157
158 158 If no names are given, add all files to the repository.
159 159
160 160 .. container:: verbose
161 161
162 162 An example showing how new (unknown) files are added
163 163 automatically by :hg:`add`::
164 164
165 165 $ ls
166 166 foo.c
167 167 $ hg status
168 168 ? foo.c
169 169 $ hg add
170 170 adding foo.c
171 171 $ hg status
172 172 A foo.c
173 173
174 174 Returns 0 if all files are successfully added.
175 175 """
176 176
177 177 m = scmutil.match(repo[None], pats, opts)
178 178 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
179 179 opts.get('subrepos'), prefix="", explicitonly=False)
180 180 return rejected and 1 or 0
181 181
182 182 @command('addremove',
183 183 similarityopts + walkopts + dryrunopts,
184 184 _('[OPTION]... [FILE]...'))
185 185 def addremove(ui, repo, *pats, **opts):
186 186 """add all new files, delete all missing files
187 187
188 188 Add all new files and remove all missing files from the
189 189 repository.
190 190
191 191 New files are ignored if they match any of the patterns in
192 192 ``.hgignore``. As with add, these changes take effect at the next
193 193 commit.
194 194
195 195 Use the -s/--similarity option to detect renamed files. This
196 196 option takes a percentage between 0 (disabled) and 100 (files must
197 197 be identical) as its parameter. With a parameter greater than 0,
198 198 this compares every removed file with every added file and records
199 199 those similar enough as renames. Detecting renamed files this way
200 200 can be expensive. After using this option, :hg:`status -C` can be
201 201 used to check which files were identified as moved or renamed. If
202 202 not specified, -s/--similarity defaults to 100 and only renames of
203 203 identical files are detected.
204 204
205 205 Returns 0 if all files are successfully added.
206 206 """
207 207 try:
208 208 sim = float(opts.get('similarity') or 100)
209 209 except ValueError:
210 210 raise util.Abort(_('similarity must be a number'))
211 211 if sim < 0 or sim > 100:
212 212 raise util.Abort(_('similarity must be between 0 and 100'))
213 213 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
214 214
215 215 @command('^annotate|blame',
216 216 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
217 217 ('', 'follow', None,
218 218 _('follow copies/renames and list the filename (DEPRECATED)')),
219 219 ('', 'no-follow', None, _("don't follow copies and renames")),
220 220 ('a', 'text', None, _('treat all files as text')),
221 221 ('u', 'user', None, _('list the author (long with -v)')),
222 222 ('f', 'file', None, _('list the filename')),
223 223 ('d', 'date', None, _('list the date (short with -q)')),
224 224 ('n', 'number', None, _('list the revision number (default)')),
225 225 ('c', 'changeset', None, _('list the changeset')),
226 226 ('l', 'line-number', None, _('show line number at the first appearance'))
227 227 ] + diffwsopts + walkopts,
228 228 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
229 229 def annotate(ui, repo, *pats, **opts):
230 230 """show changeset information by line for each file
231 231
232 232 List changes in files, showing the revision id responsible for
233 233 each line
234 234
235 235 This command is useful for discovering when a change was made and
236 236 by whom.
237 237
238 238 Without the -a/--text option, annotate will avoid processing files
239 239 it detects as binary. With -a, annotate will annotate the file
240 240 anyway, although the results will probably be neither useful
241 241 nor desirable.
242 242
243 243 Returns 0 on success.
244 244 """
245 245 if opts.get('follow'):
246 246 # --follow is deprecated and now just an alias for -f/--file
247 247 # to mimic the behavior of Mercurial before version 1.5
248 248 opts['file'] = True
249 249
250 250 datefunc = ui.quiet and util.shortdate or util.datestr
251 251 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
252 252
253 253 if not pats:
254 254 raise util.Abort(_('at least one filename or pattern is required'))
255 255
256 256 hexfn = ui.debugflag and hex or short
257 257
258 258 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
259 259 ('number', ' ', lambda x: str(x[0].rev())),
260 260 ('changeset', ' ', lambda x: hexfn(x[0].node())),
261 261 ('date', ' ', getdate),
262 262 ('file', ' ', lambda x: x[0].path()),
263 263 ('line_number', ':', lambda x: str(x[1])),
264 264 ]
265 265
266 266 if (not opts.get('user') and not opts.get('changeset')
267 267 and not opts.get('date') and not opts.get('file')):
268 268 opts['number'] = True
269 269
270 270 linenumber = opts.get('line_number') is not None
271 271 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
272 272 raise util.Abort(_('at least one of -n/-c is required for -l'))
273 273
274 274 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
275 275 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
276 276
277 277 def bad(x, y):
278 278 raise util.Abort("%s: %s" % (x, y))
279 279
280 280 ctx = scmutil.revsingle(repo, opts.get('rev'))
281 281 m = scmutil.match(ctx, pats, opts)
282 282 m.bad = bad
283 283 follow = not opts.get('no_follow')
284 284 diffopts = patch.diffopts(ui, opts, section='annotate')
285 285 for abs in ctx.walk(m):
286 286 fctx = ctx[abs]
287 287 if not opts.get('text') and util.binary(fctx.data()):
288 288 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
289 289 continue
290 290
291 291 lines = fctx.annotate(follow=follow, linenumber=linenumber,
292 292 diffopts=diffopts)
293 293 pieces = []
294 294
295 295 for f, sep in funcmap:
296 296 l = [f(n) for n, dummy in lines]
297 297 if l:
298 298 sized = [(x, encoding.colwidth(x)) for x in l]
299 299 ml = max([w for x, w in sized])
300 300 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
301 301 for x, w in sized])
302 302
303 303 if pieces:
304 304 for p, l in zip(zip(*pieces), lines):
305 305 ui.write("%s: %s" % ("".join(p), l[1]))
306 306
307 307 if lines and not lines[-1][1].endswith('\n'):
308 308 ui.write('\n')
309 309
310 310 @command('archive',
311 311 [('', 'no-decode', None, _('do not pass files through decoders')),
312 312 ('p', 'prefix', '', _('directory prefix for files in archive'),
313 313 _('PREFIX')),
314 314 ('r', 'rev', '', _('revision to distribute'), _('REV')),
315 315 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
316 316 ] + subrepoopts + walkopts,
317 317 _('[OPTION]... DEST'))
318 318 def archive(ui, repo, dest, **opts):
319 319 '''create an unversioned archive of a repository revision
320 320
321 321 By default, the revision used is the parent of the working
322 322 directory; use -r/--rev to specify a different revision.
323 323
324 324 The archive type is automatically detected based on file
325 325 extension (or override using -t/--type).
326 326
327 327 .. container:: verbose
328 328
329 329 Examples:
330 330
331 331 - create a zip file containing the 1.0 release::
332 332
333 333 hg archive -r 1.0 project-1.0.zip
334 334
335 335 - create a tarball excluding .hg files::
336 336
337 337 hg archive project.tar.gz -X ".hg*"
338 338
339 339 Valid types are:
340 340
341 341 :``files``: a directory full of files (default)
342 342 :``tar``: tar archive, uncompressed
343 343 :``tbz2``: tar archive, compressed using bzip2
344 344 :``tgz``: tar archive, compressed using gzip
345 345 :``uzip``: zip archive, uncompressed
346 346 :``zip``: zip archive, compressed using deflate
347 347
348 348 The exact name of the destination archive or directory is given
349 349 using a format string; see :hg:`help export` for details.
350 350
351 351 Each member added to an archive file has a directory prefix
352 352 prepended. Use -p/--prefix to specify a format string for the
353 353 prefix. The default is the basename of the archive, with suffixes
354 354 removed.
355 355
356 356 Returns 0 on success.
357 357 '''
358 358
359 359 ctx = scmutil.revsingle(repo, opts.get('rev'))
360 360 if not ctx:
361 361 raise util.Abort(_('no working directory: please specify a revision'))
362 362 node = ctx.node()
363 363 dest = cmdutil.makefilename(repo, dest, node)
364 364 if os.path.realpath(dest) == repo.root:
365 365 raise util.Abort(_('repository root cannot be destination'))
366 366
367 367 kind = opts.get('type') or archival.guesskind(dest) or 'files'
368 368 prefix = opts.get('prefix')
369 369
370 370 if dest == '-':
371 371 if kind == 'files':
372 372 raise util.Abort(_('cannot archive plain files to stdout'))
373 373 dest = cmdutil.makefileobj(repo, dest)
374 374 if not prefix:
375 375 prefix = os.path.basename(repo.root) + '-%h'
376 376
377 377 prefix = cmdutil.makefilename(repo, prefix, node)
378 378 matchfn = scmutil.match(ctx, [], opts)
379 379 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
380 380 matchfn, prefix, subrepos=opts.get('subrepos'))
381 381
382 382 @command('backout',
383 383 [('', 'merge', None, _('merge with old dirstate parent after backout')),
384 384 ('', 'parent', '',
385 385 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
386 386 ('r', 'rev', '', _('revision to backout'), _('REV')),
387 387 ] + mergetoolopts + walkopts + commitopts + commitopts2,
388 388 _('[OPTION]... [-r] REV'))
389 389 def backout(ui, repo, node=None, rev=None, **opts):
390 390 '''reverse effect of earlier changeset
391 391
392 392 Prepare a new changeset with the effect of REV undone in the
393 393 current working directory.
394 394
395 395 If REV is the parent of the working directory, then this new changeset
396 396 is committed automatically. Otherwise, hg needs to merge the
397 397 changes and the merged result is left uncommitted.
398 398
399 399 .. note::
400
400 401 backout cannot be used to fix either an unwanted or
401 402 incorrect merge.
402 403
403 404 .. container:: verbose
404 405
405 406 By default, the pending changeset will have one parent,
406 407 maintaining a linear history. With --merge, the pending
407 408 changeset will instead have two parents: the old parent of the
408 409 working directory and a new child of REV that simply undoes REV.
409 410
410 411 Before version 1.7, the behavior without --merge was equivalent
411 412 to specifying --merge followed by :hg:`update --clean .` to
412 413 cancel the merge and leave the child of REV as a head to be
413 414 merged separately.
414 415
415 416 See :hg:`help dates` for a list of formats valid for -d/--date.
416 417
417 418 Returns 0 on success.
418 419 '''
419 420 if rev and node:
420 421 raise util.Abort(_("please specify just one revision"))
421 422
422 423 if not rev:
423 424 rev = node
424 425
425 426 if not rev:
426 427 raise util.Abort(_("please specify a revision to backout"))
427 428
428 429 date = opts.get('date')
429 430 if date:
430 431 opts['date'] = util.parsedate(date)
431 432
432 433 cmdutil.checkunfinished(repo)
433 434 cmdutil.bailifchanged(repo)
434 435 node = scmutil.revsingle(repo, rev).node()
435 436
436 437 op1, op2 = repo.dirstate.parents()
437 438 a = repo.changelog.ancestor(op1, node)
438 439 if a != node:
439 440 raise util.Abort(_('cannot backout change on a different branch'))
440 441
441 442 p1, p2 = repo.changelog.parents(node)
442 443 if p1 == nullid:
443 444 raise util.Abort(_('cannot backout a change with no parents'))
444 445 if p2 != nullid:
445 446 if not opts.get('parent'):
446 447 raise util.Abort(_('cannot backout a merge changeset'))
447 448 p = repo.lookup(opts['parent'])
448 449 if p not in (p1, p2):
449 450 raise util.Abort(_('%s is not a parent of %s') %
450 451 (short(p), short(node)))
451 452 parent = p
452 453 else:
453 454 if opts.get('parent'):
454 455 raise util.Abort(_('cannot use --parent on non-merge changeset'))
455 456 parent = p1
456 457
457 458 # the backout should appear on the same branch
458 459 wlock = repo.wlock()
459 460 try:
460 461 branch = repo.dirstate.branch()
461 462 bheads = repo.branchheads(branch)
462 463 hg.clean(repo, node, show_stats=False)
463 464 repo.dirstate.setbranch(branch)
464 465 rctx = scmutil.revsingle(repo, hex(parent))
465 466 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
466 467 if not opts.get('merge') and op1 != node:
467 468 try:
468 469 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
469 470 return hg.update(repo, op1)
470 471 finally:
471 472 ui.setconfig('ui', 'forcemerge', '')
472 473
473 474 e = cmdutil.commiteditor
474 475 if not opts['message'] and not opts['logfile']:
475 476 # we don't translate commit messages
476 477 opts['message'] = "Backed out changeset %s" % short(node)
477 478 e = cmdutil.commitforceeditor
478 479
479 480 def commitfunc(ui, repo, message, match, opts):
480 481 return repo.commit(message, opts.get('user'), opts.get('date'),
481 482 match, editor=e)
482 483 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
483 484 cmdutil.commitstatus(repo, newnode, branch, bheads)
484 485
485 486 def nice(node):
486 487 return '%d:%s' % (repo.changelog.rev(node), short(node))
487 488 ui.status(_('changeset %s backs out changeset %s\n') %
488 489 (nice(repo.changelog.tip()), nice(node)))
489 490 if opts.get('merge') and op1 != node:
490 491 hg.clean(repo, op1, show_stats=False)
491 492 ui.status(_('merging with changeset %s\n')
492 493 % nice(repo.changelog.tip()))
493 494 try:
494 495 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
495 496 return hg.merge(repo, hex(repo.changelog.tip()))
496 497 finally:
497 498 ui.setconfig('ui', 'forcemerge', '')
498 499 finally:
499 500 wlock.release()
500 501 return 0
501 502
502 503 @command('bisect',
503 504 [('r', 'reset', False, _('reset bisect state')),
504 505 ('g', 'good', False, _('mark changeset good')),
505 506 ('b', 'bad', False, _('mark changeset bad')),
506 507 ('s', 'skip', False, _('skip testing changeset')),
507 508 ('e', 'extend', False, _('extend the bisect range')),
508 509 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
509 510 ('U', 'noupdate', False, _('do not update to target'))],
510 511 _("[-gbsr] [-U] [-c CMD] [REV]"))
511 512 def bisect(ui, repo, rev=None, extra=None, command=None,
512 513 reset=None, good=None, bad=None, skip=None, extend=None,
513 514 noupdate=None):
514 515 """subdivision search of changesets
515 516
516 517 This command helps to find changesets which introduce problems. To
517 518 use, mark the earliest changeset you know exhibits the problem as
518 519 bad, then mark the latest changeset which is free from the problem
519 520 as good. Bisect will update your working directory to a revision
520 521 for testing (unless the -U/--noupdate option is specified). Once
521 522 you have performed tests, mark the working directory as good or
522 523 bad, and bisect will either update to another candidate changeset
523 524 or announce that it has found the bad revision.
524 525
525 526 As a shortcut, you can also use the revision argument to mark a
526 527 revision as good or bad without checking it out first.
527 528
528 529 If you supply a command, it will be used for automatic bisection.
529 530 The environment variable HG_NODE will contain the ID of the
530 531 changeset being tested. The exit status of the command will be
531 532 used to mark revisions as good or bad: status 0 means good, 125
532 533 means to skip the revision, 127 (command not found) will abort the
533 534 bisection, and any other non-zero exit status means the revision
534 535 is bad.
535 536
536 537 .. container:: verbose
537 538
538 539 Some examples:
539 540
540 541 - start a bisection with known bad revision 12, and good revision 34::
541 542
542 543 hg bisect --bad 34
543 544 hg bisect --good 12
544 545
545 546 - advance the current bisection by marking current revision as good or
546 547 bad::
547 548
548 549 hg bisect --good
549 550 hg bisect --bad
550 551
551 552 - mark the current revision, or a known revision, to be skipped (e.g. if
552 553 that revision is not usable because of another issue)::
553 554
554 555 hg bisect --skip
555 556 hg bisect --skip 23
556 557
557 558 - skip all revisions that do not touch directories ``foo`` or ``bar``::
558 559
559 560 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
560 561
561 562 - forget the current bisection::
562 563
563 564 hg bisect --reset
564 565
565 566 - use 'make && make tests' to automatically find the first broken
566 567 revision::
567 568
568 569 hg bisect --reset
569 570 hg bisect --bad 34
570 571 hg bisect --good 12
571 572 hg bisect --command "make && make tests"
572 573
573 574 - see all changesets whose states are already known in the current
574 575 bisection::
575 576
576 577 hg log -r "bisect(pruned)"
577 578
578 579 - see the changeset currently being bisected (especially useful
579 580 if running with -U/--noupdate)::
580 581
581 582 hg log -r "bisect(current)"
582 583
583 584 - see all changesets that took part in the current bisection::
584 585
585 586 hg log -r "bisect(range)"
586 587
587 588 - with the graphlog extension, you can even get a nice graph::
588 589
589 590 hg log --graph -r "bisect(range)"
590 591
591 592 See :hg:`help revsets` for more about the `bisect()` keyword.
592 593
593 594 Returns 0 on success.
594 595 """
595 596 def extendbisectrange(nodes, good):
596 597 # bisect is incomplete when it ends on a merge node and
597 598 # one of the parent was not checked.
598 599 parents = repo[nodes[0]].parents()
599 600 if len(parents) > 1:
600 601 side = good and state['bad'] or state['good']
601 602 num = len(set(i.node() for i in parents) & set(side))
602 603 if num == 1:
603 604 return parents[0].ancestor(parents[1])
604 605 return None
605 606
606 607 def print_result(nodes, good):
607 608 displayer = cmdutil.show_changeset(ui, repo, {})
608 609 if len(nodes) == 1:
609 610 # narrowed it down to a single revision
610 611 if good:
611 612 ui.write(_("The first good revision is:\n"))
612 613 else:
613 614 ui.write(_("The first bad revision is:\n"))
614 615 displayer.show(repo[nodes[0]])
615 616 extendnode = extendbisectrange(nodes, good)
616 617 if extendnode is not None:
617 618 ui.write(_('Not all ancestors of this changeset have been'
618 619 ' checked.\nUse bisect --extend to continue the '
619 620 'bisection from\nthe common ancestor, %s.\n')
620 621 % extendnode)
621 622 else:
622 623 # multiple possible revisions
623 624 if good:
624 625 ui.write(_("Due to skipped revisions, the first "
625 626 "good revision could be any of:\n"))
626 627 else:
627 628 ui.write(_("Due to skipped revisions, the first "
628 629 "bad revision could be any of:\n"))
629 630 for n in nodes:
630 631 displayer.show(repo[n])
631 632 displayer.close()
632 633
633 634 def check_state(state, interactive=True):
634 635 if not state['good'] or not state['bad']:
635 636 if (good or bad or skip or reset) and interactive:
636 637 return
637 638 if not state['good']:
638 639 raise util.Abort(_('cannot bisect (no known good revisions)'))
639 640 else:
640 641 raise util.Abort(_('cannot bisect (no known bad revisions)'))
641 642 return True
642 643
643 644 # backward compatibility
644 645 if rev in "good bad reset init".split():
645 646 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
646 647 cmd, rev, extra = rev, extra, None
647 648 if cmd == "good":
648 649 good = True
649 650 elif cmd == "bad":
650 651 bad = True
651 652 else:
652 653 reset = True
653 654 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
654 655 raise util.Abort(_('incompatible arguments'))
655 656
656 657 cmdutil.checkunfinished(repo)
657 658
658 659 if reset:
659 660 p = repo.join("bisect.state")
660 661 if os.path.exists(p):
661 662 os.unlink(p)
662 663 return
663 664
664 665 state = hbisect.load_state(repo)
665 666
666 667 if command:
667 668 changesets = 1
668 669 try:
669 670 node = state['current'][0]
670 671 except LookupError:
671 672 if noupdate:
672 673 raise util.Abort(_('current bisect revision is unknown - '
673 674 'start a new bisect to fix'))
674 675 node, p2 = repo.dirstate.parents()
675 676 if p2 != nullid:
676 677 raise util.Abort(_('current bisect revision is a merge'))
677 678 try:
678 679 while changesets:
679 680 # update state
680 681 state['current'] = [node]
681 682 hbisect.save_state(repo, state)
682 683 status = util.system(command,
683 684 environ={'HG_NODE': hex(node)},
684 685 out=ui.fout)
685 686 if status == 125:
686 687 transition = "skip"
687 688 elif status == 0:
688 689 transition = "good"
689 690 # status < 0 means process was killed
690 691 elif status == 127:
691 692 raise util.Abort(_("failed to execute %s") % command)
692 693 elif status < 0:
693 694 raise util.Abort(_("%s killed") % command)
694 695 else:
695 696 transition = "bad"
696 697 ctx = scmutil.revsingle(repo, rev, node)
697 698 rev = None # clear for future iterations
698 699 state[transition].append(ctx.node())
699 700 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
700 701 check_state(state, interactive=False)
701 702 # bisect
702 703 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
703 704 # update to next check
704 705 node = nodes[0]
705 706 if not noupdate:
706 707 cmdutil.bailifchanged(repo)
707 708 hg.clean(repo, node, show_stats=False)
708 709 finally:
709 710 state['current'] = [node]
710 711 hbisect.save_state(repo, state)
711 712 print_result(nodes, good)
712 713 return
713 714
714 715 # update state
715 716
716 717 if rev:
717 718 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
718 719 else:
719 720 nodes = [repo.lookup('.')]
720 721
721 722 if good or bad or skip:
722 723 if good:
723 724 state['good'] += nodes
724 725 elif bad:
725 726 state['bad'] += nodes
726 727 elif skip:
727 728 state['skip'] += nodes
728 729 hbisect.save_state(repo, state)
729 730
730 731 if not check_state(state):
731 732 return
732 733
733 734 # actually bisect
734 735 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
735 736 if extend:
736 737 if not changesets:
737 738 extendnode = extendbisectrange(nodes, good)
738 739 if extendnode is not None:
739 740 ui.write(_("Extending search to changeset %d:%s\n"
740 741 % (extendnode.rev(), extendnode)))
741 742 state['current'] = [extendnode.node()]
742 743 hbisect.save_state(repo, state)
743 744 if noupdate:
744 745 return
745 746 cmdutil.bailifchanged(repo)
746 747 return hg.clean(repo, extendnode.node())
747 748 raise util.Abort(_("nothing to extend"))
748 749
749 750 if changesets == 0:
750 751 print_result(nodes, good)
751 752 else:
752 753 assert len(nodes) == 1 # only a single node can be tested next
753 754 node = nodes[0]
754 755 # compute the approximate number of remaining tests
755 756 tests, size = 0, 2
756 757 while size <= changesets:
757 758 tests, size = tests + 1, size * 2
758 759 rev = repo.changelog.rev(node)
759 760 ui.write(_("Testing changeset %d:%s "
760 761 "(%d changesets remaining, ~%d tests)\n")
761 762 % (rev, short(node), changesets, tests))
762 763 state['current'] = [node]
763 764 hbisect.save_state(repo, state)
764 765 if not noupdate:
765 766 cmdutil.bailifchanged(repo)
766 767 return hg.clean(repo, node)
767 768
768 769 @command('bookmarks|bookmark',
769 770 [('f', 'force', False, _('force')),
770 771 ('r', 'rev', '', _('revision'), _('REV')),
771 772 ('d', 'delete', False, _('delete a given bookmark')),
772 773 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
773 774 ('i', 'inactive', False, _('mark a bookmark inactive'))],
774 775 _('hg bookmarks [OPTIONS]... [NAME]...'))
775 776 def bookmark(ui, repo, *names, **opts):
776 777 '''track a line of development with movable markers
777 778
778 779 Bookmarks are pointers to certain commits that move when committing.
779 780 Bookmarks are local. They can be renamed, copied and deleted. It is
780 781 possible to use :hg:`merge NAME` to merge from a given bookmark, and
781 782 :hg:`update NAME` to update to a given bookmark.
782 783
783 784 You can use :hg:`bookmark NAME` to set a bookmark on the working
784 785 directory's parent revision with the given name. If you specify
785 786 a revision using -r REV (where REV may be an existing bookmark),
786 787 the bookmark is assigned to that revision.
787 788
788 789 Bookmarks can be pushed and pulled between repositories (see :hg:`help
789 790 push` and :hg:`help pull`). This requires both the local and remote
790 791 repositories to support bookmarks. For versions prior to 1.8, this means
791 792 the bookmarks extension must be enabled.
792 793
793 794 If you set a bookmark called '@', new clones of the repository will
794 795 have that revision checked out (and the bookmark made active) by
795 796 default.
796 797
797 798 With -i/--inactive, the new bookmark will not be made the active
798 799 bookmark. If -r/--rev is given, the new bookmark will not be made
799 800 active even if -i/--inactive is not given. If no NAME is given, the
800 801 current active bookmark will be marked inactive.
801 802 '''
802 803 force = opts.get('force')
803 804 rev = opts.get('rev')
804 805 delete = opts.get('delete')
805 806 rename = opts.get('rename')
806 807 inactive = opts.get('inactive')
807 808
808 809 hexfn = ui.debugflag and hex or short
809 810 marks = repo._bookmarks
810 811 cur = repo.changectx('.').node()
811 812
812 813 def checkformat(mark):
813 814 mark = mark.strip()
814 815 if not mark:
815 816 raise util.Abort(_("bookmark names cannot consist entirely of "
816 817 "whitespace"))
817 818 scmutil.checknewlabel(repo, mark, 'bookmark')
818 819 return mark
819 820
820 821 def checkconflict(repo, mark, force=False, target=None):
821 822 if mark in marks and not force:
822 823 if target:
823 824 if marks[mark] == target and target == cur:
824 825 # re-activating a bookmark
825 826 return
826 827 anc = repo.changelog.ancestors([repo[target].rev()])
827 828 bmctx = repo[marks[mark]]
828 829 divs = [repo[b].node() for b in marks
829 830 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
830 831
831 832 # allow resolving a single divergent bookmark even if moving
832 833 # the bookmark across branches when a revision is specified
833 834 # that contains a divergent bookmark
834 835 if bmctx.rev() not in anc and target in divs:
835 836 bookmarks.deletedivergent(repo, [target], mark)
836 837 return
837 838
838 839 deletefrom = [b for b in divs
839 840 if repo[b].rev() in anc or b == target]
840 841 bookmarks.deletedivergent(repo, deletefrom, mark)
841 842 if bmctx.rev() in anc:
842 843 ui.status(_("moving bookmark '%s' forward from %s\n") %
843 844 (mark, short(bmctx.node())))
844 845 return
845 846 raise util.Abort(_("bookmark '%s' already exists "
846 847 "(use -f to force)") % mark)
847 848 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
848 849 and not force):
849 850 raise util.Abort(
850 851 _("a bookmark cannot have the name of an existing branch"))
851 852
852 853 if delete and rename:
853 854 raise util.Abort(_("--delete and --rename are incompatible"))
854 855 if delete and rev:
855 856 raise util.Abort(_("--rev is incompatible with --delete"))
856 857 if rename and rev:
857 858 raise util.Abort(_("--rev is incompatible with --rename"))
858 859 if not names and (delete or rev):
859 860 raise util.Abort(_("bookmark name required"))
860 861
861 862 if delete:
862 863 for mark in names:
863 864 if mark not in marks:
864 865 raise util.Abort(_("bookmark '%s' does not exist") % mark)
865 866 if mark == repo._bookmarkcurrent:
866 867 bookmarks.setcurrent(repo, None)
867 868 del marks[mark]
868 869 marks.write()
869 870
870 871 elif rename:
871 872 if not names:
872 873 raise util.Abort(_("new bookmark name required"))
873 874 elif len(names) > 1:
874 875 raise util.Abort(_("only one new bookmark name allowed"))
875 876 mark = checkformat(names[0])
876 877 if rename not in marks:
877 878 raise util.Abort(_("bookmark '%s' does not exist") % rename)
878 879 checkconflict(repo, mark, force)
879 880 marks[mark] = marks[rename]
880 881 if repo._bookmarkcurrent == rename and not inactive:
881 882 bookmarks.setcurrent(repo, mark)
882 883 del marks[rename]
883 884 marks.write()
884 885
885 886 elif names:
886 887 newact = None
887 888 for mark in names:
888 889 mark = checkformat(mark)
889 890 if newact is None:
890 891 newact = mark
891 892 if inactive and mark == repo._bookmarkcurrent:
892 893 bookmarks.setcurrent(repo, None)
893 894 return
894 895 tgt = cur
895 896 if rev:
896 897 tgt = scmutil.revsingle(repo, rev).node()
897 898 checkconflict(repo, mark, force, tgt)
898 899 marks[mark] = tgt
899 900 if not inactive and cur == marks[newact] and not rev:
900 901 bookmarks.setcurrent(repo, newact)
901 902 elif cur != tgt and newact == repo._bookmarkcurrent:
902 903 bookmarks.setcurrent(repo, None)
903 904 marks.write()
904 905
905 906 # Same message whether trying to deactivate the current bookmark (-i
906 907 # with no NAME) or listing bookmarks
907 908 elif len(marks) == 0:
908 909 ui.status(_("no bookmarks set\n"))
909 910
910 911 elif inactive:
911 912 if not repo._bookmarkcurrent:
912 913 ui.status(_("no active bookmark\n"))
913 914 else:
914 915 bookmarks.setcurrent(repo, None)
915 916
916 917 else: # show bookmarks
917 918 for bmark, n in sorted(marks.iteritems()):
918 919 current = repo._bookmarkcurrent
919 920 if bmark == current:
920 921 prefix, label = '*', 'bookmarks.current'
921 922 else:
922 923 prefix, label = ' ', ''
923 924
924 925 if ui.quiet:
925 926 ui.write("%s\n" % bmark, label=label)
926 927 else:
927 928 ui.write(" %s %-25s %d:%s\n" % (
928 929 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
929 930 label=label)
930 931
931 932 @command('branch',
932 933 [('f', 'force', None,
933 934 _('set branch name even if it shadows an existing branch')),
934 935 ('C', 'clean', None, _('reset branch name to parent branch name'))],
935 936 _('[-fC] [NAME]'))
936 937 def branch(ui, repo, label=None, **opts):
937 938 """set or show the current branch name
938 939
939 940 .. note::
941
940 942 Branch names are permanent and global. Use :hg:`bookmark` to create a
941 943 light-weight bookmark instead. See :hg:`help glossary` for more
942 944 information about named branches and bookmarks.
943 945
944 946 With no argument, show the current branch name. With one argument,
945 947 set the working directory branch name (the branch will not exist
946 948 in the repository until the next commit). Standard practice
947 949 recommends that primary development take place on the 'default'
948 950 branch.
949 951
950 952 Unless -f/--force is specified, branch will not let you set a
951 953 branch name that already exists, even if it's inactive.
952 954
953 955 Use -C/--clean to reset the working directory branch to that of
954 956 the parent of the working directory, negating a previous branch
955 957 change.
956 958
957 959 Use the command :hg:`update` to switch to an existing branch. Use
958 960 :hg:`commit --close-branch` to mark this branch as closed.
959 961
960 962 Returns 0 on success.
961 963 """
962 964 if label:
963 965 label = label.strip()
964 966
965 967 if not opts.get('clean') and not label:
966 968 ui.write("%s\n" % repo.dirstate.branch())
967 969 return
968 970
969 971 wlock = repo.wlock()
970 972 try:
971 973 if opts.get('clean'):
972 974 label = repo[None].p1().branch()
973 975 repo.dirstate.setbranch(label)
974 976 ui.status(_('reset working directory to branch %s\n') % label)
975 977 elif label:
976 978 if not opts.get('force') and label in repo.branchmap():
977 979 if label not in [p.branch() for p in repo.parents()]:
978 980 raise util.Abort(_('a branch of the same name already'
979 981 ' exists'),
980 982 # i18n: "it" refers to an existing branch
981 983 hint=_("use 'hg update' to switch to it"))
982 984 scmutil.checknewlabel(repo, label, 'branch')
983 985 repo.dirstate.setbranch(label)
984 986 ui.status(_('marked working directory as branch %s\n') % label)
985 987 ui.status(_('(branches are permanent and global, '
986 988 'did you want a bookmark?)\n'))
987 989 finally:
988 990 wlock.release()
989 991
990 992 @command('branches',
991 993 [('a', 'active', False, _('show only branches that have unmerged heads')),
992 994 ('c', 'closed', False, _('show normal and closed branches'))],
993 995 _('[-ac]'))
994 996 def branches(ui, repo, active=False, closed=False):
995 997 """list repository named branches
996 998
997 999 List the repository's named branches, indicating which ones are
998 1000 inactive. If -c/--closed is specified, also list branches which have
999 1001 been marked closed (see :hg:`commit --close-branch`).
1000 1002
1001 1003 If -a/--active is specified, only show active branches. A branch
1002 1004 is considered active if it contains repository heads.
1003 1005
1004 1006 Use the command :hg:`update` to switch to an existing branch.
1005 1007
1006 1008 Returns 0.
1007 1009 """
1008 1010
1009 1011 hexfunc = ui.debugflag and hex or short
1010 1012
1011 1013 activebranches = set([repo[n].branch() for n in repo.heads()])
1012 1014 branches = []
1013 1015 for tag, heads in repo.branchmap().iteritems():
1014 1016 for h in reversed(heads):
1015 1017 ctx = repo[h]
1016 1018 isopen = not ctx.closesbranch()
1017 1019 if isopen:
1018 1020 tip = ctx
1019 1021 break
1020 1022 else:
1021 1023 tip = repo[heads[-1]]
1022 1024 isactive = tag in activebranches and isopen
1023 1025 branches.append((tip, isactive, isopen))
1024 1026 branches.sort(key=lambda i: (i[1], i[0].rev(), i[0].branch(), i[2]),
1025 1027 reverse=True)
1026 1028
1027 1029 for ctx, isactive, isopen in branches:
1028 1030 if (not active) or isactive:
1029 1031 if isactive:
1030 1032 label = 'branches.active'
1031 1033 notice = ''
1032 1034 elif not isopen:
1033 1035 if not closed:
1034 1036 continue
1035 1037 label = 'branches.closed'
1036 1038 notice = _(' (closed)')
1037 1039 else:
1038 1040 label = 'branches.inactive'
1039 1041 notice = _(' (inactive)')
1040 1042 if ctx.branch() == repo.dirstate.branch():
1041 1043 label = 'branches.current'
1042 1044 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(ctx.branch()))
1043 1045 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
1044 1046 'log.changeset changeset.%s' % ctx.phasestr())
1045 1047 tag = ui.label(ctx.branch(), label)
1046 1048 if ui.quiet:
1047 1049 ui.write("%s\n" % tag)
1048 1050 else:
1049 1051 ui.write("%s %s%s\n" % (tag, rev, notice))
1050 1052
1051 1053 @command('bundle',
1052 1054 [('f', 'force', None, _('run even when the destination is unrelated')),
1053 1055 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1054 1056 _('REV')),
1055 1057 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1056 1058 _('BRANCH')),
1057 1059 ('', 'base', [],
1058 1060 _('a base changeset assumed to be available at the destination'),
1059 1061 _('REV')),
1060 1062 ('a', 'all', None, _('bundle all changesets in the repository')),
1061 1063 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1062 1064 ] + remoteopts,
1063 1065 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1064 1066 def bundle(ui, repo, fname, dest=None, **opts):
1065 1067 """create a changegroup file
1066 1068
1067 1069 Generate a compressed changegroup file collecting changesets not
1068 1070 known to be in another repository.
1069 1071
1070 1072 If you omit the destination repository, then hg assumes the
1071 1073 destination will have all the nodes you specify with --base
1072 1074 parameters. To create a bundle containing all changesets, use
1073 1075 -a/--all (or --base null).
1074 1076
1075 1077 You can change compression method with the -t/--type option.
1076 1078 The available compression methods are: none, bzip2, and
1077 1079 gzip (by default, bundles are compressed using bzip2).
1078 1080
1079 1081 The bundle file can then be transferred using conventional means
1080 1082 and applied to another repository with the unbundle or pull
1081 1083 command. This is useful when direct push and pull are not
1082 1084 available or when exporting an entire repository is undesirable.
1083 1085
1084 1086 Applying bundles preserves all changeset contents including
1085 1087 permissions, copy/rename information, and revision history.
1086 1088
1087 1089 Returns 0 on success, 1 if no changes found.
1088 1090 """
1089 1091 revs = None
1090 1092 if 'rev' in opts:
1091 1093 revs = scmutil.revrange(repo, opts['rev'])
1092 1094
1093 1095 bundletype = opts.get('type', 'bzip2').lower()
1094 1096 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1095 1097 bundletype = btypes.get(bundletype)
1096 1098 if bundletype not in changegroup.bundletypes:
1097 1099 raise util.Abort(_('unknown bundle type specified with --type'))
1098 1100
1099 1101 if opts.get('all'):
1100 1102 base = ['null']
1101 1103 else:
1102 1104 base = scmutil.revrange(repo, opts.get('base'))
1103 1105 # TODO: get desired bundlecaps from command line.
1104 1106 bundlecaps = None
1105 1107 if base:
1106 1108 if dest:
1107 1109 raise util.Abort(_("--base is incompatible with specifying "
1108 1110 "a destination"))
1109 1111 common = [repo.lookup(rev) for rev in base]
1110 1112 heads = revs and map(repo.lookup, revs) or revs
1111 1113 cg = repo.getbundle('bundle', heads=heads, common=common,
1112 1114 bundlecaps=bundlecaps)
1113 1115 outgoing = None
1114 1116 else:
1115 1117 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1116 1118 dest, branches = hg.parseurl(dest, opts.get('branch'))
1117 1119 other = hg.peer(repo, opts, dest)
1118 1120 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1119 1121 heads = revs and map(repo.lookup, revs) or revs
1120 1122 outgoing = discovery.findcommonoutgoing(repo, other,
1121 1123 onlyheads=heads,
1122 1124 force=opts.get('force'),
1123 1125 portable=True)
1124 1126 cg = repo.getlocalbundle('bundle', outgoing, bundlecaps)
1125 1127 if not cg:
1126 1128 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1127 1129 return 1
1128 1130
1129 1131 changegroup.writebundle(cg, fname, bundletype)
1130 1132
1131 1133 @command('cat',
1132 1134 [('o', 'output', '',
1133 1135 _('print output to file with formatted name'), _('FORMAT')),
1134 1136 ('r', 'rev', '', _('print the given revision'), _('REV')),
1135 1137 ('', 'decode', None, _('apply any matching decode filter')),
1136 1138 ] + walkopts,
1137 1139 _('[OPTION]... FILE...'))
1138 1140 def cat(ui, repo, file1, *pats, **opts):
1139 1141 """output the current or given revision of files
1140 1142
1141 1143 Print the specified files as they were at the given revision. If
1142 1144 no revision is given, the parent of the working directory is used.
1143 1145
1144 1146 Output may be to a file, in which case the name of the file is
1145 1147 given using a format string. The formatting rules are the same as
1146 1148 for the export command, with the following additions:
1147 1149
1148 1150 :``%s``: basename of file being printed
1149 1151 :``%d``: dirname of file being printed, or '.' if in repository root
1150 1152 :``%p``: root-relative path name of file being printed
1151 1153
1152 1154 Returns 0 on success.
1153 1155 """
1154 1156 ctx = scmutil.revsingle(repo, opts.get('rev'))
1155 1157 err = 1
1156 1158 m = scmutil.match(ctx, (file1,) + pats, opts)
1157 1159 for abs in ctx.walk(m):
1158 1160 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1159 1161 pathname=abs)
1160 1162 data = ctx[abs].data()
1161 1163 if opts.get('decode'):
1162 1164 data = repo.wwritedata(abs, data)
1163 1165 fp.write(data)
1164 1166 fp.close()
1165 1167 err = 0
1166 1168 return err
1167 1169
1168 1170 @command('^clone',
1169 1171 [('U', 'noupdate', None,
1170 1172 _('the clone will include an empty working copy (only a repository)')),
1171 1173 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1172 1174 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1173 1175 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1174 1176 ('', 'pull', None, _('use pull protocol to copy metadata')),
1175 1177 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1176 1178 ] + remoteopts,
1177 1179 _('[OPTION]... SOURCE [DEST]'))
1178 1180 def clone(ui, source, dest=None, **opts):
1179 1181 """make a copy of an existing repository
1180 1182
1181 1183 Create a copy of an existing repository in a new directory.
1182 1184
1183 1185 If no destination directory name is specified, it defaults to the
1184 1186 basename of the source.
1185 1187
1186 1188 The location of the source is added to the new repository's
1187 1189 ``.hg/hgrc`` file, as the default to be used for future pulls.
1188 1190
1189 1191 Only local paths and ``ssh://`` URLs are supported as
1190 1192 destinations. For ``ssh://`` destinations, no working directory or
1191 1193 ``.hg/hgrc`` will be created on the remote side.
1192 1194
1193 1195 To pull only a subset of changesets, specify one or more revisions
1194 1196 identifiers with -r/--rev or branches with -b/--branch. The
1195 1197 resulting clone will contain only the specified changesets and
1196 1198 their ancestors. These options (or 'clone src#rev dest') imply
1197 1199 --pull, even for local source repositories. Note that specifying a
1198 1200 tag will include the tagged changeset but not the changeset
1199 1201 containing the tag.
1200 1202
1201 1203 If the source repository has a bookmark called '@' set, that
1202 1204 revision will be checked out in the new repository by default.
1203 1205
1204 1206 To check out a particular version, use -u/--update, or
1205 1207 -U/--noupdate to create a clone with no working directory.
1206 1208
1207 1209 .. container:: verbose
1208 1210
1209 1211 For efficiency, hardlinks are used for cloning whenever the
1210 1212 source and destination are on the same filesystem (note this
1211 1213 applies only to the repository data, not to the working
1212 1214 directory). Some filesystems, such as AFS, implement hardlinking
1213 1215 incorrectly, but do not report errors. In these cases, use the
1214 1216 --pull option to avoid hardlinking.
1215 1217
1216 1218 In some cases, you can clone repositories and the working
1217 1219 directory using full hardlinks with ::
1218 1220
1219 1221 $ cp -al REPO REPOCLONE
1220 1222
1221 1223 This is the fastest way to clone, but it is not always safe. The
1222 1224 operation is not atomic (making sure REPO is not modified during
1223 1225 the operation is up to you) and you have to make sure your
1224 1226 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1225 1227 so). Also, this is not compatible with certain extensions that
1226 1228 place their metadata under the .hg directory, such as mq.
1227 1229
1228 1230 Mercurial will update the working directory to the first applicable
1229 1231 revision from this list:
1230 1232
1231 1233 a) null if -U or the source repository has no changesets
1232 1234 b) if -u . and the source repository is local, the first parent of
1233 1235 the source repository's working directory
1234 1236 c) the changeset specified with -u (if a branch name, this means the
1235 1237 latest head of that branch)
1236 1238 d) the changeset specified with -r
1237 1239 e) the tipmost head specified with -b
1238 1240 f) the tipmost head specified with the url#branch source syntax
1239 1241 g) the revision marked with the '@' bookmark, if present
1240 1242 h) the tipmost head of the default branch
1241 1243 i) tip
1242 1244
1243 1245 Examples:
1244 1246
1245 1247 - clone a remote repository to a new directory named hg/::
1246 1248
1247 1249 hg clone http://selenic.com/hg
1248 1250
1249 1251 - create a lightweight local clone::
1250 1252
1251 1253 hg clone project/ project-feature/
1252 1254
1253 1255 - clone from an absolute path on an ssh server (note double-slash)::
1254 1256
1255 1257 hg clone ssh://user@server//home/projects/alpha/
1256 1258
1257 1259 - do a high-speed clone over a LAN while checking out a
1258 1260 specified version::
1259 1261
1260 1262 hg clone --uncompressed http://server/repo -u 1.5
1261 1263
1262 1264 - create a repository without changesets after a particular revision::
1263 1265
1264 1266 hg clone -r 04e544 experimental/ good/
1265 1267
1266 1268 - clone (and track) a particular named branch::
1267 1269
1268 1270 hg clone http://selenic.com/hg#stable
1269 1271
1270 1272 See :hg:`help urls` for details on specifying URLs.
1271 1273
1272 1274 Returns 0 on success.
1273 1275 """
1274 1276 if opts.get('noupdate') and opts.get('updaterev'):
1275 1277 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1276 1278
1277 1279 r = hg.clone(ui, opts, source, dest,
1278 1280 pull=opts.get('pull'),
1279 1281 stream=opts.get('uncompressed'),
1280 1282 rev=opts.get('rev'),
1281 1283 update=opts.get('updaterev') or not opts.get('noupdate'),
1282 1284 branch=opts.get('branch'))
1283 1285
1284 1286 return r is None
1285 1287
1286 1288 @command('^commit|ci',
1287 1289 [('A', 'addremove', None,
1288 1290 _('mark new/missing files as added/removed before committing')),
1289 1291 ('', 'close-branch', None,
1290 1292 _('mark a branch as closed, hiding it from the branch list')),
1291 1293 ('', 'amend', None, _('amend the parent of the working dir')),
1292 1294 ('s', 'secret', None, _('use the secret phase for committing')),
1293 1295 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1294 1296 _('[OPTION]... [FILE]...'))
1295 1297 def commit(ui, repo, *pats, **opts):
1296 1298 """commit the specified files or all outstanding changes
1297 1299
1298 1300 Commit changes to the given files into the repository. Unlike a
1299 1301 centralized SCM, this operation is a local operation. See
1300 1302 :hg:`push` for a way to actively distribute your changes.
1301 1303
1302 1304 If a list of files is omitted, all changes reported by :hg:`status`
1303 1305 will be committed.
1304 1306
1305 1307 If you are committing the result of a merge, do not provide any
1306 1308 filenames or -I/-X filters.
1307 1309
1308 1310 If no commit message is specified, Mercurial starts your
1309 1311 configured editor where you can enter a message. In case your
1310 1312 commit fails, you will find a backup of your message in
1311 1313 ``.hg/last-message.txt``.
1312 1314
1313 1315 The --amend flag can be used to amend the parent of the
1314 1316 working directory with a new commit that contains the changes
1315 1317 in the parent in addition to those currently reported by :hg:`status`,
1316 1318 if there are any. The old commit is stored in a backup bundle in
1317 1319 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1318 1320 on how to restore it).
1319 1321
1320 1322 Message, user and date are taken from the amended commit unless
1321 1323 specified. When a message isn't specified on the command line,
1322 1324 the editor will open with the message of the amended commit.
1323 1325
1324 1326 It is not possible to amend public changesets (see :hg:`help phases`)
1325 1327 or changesets that have children.
1326 1328
1327 1329 See :hg:`help dates` for a list of formats valid for -d/--date.
1328 1330
1329 1331 Returns 0 on success, 1 if nothing changed.
1330 1332 """
1331 1333 if opts.get('subrepos'):
1332 1334 if opts.get('amend'):
1333 1335 raise util.Abort(_('cannot amend with --subrepos'))
1334 1336 # Let --subrepos on the command line override config setting.
1335 1337 ui.setconfig('ui', 'commitsubrepos', True)
1336 1338
1337 1339 # Save this for restoring it later
1338 1340 oldcommitphase = ui.config('phases', 'new-commit')
1339 1341
1340 1342 cmdutil.checkunfinished(repo, commit=True)
1341 1343
1342 1344 branch = repo[None].branch()
1343 1345 bheads = repo.branchheads(branch)
1344 1346
1345 1347 extra = {}
1346 1348 if opts.get('close_branch'):
1347 1349 extra['close'] = 1
1348 1350
1349 1351 if not bheads:
1350 1352 raise util.Abort(_('can only close branch heads'))
1351 1353 elif opts.get('amend'):
1352 1354 if repo.parents()[0].p1().branch() != branch and \
1353 1355 repo.parents()[0].p2().branch() != branch:
1354 1356 raise util.Abort(_('can only close branch heads'))
1355 1357
1356 1358 if opts.get('amend'):
1357 1359 if ui.configbool('ui', 'commitsubrepos'):
1358 1360 raise util.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1359 1361
1360 1362 old = repo['.']
1361 1363 if old.phase() == phases.public:
1362 1364 raise util.Abort(_('cannot amend public changesets'))
1363 1365 if len(repo[None].parents()) > 1:
1364 1366 raise util.Abort(_('cannot amend while merging'))
1365 1367 if (not obsolete._enabled) and old.children():
1366 1368 raise util.Abort(_('cannot amend changeset with children'))
1367 1369
1368 1370 e = cmdutil.commiteditor
1369 1371 if opts.get('force_editor'):
1370 1372 e = cmdutil.commitforceeditor
1371 1373
1372 1374 def commitfunc(ui, repo, message, match, opts):
1373 1375 editor = e
1374 1376 # message contains text from -m or -l, if it's empty,
1375 1377 # open the editor with the old message
1376 1378 if not message:
1377 1379 message = old.description()
1378 1380 editor = cmdutil.commitforceeditor
1379 1381 try:
1380 1382 if opts.get('secret'):
1381 1383 ui.setconfig('phases', 'new-commit', 'secret')
1382 1384
1383 1385 return repo.commit(message,
1384 1386 opts.get('user') or old.user(),
1385 1387 opts.get('date') or old.date(),
1386 1388 match,
1387 1389 editor=editor,
1388 1390 extra=extra)
1389 1391 finally:
1390 1392 ui.setconfig('phases', 'new-commit', oldcommitphase)
1391 1393
1392 1394 current = repo._bookmarkcurrent
1393 1395 marks = old.bookmarks()
1394 1396 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1395 1397 if node == old.node():
1396 1398 ui.status(_("nothing changed\n"))
1397 1399 return 1
1398 1400 elif marks:
1399 1401 ui.debug('moving bookmarks %r from %s to %s\n' %
1400 1402 (marks, old.hex(), hex(node)))
1401 1403 newmarks = repo._bookmarks
1402 1404 for bm in marks:
1403 1405 newmarks[bm] = node
1404 1406 if bm == current:
1405 1407 bookmarks.setcurrent(repo, bm)
1406 1408 newmarks.write()
1407 1409 else:
1408 1410 e = cmdutil.commiteditor
1409 1411 if opts.get('force_editor'):
1410 1412 e = cmdutil.commitforceeditor
1411 1413
1412 1414 def commitfunc(ui, repo, message, match, opts):
1413 1415 try:
1414 1416 if opts.get('secret'):
1415 1417 ui.setconfig('phases', 'new-commit', 'secret')
1416 1418
1417 1419 return repo.commit(message, opts.get('user'), opts.get('date'),
1418 1420 match, editor=e, extra=extra)
1419 1421 finally:
1420 1422 ui.setconfig('phases', 'new-commit', oldcommitphase)
1421 1423
1422 1424
1423 1425 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1424 1426
1425 1427 if not node:
1426 1428 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1427 1429 if stat[3]:
1428 1430 ui.status(_("nothing changed (%d missing files, see "
1429 1431 "'hg status')\n") % len(stat[3]))
1430 1432 else:
1431 1433 ui.status(_("nothing changed\n"))
1432 1434 return 1
1433 1435
1434 1436 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1435 1437
1436 1438 @command('copy|cp',
1437 1439 [('A', 'after', None, _('record a copy that has already occurred')),
1438 1440 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1439 1441 ] + walkopts + dryrunopts,
1440 1442 _('[OPTION]... [SOURCE]... DEST'))
1441 1443 def copy(ui, repo, *pats, **opts):
1442 1444 """mark files as copied for the next commit
1443 1445
1444 1446 Mark dest as having copies of source files. If dest is a
1445 1447 directory, copies are put in that directory. If dest is a file,
1446 1448 the source must be a single file.
1447 1449
1448 1450 By default, this command copies the contents of files as they
1449 1451 exist in the working directory. If invoked with -A/--after, the
1450 1452 operation is recorded, but no copying is performed.
1451 1453
1452 1454 This command takes effect with the next commit. To undo a copy
1453 1455 before that, see :hg:`revert`.
1454 1456
1455 1457 Returns 0 on success, 1 if errors are encountered.
1456 1458 """
1457 1459 wlock = repo.wlock(False)
1458 1460 try:
1459 1461 return cmdutil.copy(ui, repo, pats, opts)
1460 1462 finally:
1461 1463 wlock.release()
1462 1464
1463 1465 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1464 1466 def debugancestor(ui, repo, *args):
1465 1467 """find the ancestor revision of two revisions in a given index"""
1466 1468 if len(args) == 3:
1467 1469 index, rev1, rev2 = args
1468 1470 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1469 1471 lookup = r.lookup
1470 1472 elif len(args) == 2:
1471 1473 if not repo:
1472 1474 raise util.Abort(_("there is no Mercurial repository here "
1473 1475 "(.hg not found)"))
1474 1476 rev1, rev2 = args
1475 1477 r = repo.changelog
1476 1478 lookup = repo.lookup
1477 1479 else:
1478 1480 raise util.Abort(_('either two or three arguments required'))
1479 1481 a = r.ancestor(lookup(rev1), lookup(rev2))
1480 1482 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1481 1483
1482 1484 @command('debugbuilddag',
1483 1485 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1484 1486 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1485 1487 ('n', 'new-file', None, _('add new file at each rev'))],
1486 1488 _('[OPTION]... [TEXT]'))
1487 1489 def debugbuilddag(ui, repo, text=None,
1488 1490 mergeable_file=False,
1489 1491 overwritten_file=False,
1490 1492 new_file=False):
1491 1493 """builds a repo with a given DAG from scratch in the current empty repo
1492 1494
1493 1495 The description of the DAG is read from stdin if not given on the
1494 1496 command line.
1495 1497
1496 1498 Elements:
1497 1499
1498 1500 - "+n" is a linear run of n nodes based on the current default parent
1499 1501 - "." is a single node based on the current default parent
1500 1502 - "$" resets the default parent to null (implied at the start);
1501 1503 otherwise the default parent is always the last node created
1502 1504 - "<p" sets the default parent to the backref p
1503 1505 - "*p" is a fork at parent p, which is a backref
1504 1506 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1505 1507 - "/p2" is a merge of the preceding node and p2
1506 1508 - ":tag" defines a local tag for the preceding node
1507 1509 - "@branch" sets the named branch for subsequent nodes
1508 1510 - "#...\\n" is a comment up to the end of the line
1509 1511
1510 1512 Whitespace between the above elements is ignored.
1511 1513
1512 1514 A backref is either
1513 1515
1514 1516 - a number n, which references the node curr-n, where curr is the current
1515 1517 node, or
1516 1518 - the name of a local tag you placed earlier using ":tag", or
1517 1519 - empty to denote the default parent.
1518 1520
1519 1521 All string valued-elements are either strictly alphanumeric, or must
1520 1522 be enclosed in double quotes ("..."), with "\\" as escape character.
1521 1523 """
1522 1524
1523 1525 if text is None:
1524 1526 ui.status(_("reading DAG from stdin\n"))
1525 1527 text = ui.fin.read()
1526 1528
1527 1529 cl = repo.changelog
1528 1530 if len(cl) > 0:
1529 1531 raise util.Abort(_('repository is not empty'))
1530 1532
1531 1533 # determine number of revs in DAG
1532 1534 total = 0
1533 1535 for type, data in dagparser.parsedag(text):
1534 1536 if type == 'n':
1535 1537 total += 1
1536 1538
1537 1539 if mergeable_file:
1538 1540 linesperrev = 2
1539 1541 # make a file with k lines per rev
1540 1542 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1541 1543 initialmergedlines.append("")
1542 1544
1543 1545 tags = []
1544 1546
1545 1547 lock = tr = None
1546 1548 try:
1547 1549 lock = repo.lock()
1548 1550 tr = repo.transaction("builddag")
1549 1551
1550 1552 at = -1
1551 1553 atbranch = 'default'
1552 1554 nodeids = []
1553 1555 id = 0
1554 1556 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1555 1557 for type, data in dagparser.parsedag(text):
1556 1558 if type == 'n':
1557 1559 ui.note(('node %s\n' % str(data)))
1558 1560 id, ps = data
1559 1561
1560 1562 files = []
1561 1563 fctxs = {}
1562 1564
1563 1565 p2 = None
1564 1566 if mergeable_file:
1565 1567 fn = "mf"
1566 1568 p1 = repo[ps[0]]
1567 1569 if len(ps) > 1:
1568 1570 p2 = repo[ps[1]]
1569 1571 pa = p1.ancestor(p2)
1570 1572 base, local, other = [x[fn].data() for x in (pa, p1,
1571 1573 p2)]
1572 1574 m3 = simplemerge.Merge3Text(base, local, other)
1573 1575 ml = [l.strip() for l in m3.merge_lines()]
1574 1576 ml.append("")
1575 1577 elif at > 0:
1576 1578 ml = p1[fn].data().split("\n")
1577 1579 else:
1578 1580 ml = initialmergedlines
1579 1581 ml[id * linesperrev] += " r%i" % id
1580 1582 mergedtext = "\n".join(ml)
1581 1583 files.append(fn)
1582 1584 fctxs[fn] = context.memfilectx(fn, mergedtext)
1583 1585
1584 1586 if overwritten_file:
1585 1587 fn = "of"
1586 1588 files.append(fn)
1587 1589 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1588 1590
1589 1591 if new_file:
1590 1592 fn = "nf%i" % id
1591 1593 files.append(fn)
1592 1594 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1593 1595 if len(ps) > 1:
1594 1596 if not p2:
1595 1597 p2 = repo[ps[1]]
1596 1598 for fn in p2:
1597 1599 if fn.startswith("nf"):
1598 1600 files.append(fn)
1599 1601 fctxs[fn] = p2[fn]
1600 1602
1601 1603 def fctxfn(repo, cx, path):
1602 1604 return fctxs.get(path)
1603 1605
1604 1606 if len(ps) == 0 or ps[0] < 0:
1605 1607 pars = [None, None]
1606 1608 elif len(ps) == 1:
1607 1609 pars = [nodeids[ps[0]], None]
1608 1610 else:
1609 1611 pars = [nodeids[p] for p in ps]
1610 1612 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1611 1613 date=(id, 0),
1612 1614 user="debugbuilddag",
1613 1615 extra={'branch': atbranch})
1614 1616 nodeid = repo.commitctx(cx)
1615 1617 nodeids.append(nodeid)
1616 1618 at = id
1617 1619 elif type == 'l':
1618 1620 id, name = data
1619 1621 ui.note(('tag %s\n' % name))
1620 1622 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1621 1623 elif type == 'a':
1622 1624 ui.note(('branch %s\n' % data))
1623 1625 atbranch = data
1624 1626 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1625 1627 tr.close()
1626 1628
1627 1629 if tags:
1628 1630 repo.opener.write("localtags", "".join(tags))
1629 1631 finally:
1630 1632 ui.progress(_('building'), None)
1631 1633 release(tr, lock)
1632 1634
1633 1635 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1634 1636 def debugbundle(ui, bundlepath, all=None, **opts):
1635 1637 """lists the contents of a bundle"""
1636 1638 f = hg.openpath(ui, bundlepath)
1637 1639 try:
1638 1640 gen = changegroup.readbundle(f, bundlepath)
1639 1641 if all:
1640 1642 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1641 1643
1642 1644 def showchunks(named):
1643 1645 ui.write("\n%s\n" % named)
1644 1646 chain = None
1645 1647 while True:
1646 1648 chunkdata = gen.deltachunk(chain)
1647 1649 if not chunkdata:
1648 1650 break
1649 1651 node = chunkdata['node']
1650 1652 p1 = chunkdata['p1']
1651 1653 p2 = chunkdata['p2']
1652 1654 cs = chunkdata['cs']
1653 1655 deltabase = chunkdata['deltabase']
1654 1656 delta = chunkdata['delta']
1655 1657 ui.write("%s %s %s %s %s %s\n" %
1656 1658 (hex(node), hex(p1), hex(p2),
1657 1659 hex(cs), hex(deltabase), len(delta)))
1658 1660 chain = node
1659 1661
1660 1662 chunkdata = gen.changelogheader()
1661 1663 showchunks("changelog")
1662 1664 chunkdata = gen.manifestheader()
1663 1665 showchunks("manifest")
1664 1666 while True:
1665 1667 chunkdata = gen.filelogheader()
1666 1668 if not chunkdata:
1667 1669 break
1668 1670 fname = chunkdata['filename']
1669 1671 showchunks(fname)
1670 1672 else:
1671 1673 chunkdata = gen.changelogheader()
1672 1674 chain = None
1673 1675 while True:
1674 1676 chunkdata = gen.deltachunk(chain)
1675 1677 if not chunkdata:
1676 1678 break
1677 1679 node = chunkdata['node']
1678 1680 ui.write("%s\n" % hex(node))
1679 1681 chain = node
1680 1682 finally:
1681 1683 f.close()
1682 1684
1683 1685 @command('debugcheckstate', [], '')
1684 1686 def debugcheckstate(ui, repo):
1685 1687 """validate the correctness of the current dirstate"""
1686 1688 parent1, parent2 = repo.dirstate.parents()
1687 1689 m1 = repo[parent1].manifest()
1688 1690 m2 = repo[parent2].manifest()
1689 1691 errors = 0
1690 1692 for f in repo.dirstate:
1691 1693 state = repo.dirstate[f]
1692 1694 if state in "nr" and f not in m1:
1693 1695 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1694 1696 errors += 1
1695 1697 if state in "a" and f in m1:
1696 1698 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1697 1699 errors += 1
1698 1700 if state in "m" and f not in m1 and f not in m2:
1699 1701 ui.warn(_("%s in state %s, but not in either manifest\n") %
1700 1702 (f, state))
1701 1703 errors += 1
1702 1704 for f in m1:
1703 1705 state = repo.dirstate[f]
1704 1706 if state not in "nrm":
1705 1707 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1706 1708 errors += 1
1707 1709 if errors:
1708 1710 error = _(".hg/dirstate inconsistent with current parent's manifest")
1709 1711 raise util.Abort(error)
1710 1712
1711 1713 @command('debugcommands', [], _('[COMMAND]'))
1712 1714 def debugcommands(ui, cmd='', *args):
1713 1715 """list all available commands and options"""
1714 1716 for cmd, vals in sorted(table.iteritems()):
1715 1717 cmd = cmd.split('|')[0].strip('^')
1716 1718 opts = ', '.join([i[1] for i in vals[1]])
1717 1719 ui.write('%s: %s\n' % (cmd, opts))
1718 1720
1719 1721 @command('debugcomplete',
1720 1722 [('o', 'options', None, _('show the command options'))],
1721 1723 _('[-o] CMD'))
1722 1724 def debugcomplete(ui, cmd='', **opts):
1723 1725 """returns the completion list associated with the given command"""
1724 1726
1725 1727 if opts.get('options'):
1726 1728 options = []
1727 1729 otables = [globalopts]
1728 1730 if cmd:
1729 1731 aliases, entry = cmdutil.findcmd(cmd, table, False)
1730 1732 otables.append(entry[1])
1731 1733 for t in otables:
1732 1734 for o in t:
1733 1735 if "(DEPRECATED)" in o[3]:
1734 1736 continue
1735 1737 if o[0]:
1736 1738 options.append('-%s' % o[0])
1737 1739 options.append('--%s' % o[1])
1738 1740 ui.write("%s\n" % "\n".join(options))
1739 1741 return
1740 1742
1741 1743 cmdlist = cmdutil.findpossible(cmd, table)
1742 1744 if ui.verbose:
1743 1745 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1744 1746 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1745 1747
1746 1748 @command('debugdag',
1747 1749 [('t', 'tags', None, _('use tags as labels')),
1748 1750 ('b', 'branches', None, _('annotate with branch names')),
1749 1751 ('', 'dots', None, _('use dots for runs')),
1750 1752 ('s', 'spaces', None, _('separate elements by spaces'))],
1751 1753 _('[OPTION]... [FILE [REV]...]'))
1752 1754 def debugdag(ui, repo, file_=None, *revs, **opts):
1753 1755 """format the changelog or an index DAG as a concise textual description
1754 1756
1755 1757 If you pass a revlog index, the revlog's DAG is emitted. If you list
1756 1758 revision numbers, they get labeled in the output as rN.
1757 1759
1758 1760 Otherwise, the changelog DAG of the current repo is emitted.
1759 1761 """
1760 1762 spaces = opts.get('spaces')
1761 1763 dots = opts.get('dots')
1762 1764 if file_:
1763 1765 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1764 1766 revs = set((int(r) for r in revs))
1765 1767 def events():
1766 1768 for r in rlog:
1767 1769 yield 'n', (r, list(set(p for p in rlog.parentrevs(r)
1768 1770 if p != -1)))
1769 1771 if r in revs:
1770 1772 yield 'l', (r, "r%i" % r)
1771 1773 elif repo:
1772 1774 cl = repo.changelog
1773 1775 tags = opts.get('tags')
1774 1776 branches = opts.get('branches')
1775 1777 if tags:
1776 1778 labels = {}
1777 1779 for l, n in repo.tags().items():
1778 1780 labels.setdefault(cl.rev(n), []).append(l)
1779 1781 def events():
1780 1782 b = "default"
1781 1783 for r in cl:
1782 1784 if branches:
1783 1785 newb = cl.read(cl.node(r))[5]['branch']
1784 1786 if newb != b:
1785 1787 yield 'a', newb
1786 1788 b = newb
1787 1789 yield 'n', (r, list(set(p for p in cl.parentrevs(r)
1788 1790 if p != -1)))
1789 1791 if tags:
1790 1792 ls = labels.get(r)
1791 1793 if ls:
1792 1794 for l in ls:
1793 1795 yield 'l', (r, l)
1794 1796 else:
1795 1797 raise util.Abort(_('need repo for changelog dag'))
1796 1798
1797 1799 for line in dagparser.dagtextlines(events(),
1798 1800 addspaces=spaces,
1799 1801 wraplabels=True,
1800 1802 wrapannotations=True,
1801 1803 wrapnonlinear=dots,
1802 1804 usedots=dots,
1803 1805 maxlinewidth=70):
1804 1806 ui.write(line)
1805 1807 ui.write("\n")
1806 1808
1807 1809 @command('debugdata',
1808 1810 [('c', 'changelog', False, _('open changelog')),
1809 1811 ('m', 'manifest', False, _('open manifest'))],
1810 1812 _('-c|-m|FILE REV'))
1811 1813 def debugdata(ui, repo, file_, rev=None, **opts):
1812 1814 """dump the contents of a data file revision"""
1813 1815 if opts.get('changelog') or opts.get('manifest'):
1814 1816 file_, rev = None, file_
1815 1817 elif rev is None:
1816 1818 raise error.CommandError('debugdata', _('invalid arguments'))
1817 1819 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1818 1820 try:
1819 1821 ui.write(r.revision(r.lookup(rev)))
1820 1822 except KeyError:
1821 1823 raise util.Abort(_('invalid revision identifier %s') % rev)
1822 1824
1823 1825 @command('debugdate',
1824 1826 [('e', 'extended', None, _('try extended date formats'))],
1825 1827 _('[-e] DATE [RANGE]'))
1826 1828 def debugdate(ui, date, range=None, **opts):
1827 1829 """parse and display a date"""
1828 1830 if opts["extended"]:
1829 1831 d = util.parsedate(date, util.extendeddateformats)
1830 1832 else:
1831 1833 d = util.parsedate(date)
1832 1834 ui.write(("internal: %s %s\n") % d)
1833 1835 ui.write(("standard: %s\n") % util.datestr(d))
1834 1836 if range:
1835 1837 m = util.matchdate(range)
1836 1838 ui.write(("match: %s\n") % m(d[0]))
1837 1839
1838 1840 @command('debugdiscovery',
1839 1841 [('', 'old', None, _('use old-style discovery')),
1840 1842 ('', 'nonheads', None,
1841 1843 _('use old-style discovery with non-heads included')),
1842 1844 ] + remoteopts,
1843 1845 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1844 1846 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1845 1847 """runs the changeset discovery protocol in isolation"""
1846 1848 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
1847 1849 opts.get('branch'))
1848 1850 remote = hg.peer(repo, opts, remoteurl)
1849 1851 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1850 1852
1851 1853 # make sure tests are repeatable
1852 1854 random.seed(12323)
1853 1855
1854 1856 def doit(localheads, remoteheads, remote=remote):
1855 1857 if opts.get('old'):
1856 1858 if localheads:
1857 1859 raise util.Abort('cannot use localheads with old style '
1858 1860 'discovery')
1859 1861 if not util.safehasattr(remote, 'branches'):
1860 1862 # enable in-client legacy support
1861 1863 remote = localrepo.locallegacypeer(remote.local())
1862 1864 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1863 1865 force=True)
1864 1866 common = set(common)
1865 1867 if not opts.get('nonheads'):
1866 1868 ui.write(("unpruned common: %s\n") %
1867 1869 " ".join(sorted(short(n) for n in common)))
1868 1870 dag = dagutil.revlogdag(repo.changelog)
1869 1871 all = dag.ancestorset(dag.internalizeall(common))
1870 1872 common = dag.externalizeall(dag.headsetofconnecteds(all))
1871 1873 else:
1872 1874 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1873 1875 common = set(common)
1874 1876 rheads = set(hds)
1875 1877 lheads = set(repo.heads())
1876 1878 ui.write(("common heads: %s\n") %
1877 1879 " ".join(sorted(short(n) for n in common)))
1878 1880 if lheads <= common:
1879 1881 ui.write(("local is subset\n"))
1880 1882 elif rheads <= common:
1881 1883 ui.write(("remote is subset\n"))
1882 1884
1883 1885 serverlogs = opts.get('serverlog')
1884 1886 if serverlogs:
1885 1887 for filename in serverlogs:
1886 1888 logfile = open(filename, 'r')
1887 1889 try:
1888 1890 line = logfile.readline()
1889 1891 while line:
1890 1892 parts = line.strip().split(';')
1891 1893 op = parts[1]
1892 1894 if op == 'cg':
1893 1895 pass
1894 1896 elif op == 'cgss':
1895 1897 doit(parts[2].split(' '), parts[3].split(' '))
1896 1898 elif op == 'unb':
1897 1899 doit(parts[3].split(' '), parts[2].split(' '))
1898 1900 line = logfile.readline()
1899 1901 finally:
1900 1902 logfile.close()
1901 1903
1902 1904 else:
1903 1905 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1904 1906 opts.get('remote_head'))
1905 1907 localrevs = opts.get('local_head')
1906 1908 doit(localrevs, remoterevs)
1907 1909
1908 1910 @command('debugfileset',
1909 1911 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
1910 1912 _('[-r REV] FILESPEC'))
1911 1913 def debugfileset(ui, repo, expr, **opts):
1912 1914 '''parse and apply a fileset specification'''
1913 1915 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
1914 1916 if ui.verbose:
1915 1917 tree = fileset.parse(expr)[0]
1916 1918 ui.note(tree, "\n")
1917 1919
1918 1920 for f in fileset.getfileset(ctx, expr):
1919 1921 ui.write("%s\n" % f)
1920 1922
1921 1923 @command('debugfsinfo', [], _('[PATH]'))
1922 1924 def debugfsinfo(ui, path="."):
1923 1925 """show information detected about current filesystem"""
1924 1926 util.writefile('.debugfsinfo', '')
1925 1927 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
1926 1928 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
1927 1929 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
1928 1930 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
1929 1931 and 'yes' or 'no'))
1930 1932 os.unlink('.debugfsinfo')
1931 1933
1932 1934 @command('debuggetbundle',
1933 1935 [('H', 'head', [], _('id of head node'), _('ID')),
1934 1936 ('C', 'common', [], _('id of common node'), _('ID')),
1935 1937 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1936 1938 _('REPO FILE [-H|-C ID]...'))
1937 1939 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1938 1940 """retrieves a bundle from a repo
1939 1941
1940 1942 Every ID must be a full-length hex node id string. Saves the bundle to the
1941 1943 given file.
1942 1944 """
1943 1945 repo = hg.peer(ui, opts, repopath)
1944 1946 if not repo.capable('getbundle'):
1945 1947 raise util.Abort("getbundle() not supported by target repository")
1946 1948 args = {}
1947 1949 if common:
1948 1950 args['common'] = [bin(s) for s in common]
1949 1951 if head:
1950 1952 args['heads'] = [bin(s) for s in head]
1951 1953 # TODO: get desired bundlecaps from command line.
1952 1954 args['bundlecaps'] = None
1953 1955 bundle = repo.getbundle('debug', **args)
1954 1956
1955 1957 bundletype = opts.get('type', 'bzip2').lower()
1956 1958 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1957 1959 bundletype = btypes.get(bundletype)
1958 1960 if bundletype not in changegroup.bundletypes:
1959 1961 raise util.Abort(_('unknown bundle type specified with --type'))
1960 1962 changegroup.writebundle(bundle, bundlepath, bundletype)
1961 1963
1962 1964 @command('debugignore', [], '')
1963 1965 def debugignore(ui, repo, *values, **opts):
1964 1966 """display the combined ignore pattern"""
1965 1967 ignore = repo.dirstate._ignore
1966 1968 includepat = getattr(ignore, 'includepat', None)
1967 1969 if includepat is not None:
1968 1970 ui.write("%s\n" % includepat)
1969 1971 else:
1970 1972 raise util.Abort(_("no ignore patterns found"))
1971 1973
1972 1974 @command('debugindex',
1973 1975 [('c', 'changelog', False, _('open changelog')),
1974 1976 ('m', 'manifest', False, _('open manifest')),
1975 1977 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1976 1978 _('[-f FORMAT] -c|-m|FILE'))
1977 1979 def debugindex(ui, repo, file_=None, **opts):
1978 1980 """dump the contents of an index file"""
1979 1981 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1980 1982 format = opts.get('format', 0)
1981 1983 if format not in (0, 1):
1982 1984 raise util.Abort(_("unknown format %d") % format)
1983 1985
1984 1986 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1985 1987 if generaldelta:
1986 1988 basehdr = ' delta'
1987 1989 else:
1988 1990 basehdr = ' base'
1989 1991
1990 1992 if format == 0:
1991 1993 ui.write(" rev offset length " + basehdr + " linkrev"
1992 1994 " nodeid p1 p2\n")
1993 1995 elif format == 1:
1994 1996 ui.write(" rev flag offset length"
1995 1997 " size " + basehdr + " link p1 p2"
1996 1998 " nodeid\n")
1997 1999
1998 2000 for i in r:
1999 2001 node = r.node(i)
2000 2002 if generaldelta:
2001 2003 base = r.deltaparent(i)
2002 2004 else:
2003 2005 base = r.chainbase(i)
2004 2006 if format == 0:
2005 2007 try:
2006 2008 pp = r.parents(node)
2007 2009 except Exception:
2008 2010 pp = [nullid, nullid]
2009 2011 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2010 2012 i, r.start(i), r.length(i), base, r.linkrev(i),
2011 2013 short(node), short(pp[0]), short(pp[1])))
2012 2014 elif format == 1:
2013 2015 pr = r.parentrevs(i)
2014 2016 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2015 2017 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2016 2018 base, r.linkrev(i), pr[0], pr[1], short(node)))
2017 2019
2018 2020 @command('debugindexdot', [], _('FILE'))
2019 2021 def debugindexdot(ui, repo, file_):
2020 2022 """dump an index DAG as a graphviz dot file"""
2021 2023 r = None
2022 2024 if repo:
2023 2025 filelog = repo.file(file_)
2024 2026 if len(filelog):
2025 2027 r = filelog
2026 2028 if not r:
2027 2029 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2028 2030 ui.write(("digraph G {\n"))
2029 2031 for i in r:
2030 2032 node = r.node(i)
2031 2033 pp = r.parents(node)
2032 2034 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2033 2035 if pp[1] != nullid:
2034 2036 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2035 2037 ui.write("}\n")
2036 2038
2037 2039 @command('debuginstall', [], '')
2038 2040 def debuginstall(ui):
2039 2041 '''test Mercurial installation
2040 2042
2041 2043 Returns 0 on success.
2042 2044 '''
2043 2045
2044 2046 def writetemp(contents):
2045 2047 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2046 2048 f = os.fdopen(fd, "wb")
2047 2049 f.write(contents)
2048 2050 f.close()
2049 2051 return name
2050 2052
2051 2053 problems = 0
2052 2054
2053 2055 # encoding
2054 2056 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2055 2057 try:
2056 2058 encoding.fromlocal("test")
2057 2059 except util.Abort, inst:
2058 2060 ui.write(" %s\n" % inst)
2059 2061 ui.write(_(" (check that your locale is properly set)\n"))
2060 2062 problems += 1
2061 2063
2062 2064 # Python lib
2063 2065 ui.status(_("checking Python lib (%s)...\n")
2064 2066 % os.path.dirname(os.__file__))
2065 2067
2066 2068 # compiled modules
2067 2069 ui.status(_("checking installed modules (%s)...\n")
2068 2070 % os.path.dirname(__file__))
2069 2071 try:
2070 2072 import bdiff, mpatch, base85, osutil
2071 2073 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2072 2074 except Exception, inst:
2073 2075 ui.write(" %s\n" % inst)
2074 2076 ui.write(_(" One or more extensions could not be found"))
2075 2077 ui.write(_(" (check that you compiled the extensions)\n"))
2076 2078 problems += 1
2077 2079
2078 2080 # templates
2079 2081 import templater
2080 2082 p = templater.templatepath()
2081 2083 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2082 2084 try:
2083 2085 templater.templater(templater.templatepath("map-cmdline.default"))
2084 2086 except Exception, inst:
2085 2087 ui.write(" %s\n" % inst)
2086 2088 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2087 2089 problems += 1
2088 2090
2089 2091 # editor
2090 2092 ui.status(_("checking commit editor...\n"))
2091 2093 editor = ui.geteditor()
2092 2094 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
2093 2095 if not cmdpath:
2094 2096 if editor == 'vi':
2095 2097 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2096 2098 ui.write(_(" (specify a commit editor in your configuration"
2097 2099 " file)\n"))
2098 2100 else:
2099 2101 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2100 2102 ui.write(_(" (specify a commit editor in your configuration"
2101 2103 " file)\n"))
2102 2104 problems += 1
2103 2105
2104 2106 # check username
2105 2107 ui.status(_("checking username...\n"))
2106 2108 try:
2107 2109 ui.username()
2108 2110 except util.Abort, e:
2109 2111 ui.write(" %s\n" % e)
2110 2112 ui.write(_(" (specify a username in your configuration file)\n"))
2111 2113 problems += 1
2112 2114
2113 2115 if not problems:
2114 2116 ui.status(_("no problems detected\n"))
2115 2117 else:
2116 2118 ui.write(_("%s problems detected,"
2117 2119 " please check your install!\n") % problems)
2118 2120
2119 2121 return problems
2120 2122
2121 2123 @command('debugknown', [], _('REPO ID...'))
2122 2124 def debugknown(ui, repopath, *ids, **opts):
2123 2125 """test whether node ids are known to a repo
2124 2126
2125 2127 Every ID must be a full-length hex node id string. Returns a list of 0s
2126 2128 and 1s indicating unknown/known.
2127 2129 """
2128 2130 repo = hg.peer(ui, opts, repopath)
2129 2131 if not repo.capable('known'):
2130 2132 raise util.Abort("known() not supported by target repository")
2131 2133 flags = repo.known([bin(s) for s in ids])
2132 2134 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2133 2135
2134 2136 @command('debuglabelcomplete', [], _('LABEL...'))
2135 2137 def debuglabelcomplete(ui, repo, *args):
2136 2138 '''complete "labels" - tags, open branch names, bookmark names'''
2137 2139
2138 2140 labels = set()
2139 2141 labels.update(t[0] for t in repo.tagslist())
2140 2142 labels.update(repo._bookmarks.keys())
2141 2143 for heads in repo.branchmap().itervalues():
2142 2144 for h in heads:
2143 2145 ctx = repo[h]
2144 2146 if not ctx.closesbranch():
2145 2147 labels.add(ctx.branch())
2146 2148 completions = set()
2147 2149 if not args:
2148 2150 args = ['']
2149 2151 for a in args:
2150 2152 completions.update(l for l in labels if l.startswith(a))
2151 2153 ui.write('\n'.join(sorted(completions)))
2152 2154 ui.write('\n')
2153 2155
2154 2156 @command('debugobsolete',
2155 2157 [('', 'flags', 0, _('markers flag')),
2156 2158 ] + commitopts2,
2157 2159 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2158 2160 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2159 2161 """create arbitrary obsolete marker
2160 2162
2161 2163 With no arguments, displays the list of obsolescence markers."""
2162 2164 def parsenodeid(s):
2163 2165 try:
2164 2166 # We do not use revsingle/revrange functions here to accept
2165 2167 # arbitrary node identifiers, possibly not present in the
2166 2168 # local repository.
2167 2169 n = bin(s)
2168 2170 if len(n) != len(nullid):
2169 2171 raise TypeError()
2170 2172 return n
2171 2173 except TypeError:
2172 2174 raise util.Abort('changeset references must be full hexadecimal '
2173 2175 'node identifiers')
2174 2176
2175 2177 if precursor is not None:
2176 2178 metadata = {}
2177 2179 if 'date' in opts:
2178 2180 metadata['date'] = opts['date']
2179 2181 metadata['user'] = opts['user'] or ui.username()
2180 2182 succs = tuple(parsenodeid(succ) for succ in successors)
2181 2183 l = repo.lock()
2182 2184 try:
2183 2185 tr = repo.transaction('debugobsolete')
2184 2186 try:
2185 2187 repo.obsstore.create(tr, parsenodeid(precursor), succs,
2186 2188 opts['flags'], metadata)
2187 2189 tr.close()
2188 2190 finally:
2189 2191 tr.release()
2190 2192 finally:
2191 2193 l.release()
2192 2194 else:
2193 2195 for m in obsolete.allmarkers(repo):
2194 2196 ui.write(hex(m.precnode()))
2195 2197 for repl in m.succnodes():
2196 2198 ui.write(' ')
2197 2199 ui.write(hex(repl))
2198 2200 ui.write(' %X ' % m._data[2])
2199 2201 ui.write('{%s}' % (', '.join('%r: %r' % t for t in
2200 2202 sorted(m.metadata().items()))))
2201 2203 ui.write('\n')
2202 2204
2203 2205 @command('debugpathcomplete',
2204 2206 [('f', 'full', None, _('complete an entire path')),
2205 2207 ('n', 'normal', None, _('show only normal files')),
2206 2208 ('a', 'added', None, _('show only added files')),
2207 2209 ('r', 'removed', None, _('show only removed files'))],
2208 2210 _('FILESPEC...'))
2209 2211 def debugpathcomplete(ui, repo, *specs, **opts):
2210 2212 '''complete part or all of a tracked path
2211 2213
2212 2214 This command supports shells that offer path name completion. It
2213 2215 currently completes only files already known to the dirstate.
2214 2216
2215 2217 Completion extends only to the next path segment unless
2216 2218 --full is specified, in which case entire paths are used.'''
2217 2219
2218 2220 def complete(path, acceptable):
2219 2221 dirstate = repo.dirstate
2220 2222 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2221 2223 rootdir = repo.root + os.sep
2222 2224 if spec != repo.root and not spec.startswith(rootdir):
2223 2225 return [], []
2224 2226 if os.path.isdir(spec):
2225 2227 spec += '/'
2226 2228 spec = spec[len(rootdir):]
2227 2229 fixpaths = os.sep != '/'
2228 2230 if fixpaths:
2229 2231 spec = spec.replace(os.sep, '/')
2230 2232 speclen = len(spec)
2231 2233 fullpaths = opts['full']
2232 2234 files, dirs = set(), set()
2233 2235 adddir, addfile = dirs.add, files.add
2234 2236 for f, st in dirstate.iteritems():
2235 2237 if f.startswith(spec) and st[0] in acceptable:
2236 2238 if fixpaths:
2237 2239 f = f.replace('/', os.sep)
2238 2240 if fullpaths:
2239 2241 addfile(f)
2240 2242 continue
2241 2243 s = f.find(os.sep, speclen)
2242 2244 if s >= 0:
2243 2245 adddir(f[:s + 1])
2244 2246 else:
2245 2247 addfile(f)
2246 2248 return files, dirs
2247 2249
2248 2250 acceptable = ''
2249 2251 if opts['normal']:
2250 2252 acceptable += 'nm'
2251 2253 if opts['added']:
2252 2254 acceptable += 'a'
2253 2255 if opts['removed']:
2254 2256 acceptable += 'r'
2255 2257 cwd = repo.getcwd()
2256 2258 if not specs:
2257 2259 specs = ['.']
2258 2260
2259 2261 files, dirs = set(), set()
2260 2262 for spec in specs:
2261 2263 f, d = complete(spec, acceptable or 'nmar')
2262 2264 files.update(f)
2263 2265 dirs.update(d)
2264 2266 if not files and len(dirs) == 1:
2265 2267 # force the shell to consider a completion that matches one
2266 2268 # directory and zero files to be ambiguous
2267 2269 dirs.add(iter(dirs).next() + '.')
2268 2270 files.update(dirs)
2269 2271 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2270 2272 ui.write('\n')
2271 2273
2272 2274 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
2273 2275 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2274 2276 '''access the pushkey key/value protocol
2275 2277
2276 2278 With two args, list the keys in the given namespace.
2277 2279
2278 2280 With five args, set a key to new if it currently is set to old.
2279 2281 Reports success or failure.
2280 2282 '''
2281 2283
2282 2284 target = hg.peer(ui, {}, repopath)
2283 2285 if keyinfo:
2284 2286 key, old, new = keyinfo
2285 2287 r = target.pushkey(namespace, key, old, new)
2286 2288 ui.status(str(r) + '\n')
2287 2289 return not r
2288 2290 else:
2289 2291 for k, v in sorted(target.listkeys(namespace).iteritems()):
2290 2292 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2291 2293 v.encode('string-escape')))
2292 2294
2293 2295 @command('debugpvec', [], _('A B'))
2294 2296 def debugpvec(ui, repo, a, b=None):
2295 2297 ca = scmutil.revsingle(repo, a)
2296 2298 cb = scmutil.revsingle(repo, b)
2297 2299 pa = pvec.ctxpvec(ca)
2298 2300 pb = pvec.ctxpvec(cb)
2299 2301 if pa == pb:
2300 2302 rel = "="
2301 2303 elif pa > pb:
2302 2304 rel = ">"
2303 2305 elif pa < pb:
2304 2306 rel = "<"
2305 2307 elif pa | pb:
2306 2308 rel = "|"
2307 2309 ui.write(_("a: %s\n") % pa)
2308 2310 ui.write(_("b: %s\n") % pb)
2309 2311 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2310 2312 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2311 2313 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2312 2314 pa.distance(pb), rel))
2313 2315
2314 2316 @command('debugrebuilddirstate|debugrebuildstate',
2315 2317 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2316 2318 _('[-r REV]'))
2317 2319 def debugrebuilddirstate(ui, repo, rev):
2318 2320 """rebuild the dirstate as it would look like for the given revision
2319 2321
2320 2322 If no revision is specified the first current parent will be used.
2321 2323
2322 2324 The dirstate will be set to the files of the given revision.
2323 2325 The actual working directory content or existing dirstate
2324 2326 information such as adds or removes is not considered.
2325 2327
2326 2328 One use of this command is to make the next :hg:`status` invocation
2327 2329 check the actual file content.
2328 2330 """
2329 2331 ctx = scmutil.revsingle(repo, rev)
2330 2332 wlock = repo.wlock()
2331 2333 try:
2332 2334 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2333 2335 finally:
2334 2336 wlock.release()
2335 2337
2336 2338 @command('debugrename',
2337 2339 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2338 2340 _('[-r REV] FILE'))
2339 2341 def debugrename(ui, repo, file1, *pats, **opts):
2340 2342 """dump rename information"""
2341 2343
2342 2344 ctx = scmutil.revsingle(repo, opts.get('rev'))
2343 2345 m = scmutil.match(ctx, (file1,) + pats, opts)
2344 2346 for abs in ctx.walk(m):
2345 2347 fctx = ctx[abs]
2346 2348 o = fctx.filelog().renamed(fctx.filenode())
2347 2349 rel = m.rel(abs)
2348 2350 if o:
2349 2351 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2350 2352 else:
2351 2353 ui.write(_("%s not renamed\n") % rel)
2352 2354
2353 2355 @command('debugrevlog',
2354 2356 [('c', 'changelog', False, _('open changelog')),
2355 2357 ('m', 'manifest', False, _('open manifest')),
2356 2358 ('d', 'dump', False, _('dump index data'))],
2357 2359 _('-c|-m|FILE'))
2358 2360 def debugrevlog(ui, repo, file_=None, **opts):
2359 2361 """show data and statistics about a revlog"""
2360 2362 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2361 2363
2362 2364 if opts.get("dump"):
2363 2365 numrevs = len(r)
2364 2366 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2365 2367 " rawsize totalsize compression heads\n")
2366 2368 ts = 0
2367 2369 heads = set()
2368 2370 for rev in xrange(numrevs):
2369 2371 dbase = r.deltaparent(rev)
2370 2372 if dbase == -1:
2371 2373 dbase = rev
2372 2374 cbase = r.chainbase(rev)
2373 2375 p1, p2 = r.parentrevs(rev)
2374 2376 rs = r.rawsize(rev)
2375 2377 ts = ts + rs
2376 2378 heads -= set(r.parentrevs(rev))
2377 2379 heads.add(rev)
2378 2380 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2379 2381 (rev, p1, p2, r.start(rev), r.end(rev),
2380 2382 r.start(dbase), r.start(cbase),
2381 2383 r.start(p1), r.start(p2),
2382 2384 rs, ts, ts / r.end(rev), len(heads)))
2383 2385 return 0
2384 2386
2385 2387 v = r.version
2386 2388 format = v & 0xFFFF
2387 2389 flags = []
2388 2390 gdelta = False
2389 2391 if v & revlog.REVLOGNGINLINEDATA:
2390 2392 flags.append('inline')
2391 2393 if v & revlog.REVLOGGENERALDELTA:
2392 2394 gdelta = True
2393 2395 flags.append('generaldelta')
2394 2396 if not flags:
2395 2397 flags = ['(none)']
2396 2398
2397 2399 nummerges = 0
2398 2400 numfull = 0
2399 2401 numprev = 0
2400 2402 nump1 = 0
2401 2403 nump2 = 0
2402 2404 numother = 0
2403 2405 nump1prev = 0
2404 2406 nump2prev = 0
2405 2407 chainlengths = []
2406 2408
2407 2409 datasize = [None, 0, 0L]
2408 2410 fullsize = [None, 0, 0L]
2409 2411 deltasize = [None, 0, 0L]
2410 2412
2411 2413 def addsize(size, l):
2412 2414 if l[0] is None or size < l[0]:
2413 2415 l[0] = size
2414 2416 if size > l[1]:
2415 2417 l[1] = size
2416 2418 l[2] += size
2417 2419
2418 2420 numrevs = len(r)
2419 2421 for rev in xrange(numrevs):
2420 2422 p1, p2 = r.parentrevs(rev)
2421 2423 delta = r.deltaparent(rev)
2422 2424 if format > 0:
2423 2425 addsize(r.rawsize(rev), datasize)
2424 2426 if p2 != nullrev:
2425 2427 nummerges += 1
2426 2428 size = r.length(rev)
2427 2429 if delta == nullrev:
2428 2430 chainlengths.append(0)
2429 2431 numfull += 1
2430 2432 addsize(size, fullsize)
2431 2433 else:
2432 2434 chainlengths.append(chainlengths[delta] + 1)
2433 2435 addsize(size, deltasize)
2434 2436 if delta == rev - 1:
2435 2437 numprev += 1
2436 2438 if delta == p1:
2437 2439 nump1prev += 1
2438 2440 elif delta == p2:
2439 2441 nump2prev += 1
2440 2442 elif delta == p1:
2441 2443 nump1 += 1
2442 2444 elif delta == p2:
2443 2445 nump2 += 1
2444 2446 elif delta != nullrev:
2445 2447 numother += 1
2446 2448
2447 2449 # Adjust size min value for empty cases
2448 2450 for size in (datasize, fullsize, deltasize):
2449 2451 if size[0] is None:
2450 2452 size[0] = 0
2451 2453
2452 2454 numdeltas = numrevs - numfull
2453 2455 numoprev = numprev - nump1prev - nump2prev
2454 2456 totalrawsize = datasize[2]
2455 2457 datasize[2] /= numrevs
2456 2458 fulltotal = fullsize[2]
2457 2459 fullsize[2] /= numfull
2458 2460 deltatotal = deltasize[2]
2459 2461 if numrevs - numfull > 0:
2460 2462 deltasize[2] /= numrevs - numfull
2461 2463 totalsize = fulltotal + deltatotal
2462 2464 avgchainlen = sum(chainlengths) / numrevs
2463 2465 compratio = totalrawsize / totalsize
2464 2466
2465 2467 basedfmtstr = '%%%dd\n'
2466 2468 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2467 2469
2468 2470 def dfmtstr(max):
2469 2471 return basedfmtstr % len(str(max))
2470 2472 def pcfmtstr(max, padding=0):
2471 2473 return basepcfmtstr % (len(str(max)), ' ' * padding)
2472 2474
2473 2475 def pcfmt(value, total):
2474 2476 return (value, 100 * float(value) / total)
2475 2477
2476 2478 ui.write(('format : %d\n') % format)
2477 2479 ui.write(('flags : %s\n') % ', '.join(flags))
2478 2480
2479 2481 ui.write('\n')
2480 2482 fmt = pcfmtstr(totalsize)
2481 2483 fmt2 = dfmtstr(totalsize)
2482 2484 ui.write(('revisions : ') + fmt2 % numrevs)
2483 2485 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2484 2486 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2485 2487 ui.write(('revisions : ') + fmt2 % numrevs)
2486 2488 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2487 2489 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2488 2490 ui.write(('revision size : ') + fmt2 % totalsize)
2489 2491 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2490 2492 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2491 2493
2492 2494 ui.write('\n')
2493 2495 fmt = dfmtstr(max(avgchainlen, compratio))
2494 2496 ui.write(('avg chain length : ') + fmt % avgchainlen)
2495 2497 ui.write(('compression ratio : ') + fmt % compratio)
2496 2498
2497 2499 if format > 0:
2498 2500 ui.write('\n')
2499 2501 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2500 2502 % tuple(datasize))
2501 2503 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2502 2504 % tuple(fullsize))
2503 2505 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2504 2506 % tuple(deltasize))
2505 2507
2506 2508 if numdeltas > 0:
2507 2509 ui.write('\n')
2508 2510 fmt = pcfmtstr(numdeltas)
2509 2511 fmt2 = pcfmtstr(numdeltas, 4)
2510 2512 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2511 2513 if numprev > 0:
2512 2514 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2513 2515 numprev))
2514 2516 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2515 2517 numprev))
2516 2518 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2517 2519 numprev))
2518 2520 if gdelta:
2519 2521 ui.write(('deltas against p1 : ')
2520 2522 + fmt % pcfmt(nump1, numdeltas))
2521 2523 ui.write(('deltas against p2 : ')
2522 2524 + fmt % pcfmt(nump2, numdeltas))
2523 2525 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2524 2526 numdeltas))
2525 2527
2526 2528 @command('debugrevspec', [], ('REVSPEC'))
2527 2529 def debugrevspec(ui, repo, expr):
2528 2530 """parse and apply a revision specification
2529 2531
2530 2532 Use --verbose to print the parsed tree before and after aliases
2531 2533 expansion.
2532 2534 """
2533 2535 if ui.verbose:
2534 2536 tree = revset.parse(expr)[0]
2535 2537 ui.note(revset.prettyformat(tree), "\n")
2536 2538 newtree = revset.findaliases(ui, tree)
2537 2539 if newtree != tree:
2538 2540 ui.note(revset.prettyformat(newtree), "\n")
2539 2541 func = revset.match(ui, expr)
2540 2542 for c in func(repo, range(len(repo))):
2541 2543 ui.write("%s\n" % c)
2542 2544
2543 2545 @command('debugsetparents', [], _('REV1 [REV2]'))
2544 2546 def debugsetparents(ui, repo, rev1, rev2=None):
2545 2547 """manually set the parents of the current working directory
2546 2548
2547 2549 This is useful for writing repository conversion tools, but should
2548 2550 be used with care.
2549 2551
2550 2552 Returns 0 on success.
2551 2553 """
2552 2554
2553 2555 r1 = scmutil.revsingle(repo, rev1).node()
2554 2556 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2555 2557
2556 2558 wlock = repo.wlock()
2557 2559 try:
2558 2560 repo.setparents(r1, r2)
2559 2561 finally:
2560 2562 wlock.release()
2561 2563
2562 2564 @command('debugdirstate|debugstate',
2563 2565 [('', 'nodates', None, _('do not display the saved mtime')),
2564 2566 ('', 'datesort', None, _('sort by saved mtime'))],
2565 2567 _('[OPTION]...'))
2566 2568 def debugstate(ui, repo, nodates=None, datesort=None):
2567 2569 """show the contents of the current dirstate"""
2568 2570 timestr = ""
2569 2571 showdate = not nodates
2570 2572 if datesort:
2571 2573 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2572 2574 else:
2573 2575 keyfunc = None # sort by filename
2574 2576 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2575 2577 if showdate:
2576 2578 if ent[3] == -1:
2577 2579 # Pad or slice to locale representation
2578 2580 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2579 2581 time.localtime(0)))
2580 2582 timestr = 'unset'
2581 2583 timestr = (timestr[:locale_len] +
2582 2584 ' ' * (locale_len - len(timestr)))
2583 2585 else:
2584 2586 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2585 2587 time.localtime(ent[3]))
2586 2588 if ent[1] & 020000:
2587 2589 mode = 'lnk'
2588 2590 else:
2589 2591 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2590 2592 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2591 2593 for f in repo.dirstate.copies():
2592 2594 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2593 2595
2594 2596 @command('debugsub',
2595 2597 [('r', 'rev', '',
2596 2598 _('revision to check'), _('REV'))],
2597 2599 _('[-r REV] [REV]'))
2598 2600 def debugsub(ui, repo, rev=None):
2599 2601 ctx = scmutil.revsingle(repo, rev, None)
2600 2602 for k, v in sorted(ctx.substate.items()):
2601 2603 ui.write(('path %s\n') % k)
2602 2604 ui.write((' source %s\n') % v[0])
2603 2605 ui.write((' revision %s\n') % v[1])
2604 2606
2605 2607 @command('debugsuccessorssets',
2606 2608 [],
2607 2609 _('[REV]'))
2608 2610 def debugsuccessorssets(ui, repo, *revs):
2609 2611 """show set of successors for revision
2610 2612
2611 2613 A successors set of changeset A is a consistent group of revisions that
2612 2614 succeed A. It contains non-obsolete changesets only.
2613 2615
2614 2616 In most cases a changeset A has a single successors set containing a single
2615 2617 successor (changeset A replaced by A').
2616 2618
2617 2619 A changeset that is made obsolete with no successors are called "pruned".
2618 2620 Such changesets have no successors sets at all.
2619 2621
2620 2622 A changeset that has been "split" will have a successors set containing
2621 2623 more than one successor.
2622 2624
2623 2625 A changeset that has been rewritten in multiple different ways is called
2624 2626 "divergent". Such changesets have multiple successor sets (each of which
2625 2627 may also be split, i.e. have multiple successors).
2626 2628
2627 2629 Results are displayed as follows::
2628 2630
2629 2631 <rev1>
2630 2632 <successors-1A>
2631 2633 <rev2>
2632 2634 <successors-2A>
2633 2635 <successors-2B1> <successors-2B2> <successors-2B3>
2634 2636
2635 2637 Here rev2 has two possible (i.e. divergent) successors sets. The first
2636 2638 holds one element, whereas the second holds three (i.e. the changeset has
2637 2639 been split).
2638 2640 """
2639 2641 # passed to successorssets caching computation from one call to another
2640 2642 cache = {}
2641 2643 ctx2str = str
2642 2644 node2str = short
2643 2645 if ui.debug():
2644 2646 def ctx2str(ctx):
2645 2647 return ctx.hex()
2646 2648 node2str = hex
2647 2649 for rev in scmutil.revrange(repo, revs):
2648 2650 ctx = repo[rev]
2649 2651 ui.write('%s\n'% ctx2str(ctx))
2650 2652 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
2651 2653 if succsset:
2652 2654 ui.write(' ')
2653 2655 ui.write(node2str(succsset[0]))
2654 2656 for node in succsset[1:]:
2655 2657 ui.write(' ')
2656 2658 ui.write(node2str(node))
2657 2659 ui.write('\n')
2658 2660
2659 2661 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2660 2662 def debugwalk(ui, repo, *pats, **opts):
2661 2663 """show how files match on given patterns"""
2662 2664 m = scmutil.match(repo[None], pats, opts)
2663 2665 items = list(repo.walk(m))
2664 2666 if not items:
2665 2667 return
2666 2668 f = lambda fn: fn
2667 2669 if ui.configbool('ui', 'slash') and os.sep != '/':
2668 2670 f = lambda fn: util.normpath(fn)
2669 2671 fmt = 'f %%-%ds %%-%ds %%s' % (
2670 2672 max([len(abs) for abs in items]),
2671 2673 max([len(m.rel(abs)) for abs in items]))
2672 2674 for abs in items:
2673 2675 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2674 2676 ui.write("%s\n" % line.rstrip())
2675 2677
2676 2678 @command('debugwireargs',
2677 2679 [('', 'three', '', 'three'),
2678 2680 ('', 'four', '', 'four'),
2679 2681 ('', 'five', '', 'five'),
2680 2682 ] + remoteopts,
2681 2683 _('REPO [OPTIONS]... [ONE [TWO]]'))
2682 2684 def debugwireargs(ui, repopath, *vals, **opts):
2683 2685 repo = hg.peer(ui, opts, repopath)
2684 2686 for opt in remoteopts:
2685 2687 del opts[opt[1]]
2686 2688 args = {}
2687 2689 for k, v in opts.iteritems():
2688 2690 if v:
2689 2691 args[k] = v
2690 2692 # run twice to check that we don't mess up the stream for the next command
2691 2693 res1 = repo.debugwireargs(*vals, **args)
2692 2694 res2 = repo.debugwireargs(*vals, **args)
2693 2695 ui.write("%s\n" % res1)
2694 2696 if res1 != res2:
2695 2697 ui.warn("%s\n" % res2)
2696 2698
2697 2699 @command('^diff',
2698 2700 [('r', 'rev', [], _('revision'), _('REV')),
2699 2701 ('c', 'change', '', _('change made by revision'), _('REV'))
2700 2702 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2701 2703 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2702 2704 def diff(ui, repo, *pats, **opts):
2703 2705 """diff repository (or selected files)
2704 2706
2705 2707 Show differences between revisions for the specified files.
2706 2708
2707 2709 Differences between files are shown using the unified diff format.
2708 2710
2709 2711 .. note::
2712
2710 2713 diff may generate unexpected results for merges, as it will
2711 2714 default to comparing against the working directory's first
2712 2715 parent changeset if no revisions are specified.
2713 2716
2714 2717 When two revision arguments are given, then changes are shown
2715 2718 between those revisions. If only one revision is specified then
2716 2719 that revision is compared to the working directory, and, when no
2717 2720 revisions are specified, the working directory files are compared
2718 2721 to its parent.
2719 2722
2720 2723 Alternatively you can specify -c/--change with a revision to see
2721 2724 the changes in that changeset relative to its first parent.
2722 2725
2723 2726 Without the -a/--text option, diff will avoid generating diffs of
2724 2727 files it detects as binary. With -a, diff will generate a diff
2725 2728 anyway, probably with undesirable results.
2726 2729
2727 2730 Use the -g/--git option to generate diffs in the git extended diff
2728 2731 format. For more information, read :hg:`help diffs`.
2729 2732
2730 2733 .. container:: verbose
2731 2734
2732 2735 Examples:
2733 2736
2734 2737 - compare a file in the current working directory to its parent::
2735 2738
2736 2739 hg diff foo.c
2737 2740
2738 2741 - compare two historical versions of a directory, with rename info::
2739 2742
2740 2743 hg diff --git -r 1.0:1.2 lib/
2741 2744
2742 2745 - get change stats relative to the last change on some date::
2743 2746
2744 2747 hg diff --stat -r "date('may 2')"
2745 2748
2746 2749 - diff all newly-added files that contain a keyword::
2747 2750
2748 2751 hg diff "set:added() and grep(GNU)"
2749 2752
2750 2753 - compare a revision and its parents::
2751 2754
2752 2755 hg diff -c 9353 # compare against first parent
2753 2756 hg diff -r 9353^:9353 # same using revset syntax
2754 2757 hg diff -r 9353^2:9353 # compare against the second parent
2755 2758
2756 2759 Returns 0 on success.
2757 2760 """
2758 2761
2759 2762 revs = opts.get('rev')
2760 2763 change = opts.get('change')
2761 2764 stat = opts.get('stat')
2762 2765 reverse = opts.get('reverse')
2763 2766
2764 2767 if revs and change:
2765 2768 msg = _('cannot specify --rev and --change at the same time')
2766 2769 raise util.Abort(msg)
2767 2770 elif change:
2768 2771 node2 = scmutil.revsingle(repo, change, None).node()
2769 2772 node1 = repo[node2].p1().node()
2770 2773 else:
2771 2774 node1, node2 = scmutil.revpair(repo, revs)
2772 2775
2773 2776 if reverse:
2774 2777 node1, node2 = node2, node1
2775 2778
2776 2779 diffopts = patch.diffopts(ui, opts)
2777 2780 m = scmutil.match(repo[node2], pats, opts)
2778 2781 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2779 2782 listsubrepos=opts.get('subrepos'))
2780 2783
2781 2784 @command('^export',
2782 2785 [('o', 'output', '',
2783 2786 _('print output to file with formatted name'), _('FORMAT')),
2784 2787 ('', 'switch-parent', None, _('diff against the second parent')),
2785 2788 ('r', 'rev', [], _('revisions to export'), _('REV')),
2786 2789 ] + diffopts,
2787 2790 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
2788 2791 def export(ui, repo, *changesets, **opts):
2789 2792 """dump the header and diffs for one or more changesets
2790 2793
2791 2794 Print the changeset header and diffs for one or more revisions.
2792 2795 If no revision is given, the parent of the working directory is used.
2793 2796
2794 2797 The information shown in the changeset header is: author, date,
2795 2798 branch name (if non-default), changeset hash, parent(s) and commit
2796 2799 comment.
2797 2800
2798 2801 .. note::
2802
2799 2803 export may generate unexpected diff output for merge
2800 2804 changesets, as it will compare the merge changeset against its
2801 2805 first parent only.
2802 2806
2803 2807 Output may be to a file, in which case the name of the file is
2804 2808 given using a format string. The formatting rules are as follows:
2805 2809
2806 2810 :``%%``: literal "%" character
2807 2811 :``%H``: changeset hash (40 hexadecimal digits)
2808 2812 :``%N``: number of patches being generated
2809 2813 :``%R``: changeset revision number
2810 2814 :``%b``: basename of the exporting repository
2811 2815 :``%h``: short-form changeset hash (12 hexadecimal digits)
2812 2816 :``%m``: first line of the commit message (only alphanumeric characters)
2813 2817 :``%n``: zero-padded sequence number, starting at 1
2814 2818 :``%r``: zero-padded changeset revision number
2815 2819
2816 2820 Without the -a/--text option, export will avoid generating diffs
2817 2821 of files it detects as binary. With -a, export will generate a
2818 2822 diff anyway, probably with undesirable results.
2819 2823
2820 2824 Use the -g/--git option to generate diffs in the git extended diff
2821 2825 format. See :hg:`help diffs` for more information.
2822 2826
2823 2827 With the --switch-parent option, the diff will be against the
2824 2828 second parent. It can be useful to review a merge.
2825 2829
2826 2830 .. container:: verbose
2827 2831
2828 2832 Examples:
2829 2833
2830 2834 - use export and import to transplant a bugfix to the current
2831 2835 branch::
2832 2836
2833 2837 hg export -r 9353 | hg import -
2834 2838
2835 2839 - export all the changesets between two revisions to a file with
2836 2840 rename information::
2837 2841
2838 2842 hg export --git -r 123:150 > changes.txt
2839 2843
2840 2844 - split outgoing changes into a series of patches with
2841 2845 descriptive names::
2842 2846
2843 2847 hg export -r "outgoing()" -o "%n-%m.patch"
2844 2848
2845 2849 Returns 0 on success.
2846 2850 """
2847 2851 changesets += tuple(opts.get('rev', []))
2848 2852 if not changesets:
2849 2853 changesets = ['.']
2850 2854 revs = scmutil.revrange(repo, changesets)
2851 2855 if not revs:
2852 2856 raise util.Abort(_("export requires at least one changeset"))
2853 2857 if len(revs) > 1:
2854 2858 ui.note(_('exporting patches:\n'))
2855 2859 else:
2856 2860 ui.note(_('exporting patch:\n'))
2857 2861 cmdutil.export(repo, revs, template=opts.get('output'),
2858 2862 switch_parent=opts.get('switch_parent'),
2859 2863 opts=patch.diffopts(ui, opts))
2860 2864
2861 2865 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2862 2866 def forget(ui, repo, *pats, **opts):
2863 2867 """forget the specified files on the next commit
2864 2868
2865 2869 Mark the specified files so they will no longer be tracked
2866 2870 after the next commit.
2867 2871
2868 2872 This only removes files from the current branch, not from the
2869 2873 entire project history, and it does not delete them from the
2870 2874 working directory.
2871 2875
2872 2876 To undo a forget before the next commit, see :hg:`add`.
2873 2877
2874 2878 .. container:: verbose
2875 2879
2876 2880 Examples:
2877 2881
2878 2882 - forget newly-added binary files::
2879 2883
2880 2884 hg forget "set:added() and binary()"
2881 2885
2882 2886 - forget files that would be excluded by .hgignore::
2883 2887
2884 2888 hg forget "set:hgignore()"
2885 2889
2886 2890 Returns 0 on success.
2887 2891 """
2888 2892
2889 2893 if not pats:
2890 2894 raise util.Abort(_('no files specified'))
2891 2895
2892 2896 m = scmutil.match(repo[None], pats, opts)
2893 2897 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2894 2898 return rejected and 1 or 0
2895 2899
2896 2900 @command(
2897 2901 'graft',
2898 2902 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2899 2903 ('c', 'continue', False, _('resume interrupted graft')),
2900 2904 ('e', 'edit', False, _('invoke editor on commit messages')),
2901 2905 ('', 'log', None, _('append graft info to log message')),
2902 2906 ('D', 'currentdate', False,
2903 2907 _('record the current date as commit date')),
2904 2908 ('U', 'currentuser', False,
2905 2909 _('record the current user as committer'), _('DATE'))]
2906 2910 + commitopts2 + mergetoolopts + dryrunopts,
2907 2911 _('[OPTION]... [-r] REV...'))
2908 2912 def graft(ui, repo, *revs, **opts):
2909 2913 '''copy changes from other branches onto the current branch
2910 2914
2911 2915 This command uses Mercurial's merge logic to copy individual
2912 2916 changes from other branches without merging branches in the
2913 2917 history graph. This is sometimes known as 'backporting' or
2914 2918 'cherry-picking'. By default, graft will copy user, date, and
2915 2919 description from the source changesets.
2916 2920
2917 2921 Changesets that are ancestors of the current revision, that have
2918 2922 already been grafted, or that are merges will be skipped.
2919 2923
2920 2924 If --log is specified, log messages will have a comment appended
2921 2925 of the form::
2922 2926
2923 2927 (grafted from CHANGESETHASH)
2924 2928
2925 2929 If a graft merge results in conflicts, the graft process is
2926 2930 interrupted so that the current merge can be manually resolved.
2927 2931 Once all conflicts are addressed, the graft process can be
2928 2932 continued with the -c/--continue option.
2929 2933
2930 2934 .. note::
2935
2931 2936 The -c/--continue option does not reapply earlier options.
2932 2937
2933 2938 .. container:: verbose
2934 2939
2935 2940 Examples:
2936 2941
2937 2942 - copy a single change to the stable branch and edit its description::
2938 2943
2939 2944 hg update stable
2940 2945 hg graft --edit 9393
2941 2946
2942 2947 - graft a range of changesets with one exception, updating dates::
2943 2948
2944 2949 hg graft -D "2085::2093 and not 2091"
2945 2950
2946 2951 - continue a graft after resolving conflicts::
2947 2952
2948 2953 hg graft -c
2949 2954
2950 2955 - show the source of a grafted changeset::
2951 2956
2952 2957 hg log --debug -r .
2953 2958
2954 2959 Returns 0 on successful completion.
2955 2960 '''
2956 2961
2957 2962 revs = list(revs)
2958 2963 revs.extend(opts['rev'])
2959 2964
2960 2965 if not opts.get('user') and opts.get('currentuser'):
2961 2966 opts['user'] = ui.username()
2962 2967 if not opts.get('date') and opts.get('currentdate'):
2963 2968 opts['date'] = "%d %d" % util.makedate()
2964 2969
2965 2970 editor = None
2966 2971 if opts.get('edit'):
2967 2972 editor = cmdutil.commitforceeditor
2968 2973
2969 2974 cont = False
2970 2975 if opts['continue']:
2971 2976 cont = True
2972 2977 if revs:
2973 2978 raise util.Abort(_("can't specify --continue and revisions"))
2974 2979 # read in unfinished revisions
2975 2980 try:
2976 2981 nodes = repo.opener.read('graftstate').splitlines()
2977 2982 revs = [repo[node].rev() for node in nodes]
2978 2983 except IOError, inst:
2979 2984 if inst.errno != errno.ENOENT:
2980 2985 raise
2981 2986 raise util.Abort(_("no graft state found, can't continue"))
2982 2987 else:
2983 2988 cmdutil.checkunfinished(repo)
2984 2989 cmdutil.bailifchanged(repo)
2985 2990 if not revs:
2986 2991 raise util.Abort(_('no revisions specified'))
2987 2992 revs = scmutil.revrange(repo, revs)
2988 2993
2989 2994 # check for merges
2990 2995 for rev in repo.revs('%ld and merge()', revs):
2991 2996 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2992 2997 revs.remove(rev)
2993 2998 if not revs:
2994 2999 return -1
2995 3000
2996 3001 # check for ancestors of dest branch
2997 3002 crev = repo['.'].rev()
2998 3003 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2999 3004 # don't mutate while iterating, create a copy
3000 3005 for rev in list(revs):
3001 3006 if rev in ancestors:
3002 3007 ui.warn(_('skipping ancestor revision %s\n') % rev)
3003 3008 revs.remove(rev)
3004 3009 if not revs:
3005 3010 return -1
3006 3011
3007 3012 # analyze revs for earlier grafts
3008 3013 ids = {}
3009 3014 for ctx in repo.set("%ld", revs):
3010 3015 ids[ctx.hex()] = ctx.rev()
3011 3016 n = ctx.extra().get('source')
3012 3017 if n:
3013 3018 ids[n] = ctx.rev()
3014 3019
3015 3020 # check ancestors for earlier grafts
3016 3021 ui.debug('scanning for duplicate grafts\n')
3017 3022
3018 3023 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3019 3024 ctx = repo[rev]
3020 3025 n = ctx.extra().get('source')
3021 3026 if n in ids:
3022 3027 r = repo[n].rev()
3023 3028 if r in revs:
3024 3029 ui.warn(_('skipping revision %s (already grafted to %s)\n')
3025 3030 % (r, rev))
3026 3031 revs.remove(r)
3027 3032 elif ids[n] in revs:
3028 3033 ui.warn(_('skipping already grafted revision %s '
3029 3034 '(%s also has origin %d)\n') % (ids[n], rev, r))
3030 3035 revs.remove(ids[n])
3031 3036 elif ctx.hex() in ids:
3032 3037 r = ids[ctx.hex()]
3033 3038 ui.warn(_('skipping already grafted revision %s '
3034 3039 '(was grafted from %d)\n') % (r, rev))
3035 3040 revs.remove(r)
3036 3041 if not revs:
3037 3042 return -1
3038 3043
3039 3044 wlock = repo.wlock()
3040 3045 try:
3041 3046 current = repo['.']
3042 3047 for pos, ctx in enumerate(repo.set("%ld", revs)):
3043 3048
3044 3049 ui.status(_('grafting revision %s\n') % ctx.rev())
3045 3050 if opts.get('dry_run'):
3046 3051 continue
3047 3052
3048 3053 source = ctx.extra().get('source')
3049 3054 if not source:
3050 3055 source = ctx.hex()
3051 3056 extra = {'source': source}
3052 3057 user = ctx.user()
3053 3058 if opts.get('user'):
3054 3059 user = opts['user']
3055 3060 date = ctx.date()
3056 3061 if opts.get('date'):
3057 3062 date = opts['date']
3058 3063 message = ctx.description()
3059 3064 if opts.get('log'):
3060 3065 message += '\n(grafted from %s)' % ctx.hex()
3061 3066
3062 3067 # we don't merge the first commit when continuing
3063 3068 if not cont:
3064 3069 # perform the graft merge with p1(rev) as 'ancestor'
3065 3070 try:
3066 3071 # ui.forcemerge is an internal variable, do not document
3067 3072 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3068 3073 stats = mergemod.update(repo, ctx.node(), True, True, False,
3069 3074 ctx.p1().node())
3070 3075 finally:
3071 3076 repo.ui.setconfig('ui', 'forcemerge', '')
3072 3077 # report any conflicts
3073 3078 if stats and stats[3] > 0:
3074 3079 # write out state for --continue
3075 3080 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3076 3081 repo.opener.write('graftstate', ''.join(nodelines))
3077 3082 raise util.Abort(
3078 3083 _("unresolved conflicts, can't continue"),
3079 3084 hint=_('use hg resolve and hg graft --continue'))
3080 3085 else:
3081 3086 cont = False
3082 3087
3083 3088 # drop the second merge parent
3084 3089 repo.setparents(current.node(), nullid)
3085 3090 repo.dirstate.write()
3086 3091 # fix up dirstate for copies and renames
3087 3092 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
3088 3093
3089 3094 # commit
3090 3095 node = repo.commit(text=message, user=user,
3091 3096 date=date, extra=extra, editor=editor)
3092 3097 if node is None:
3093 3098 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
3094 3099 else:
3095 3100 current = repo[node]
3096 3101 finally:
3097 3102 wlock.release()
3098 3103
3099 3104 # remove state when we complete successfully
3100 3105 if not opts.get('dry_run'):
3101 3106 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3102 3107
3103 3108 return 0
3104 3109
3105 3110 @command('grep',
3106 3111 [('0', 'print0', None, _('end fields with NUL')),
3107 3112 ('', 'all', None, _('print all revisions that match')),
3108 3113 ('a', 'text', None, _('treat all files as text')),
3109 3114 ('f', 'follow', None,
3110 3115 _('follow changeset history,'
3111 3116 ' or file history across copies and renames')),
3112 3117 ('i', 'ignore-case', None, _('ignore case when matching')),
3113 3118 ('l', 'files-with-matches', None,
3114 3119 _('print only filenames and revisions that match')),
3115 3120 ('n', 'line-number', None, _('print matching line numbers')),
3116 3121 ('r', 'rev', [],
3117 3122 _('only search files changed within revision range'), _('REV')),
3118 3123 ('u', 'user', None, _('list the author (long with -v)')),
3119 3124 ('d', 'date', None, _('list the date (short with -q)')),
3120 3125 ] + walkopts,
3121 3126 _('[OPTION]... PATTERN [FILE]...'))
3122 3127 def grep(ui, repo, pattern, *pats, **opts):
3123 3128 """search for a pattern in specified files and revisions
3124 3129
3125 3130 Search revisions of files for a regular expression.
3126 3131
3127 3132 This command behaves differently than Unix grep. It only accepts
3128 3133 Python/Perl regexps. It searches repository history, not the
3129 3134 working directory. It always prints the revision number in which a
3130 3135 match appears.
3131 3136
3132 3137 By default, grep only prints output for the first revision of a
3133 3138 file in which it finds a match. To get it to print every revision
3134 3139 that contains a change in match status ("-" for a match that
3135 3140 becomes a non-match, or "+" for a non-match that becomes a match),
3136 3141 use the --all flag.
3137 3142
3138 3143 Returns 0 if a match is found, 1 otherwise.
3139 3144 """
3140 3145 reflags = re.M
3141 3146 if opts.get('ignore_case'):
3142 3147 reflags |= re.I
3143 3148 try:
3144 3149 regexp = util.compilere(pattern, reflags)
3145 3150 except re.error, inst:
3146 3151 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3147 3152 return 1
3148 3153 sep, eol = ':', '\n'
3149 3154 if opts.get('print0'):
3150 3155 sep = eol = '\0'
3151 3156
3152 3157 getfile = util.lrucachefunc(repo.file)
3153 3158
3154 3159 def matchlines(body):
3155 3160 begin = 0
3156 3161 linenum = 0
3157 3162 while begin < len(body):
3158 3163 match = regexp.search(body, begin)
3159 3164 if not match:
3160 3165 break
3161 3166 mstart, mend = match.span()
3162 3167 linenum += body.count('\n', begin, mstart) + 1
3163 3168 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3164 3169 begin = body.find('\n', mend) + 1 or len(body) + 1
3165 3170 lend = begin - 1
3166 3171 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3167 3172
3168 3173 class linestate(object):
3169 3174 def __init__(self, line, linenum, colstart, colend):
3170 3175 self.line = line
3171 3176 self.linenum = linenum
3172 3177 self.colstart = colstart
3173 3178 self.colend = colend
3174 3179
3175 3180 def __hash__(self):
3176 3181 return hash((self.linenum, self.line))
3177 3182
3178 3183 def __eq__(self, other):
3179 3184 return self.line == other.line
3180 3185
3181 3186 matches = {}
3182 3187 copies = {}
3183 3188 def grepbody(fn, rev, body):
3184 3189 matches[rev].setdefault(fn, [])
3185 3190 m = matches[rev][fn]
3186 3191 for lnum, cstart, cend, line in matchlines(body):
3187 3192 s = linestate(line, lnum, cstart, cend)
3188 3193 m.append(s)
3189 3194
3190 3195 def difflinestates(a, b):
3191 3196 sm = difflib.SequenceMatcher(None, a, b)
3192 3197 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3193 3198 if tag == 'insert':
3194 3199 for i in xrange(blo, bhi):
3195 3200 yield ('+', b[i])
3196 3201 elif tag == 'delete':
3197 3202 for i in xrange(alo, ahi):
3198 3203 yield ('-', a[i])
3199 3204 elif tag == 'replace':
3200 3205 for i in xrange(alo, ahi):
3201 3206 yield ('-', a[i])
3202 3207 for i in xrange(blo, bhi):
3203 3208 yield ('+', b[i])
3204 3209
3205 3210 def display(fn, ctx, pstates, states):
3206 3211 rev = ctx.rev()
3207 3212 datefunc = ui.quiet and util.shortdate or util.datestr
3208 3213 found = False
3209 3214 filerevmatches = {}
3210 3215 def binary():
3211 3216 flog = getfile(fn)
3212 3217 return util.binary(flog.read(ctx.filenode(fn)))
3213 3218
3214 3219 if opts.get('all'):
3215 3220 iter = difflinestates(pstates, states)
3216 3221 else:
3217 3222 iter = [('', l) for l in states]
3218 3223 for change, l in iter:
3219 3224 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3220 3225 before, match, after = None, None, None
3221 3226
3222 3227 if opts.get('line_number'):
3223 3228 cols.append((str(l.linenum), 'grep.linenumber'))
3224 3229 if opts.get('all'):
3225 3230 cols.append((change, 'grep.change'))
3226 3231 if opts.get('user'):
3227 3232 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3228 3233 if opts.get('date'):
3229 3234 cols.append((datefunc(ctx.date()), 'grep.date'))
3230 3235 if opts.get('files_with_matches'):
3231 3236 c = (fn, rev)
3232 3237 if c in filerevmatches:
3233 3238 continue
3234 3239 filerevmatches[c] = 1
3235 3240 else:
3236 3241 before = l.line[:l.colstart]
3237 3242 match = l.line[l.colstart:l.colend]
3238 3243 after = l.line[l.colend:]
3239 3244 for col, label in cols[:-1]:
3240 3245 ui.write(col, label=label)
3241 3246 ui.write(sep, label='grep.sep')
3242 3247 ui.write(cols[-1][0], label=cols[-1][1])
3243 3248 if before is not None:
3244 3249 ui.write(sep, label='grep.sep')
3245 3250 if not opts.get('text') and binary():
3246 3251 ui.write(" Binary file matches")
3247 3252 else:
3248 3253 ui.write(before)
3249 3254 ui.write(match, label='grep.match')
3250 3255 ui.write(after)
3251 3256 ui.write(eol)
3252 3257 found = True
3253 3258 return found
3254 3259
3255 3260 skip = {}
3256 3261 revfiles = {}
3257 3262 matchfn = scmutil.match(repo[None], pats, opts)
3258 3263 found = False
3259 3264 follow = opts.get('follow')
3260 3265
3261 3266 def prep(ctx, fns):
3262 3267 rev = ctx.rev()
3263 3268 pctx = ctx.p1()
3264 3269 parent = pctx.rev()
3265 3270 matches.setdefault(rev, {})
3266 3271 matches.setdefault(parent, {})
3267 3272 files = revfiles.setdefault(rev, [])
3268 3273 for fn in fns:
3269 3274 flog = getfile(fn)
3270 3275 try:
3271 3276 fnode = ctx.filenode(fn)
3272 3277 except error.LookupError:
3273 3278 continue
3274 3279
3275 3280 copied = flog.renamed(fnode)
3276 3281 copy = follow and copied and copied[0]
3277 3282 if copy:
3278 3283 copies.setdefault(rev, {})[fn] = copy
3279 3284 if fn in skip:
3280 3285 if copy:
3281 3286 skip[copy] = True
3282 3287 continue
3283 3288 files.append(fn)
3284 3289
3285 3290 if fn not in matches[rev]:
3286 3291 grepbody(fn, rev, flog.read(fnode))
3287 3292
3288 3293 pfn = copy or fn
3289 3294 if pfn not in matches[parent]:
3290 3295 try:
3291 3296 fnode = pctx.filenode(pfn)
3292 3297 grepbody(pfn, parent, flog.read(fnode))
3293 3298 except error.LookupError:
3294 3299 pass
3295 3300
3296 3301 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3297 3302 rev = ctx.rev()
3298 3303 parent = ctx.p1().rev()
3299 3304 for fn in sorted(revfiles.get(rev, [])):
3300 3305 states = matches[rev][fn]
3301 3306 copy = copies.get(rev, {}).get(fn)
3302 3307 if fn in skip:
3303 3308 if copy:
3304 3309 skip[copy] = True
3305 3310 continue
3306 3311 pstates = matches.get(parent, {}).get(copy or fn, [])
3307 3312 if pstates or states:
3308 3313 r = display(fn, ctx, pstates, states)
3309 3314 found = found or r
3310 3315 if r and not opts.get('all'):
3311 3316 skip[fn] = True
3312 3317 if copy:
3313 3318 skip[copy] = True
3314 3319 del matches[rev]
3315 3320 del revfiles[rev]
3316 3321
3317 3322 return not found
3318 3323
3319 3324 @command('heads',
3320 3325 [('r', 'rev', '',
3321 3326 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3322 3327 ('t', 'topo', False, _('show topological heads only')),
3323 3328 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3324 3329 ('c', 'closed', False, _('show normal and closed branch heads')),
3325 3330 ] + templateopts,
3326 3331 _('[-ct] [-r STARTREV] [REV]...'))
3327 3332 def heads(ui, repo, *branchrevs, **opts):
3328 3333 """show branch heads
3329 3334
3330 3335 With no arguments, show all open branch heads in the repository.
3331 3336 Branch heads are changesets that have no descendants on the
3332 3337 same branch. They are where development generally takes place and
3333 3338 are the usual targets for update and merge operations.
3334 3339
3335 3340 If one or more REVs are given, only open branch heads on the
3336 3341 branches associated with the specified changesets are shown. This
3337 3342 means that you can use :hg:`heads .` to see the heads on the
3338 3343 currently checked-out branch.
3339 3344
3340 3345 If -c/--closed is specified, also show branch heads marked closed
3341 3346 (see :hg:`commit --close-branch`).
3342 3347
3343 3348 If STARTREV is specified, only those heads that are descendants of
3344 3349 STARTREV will be displayed.
3345 3350
3346 3351 If -t/--topo is specified, named branch mechanics will be ignored and only
3347 3352 topological heads (changesets with no children) will be shown.
3348 3353
3349 3354 Returns 0 if matching heads are found, 1 if not.
3350 3355 """
3351 3356
3352 3357 start = None
3353 3358 if 'rev' in opts:
3354 3359 start = scmutil.revsingle(repo, opts['rev'], None).node()
3355 3360
3356 3361 if opts.get('topo'):
3357 3362 heads = [repo[h] for h in repo.heads(start)]
3358 3363 else:
3359 3364 heads = []
3360 3365 for branch in repo.branchmap():
3361 3366 heads += repo.branchheads(branch, start, opts.get('closed'))
3362 3367 heads = [repo[h] for h in heads]
3363 3368
3364 3369 if branchrevs:
3365 3370 branches = set(repo[br].branch() for br in branchrevs)
3366 3371 heads = [h for h in heads if h.branch() in branches]
3367 3372
3368 3373 if opts.get('active') and branchrevs:
3369 3374 dagheads = repo.heads(start)
3370 3375 heads = [h for h in heads if h.node() in dagheads]
3371 3376
3372 3377 if branchrevs:
3373 3378 haveheads = set(h.branch() for h in heads)
3374 3379 if branches - haveheads:
3375 3380 headless = ', '.join(b for b in branches - haveheads)
3376 3381 msg = _('no open branch heads found on branches %s')
3377 3382 if opts.get('rev'):
3378 3383 msg += _(' (started at %s)') % opts['rev']
3379 3384 ui.warn((msg + '\n') % headless)
3380 3385
3381 3386 if not heads:
3382 3387 return 1
3383 3388
3384 3389 heads = sorted(heads, key=lambda x: -x.rev())
3385 3390 displayer = cmdutil.show_changeset(ui, repo, opts)
3386 3391 for ctx in heads:
3387 3392 displayer.show(ctx)
3388 3393 displayer.close()
3389 3394
3390 3395 @command('help',
3391 3396 [('e', 'extension', None, _('show only help for extensions')),
3392 3397 ('c', 'command', None, _('show only help for commands')),
3393 3398 ('k', 'keyword', '', _('show topics matching keyword')),
3394 3399 ],
3395 3400 _('[-ec] [TOPIC]'))
3396 3401 def help_(ui, name=None, **opts):
3397 3402 """show help for a given topic or a help overview
3398 3403
3399 3404 With no arguments, print a list of commands with short help messages.
3400 3405
3401 3406 Given a topic, extension, or command name, print help for that
3402 3407 topic.
3403 3408
3404 3409 Returns 0 if successful.
3405 3410 """
3406 3411
3407 3412 textwidth = min(ui.termwidth(), 80) - 2
3408 3413
3409 3414 keep = ui.verbose and ['verbose'] or []
3410 3415 text = help.help_(ui, name, **opts)
3411 3416
3412 3417 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3413 3418 if 'verbose' in pruned:
3414 3419 keep.append('omitted')
3415 3420 else:
3416 3421 keep.append('notomitted')
3417 3422 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3418 3423 ui.write(formatted)
3419 3424
3420 3425
3421 3426 @command('identify|id',
3422 3427 [('r', 'rev', '',
3423 3428 _('identify the specified revision'), _('REV')),
3424 3429 ('n', 'num', None, _('show local revision number')),
3425 3430 ('i', 'id', None, _('show global revision id')),
3426 3431 ('b', 'branch', None, _('show branch')),
3427 3432 ('t', 'tags', None, _('show tags')),
3428 3433 ('B', 'bookmarks', None, _('show bookmarks')),
3429 3434 ] + remoteopts,
3430 3435 _('[-nibtB] [-r REV] [SOURCE]'))
3431 3436 def identify(ui, repo, source=None, rev=None,
3432 3437 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3433 3438 """identify the working copy or specified revision
3434 3439
3435 3440 Print a summary identifying the repository state at REV using one or
3436 3441 two parent hash identifiers, followed by a "+" if the working
3437 3442 directory has uncommitted changes, the branch name (if not default),
3438 3443 a list of tags, and a list of bookmarks.
3439 3444
3440 3445 When REV is not given, print a summary of the current state of the
3441 3446 repository.
3442 3447
3443 3448 Specifying a path to a repository root or Mercurial bundle will
3444 3449 cause lookup to operate on that repository/bundle.
3445 3450
3446 3451 .. container:: verbose
3447 3452
3448 3453 Examples:
3449 3454
3450 3455 - generate a build identifier for the working directory::
3451 3456
3452 3457 hg id --id > build-id.dat
3453 3458
3454 3459 - find the revision corresponding to a tag::
3455 3460
3456 3461 hg id -n -r 1.3
3457 3462
3458 3463 - check the most recent revision of a remote repository::
3459 3464
3460 3465 hg id -r tip http://selenic.com/hg/
3461 3466
3462 3467 Returns 0 if successful.
3463 3468 """
3464 3469
3465 3470 if not repo and not source:
3466 3471 raise util.Abort(_("there is no Mercurial repository here "
3467 3472 "(.hg not found)"))
3468 3473
3469 3474 hexfunc = ui.debugflag and hex or short
3470 3475 default = not (num or id or branch or tags or bookmarks)
3471 3476 output = []
3472 3477 revs = []
3473 3478
3474 3479 if source:
3475 3480 source, branches = hg.parseurl(ui.expandpath(source))
3476 3481 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3477 3482 repo = peer.local()
3478 3483 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3479 3484
3480 3485 if not repo:
3481 3486 if num or branch or tags:
3482 3487 raise util.Abort(
3483 3488 _("can't query remote revision number, branch, or tags"))
3484 3489 if not rev and revs:
3485 3490 rev = revs[0]
3486 3491 if not rev:
3487 3492 rev = "tip"
3488 3493
3489 3494 remoterev = peer.lookup(rev)
3490 3495 if default or id:
3491 3496 output = [hexfunc(remoterev)]
3492 3497
3493 3498 def getbms():
3494 3499 bms = []
3495 3500
3496 3501 if 'bookmarks' in peer.listkeys('namespaces'):
3497 3502 hexremoterev = hex(remoterev)
3498 3503 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3499 3504 if bmr == hexremoterev]
3500 3505
3501 3506 return sorted(bms)
3502 3507
3503 3508 if bookmarks:
3504 3509 output.extend(getbms())
3505 3510 elif default and not ui.quiet:
3506 3511 # multiple bookmarks for a single parent separated by '/'
3507 3512 bm = '/'.join(getbms())
3508 3513 if bm:
3509 3514 output.append(bm)
3510 3515 else:
3511 3516 if not rev:
3512 3517 ctx = repo[None]
3513 3518 parents = ctx.parents()
3514 3519 changed = ""
3515 3520 if default or id or num:
3516 3521 if (util.any(repo.status())
3517 3522 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3518 3523 changed = '+'
3519 3524 if default or id:
3520 3525 output = ["%s%s" %
3521 3526 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3522 3527 if num:
3523 3528 output.append("%s%s" %
3524 3529 ('+'.join([str(p.rev()) for p in parents]), changed))
3525 3530 else:
3526 3531 ctx = scmutil.revsingle(repo, rev)
3527 3532 if default or id:
3528 3533 output = [hexfunc(ctx.node())]
3529 3534 if num:
3530 3535 output.append(str(ctx.rev()))
3531 3536
3532 3537 if default and not ui.quiet:
3533 3538 b = ctx.branch()
3534 3539 if b != 'default':
3535 3540 output.append("(%s)" % b)
3536 3541
3537 3542 # multiple tags for a single parent separated by '/'
3538 3543 t = '/'.join(ctx.tags())
3539 3544 if t:
3540 3545 output.append(t)
3541 3546
3542 3547 # multiple bookmarks for a single parent separated by '/'
3543 3548 bm = '/'.join(ctx.bookmarks())
3544 3549 if bm:
3545 3550 output.append(bm)
3546 3551 else:
3547 3552 if branch:
3548 3553 output.append(ctx.branch())
3549 3554
3550 3555 if tags:
3551 3556 output.extend(ctx.tags())
3552 3557
3553 3558 if bookmarks:
3554 3559 output.extend(ctx.bookmarks())
3555 3560
3556 3561 ui.write("%s\n" % ' '.join(output))
3557 3562
3558 3563 @command('import|patch',
3559 3564 [('p', 'strip', 1,
3560 3565 _('directory strip option for patch. This has the same '
3561 3566 'meaning as the corresponding patch option'), _('NUM')),
3562 3567 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3563 3568 ('e', 'edit', False, _('invoke editor on commit messages')),
3564 3569 ('f', 'force', None,
3565 3570 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
3566 3571 ('', 'no-commit', None,
3567 3572 _("don't commit, just update the working directory")),
3568 3573 ('', 'bypass', None,
3569 3574 _("apply patch without touching the working directory")),
3570 3575 ('', 'exact', None,
3571 3576 _('apply patch to the nodes from which it was generated')),
3572 3577 ('', 'import-branch', None,
3573 3578 _('use any branch information in patch (implied by --exact)'))] +
3574 3579 commitopts + commitopts2 + similarityopts,
3575 3580 _('[OPTION]... PATCH...'))
3576 3581 def import_(ui, repo, patch1=None, *patches, **opts):
3577 3582 """import an ordered set of patches
3578 3583
3579 3584 Import a list of patches and commit them individually (unless
3580 3585 --no-commit is specified).
3581 3586
3582 3587 Because import first applies changes to the working directory,
3583 3588 import will abort if there are outstanding changes.
3584 3589
3585 3590 You can import a patch straight from a mail message. Even patches
3586 3591 as attachments work (to use the body part, it must have type
3587 3592 text/plain or text/x-patch). From and Subject headers of email
3588 3593 message are used as default committer and commit message. All
3589 3594 text/plain body parts before first diff are added to commit
3590 3595 message.
3591 3596
3592 3597 If the imported patch was generated by :hg:`export`, user and
3593 3598 description from patch override values from message headers and
3594 3599 body. Values given on command line with -m/--message and -u/--user
3595 3600 override these.
3596 3601
3597 3602 If --exact is specified, import will set the working directory to
3598 3603 the parent of each patch before applying it, and will abort if the
3599 3604 resulting changeset has a different ID than the one recorded in
3600 3605 the patch. This may happen due to character set problems or other
3601 3606 deficiencies in the text patch format.
3602 3607
3603 3608 Use --bypass to apply and commit patches directly to the
3604 3609 repository, not touching the working directory. Without --exact,
3605 3610 patches will be applied on top of the working directory parent
3606 3611 revision.
3607 3612
3608 3613 With -s/--similarity, hg will attempt to discover renames and
3609 3614 copies in the patch in the same way as :hg:`addremove`.
3610 3615
3611 3616 To read a patch from standard input, use "-" as the patch name. If
3612 3617 a URL is specified, the patch will be downloaded from it.
3613 3618 See :hg:`help dates` for a list of formats valid for -d/--date.
3614 3619
3615 3620 .. container:: verbose
3616 3621
3617 3622 Examples:
3618 3623
3619 3624 - import a traditional patch from a website and detect renames::
3620 3625
3621 3626 hg import -s 80 http://example.com/bugfix.patch
3622 3627
3623 3628 - import a changeset from an hgweb server::
3624 3629
3625 3630 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3626 3631
3627 3632 - import all the patches in an Unix-style mbox::
3628 3633
3629 3634 hg import incoming-patches.mbox
3630 3635
3631 3636 - attempt to exactly restore an exported changeset (not always
3632 3637 possible)::
3633 3638
3634 3639 hg import --exact proposed-fix.patch
3635 3640
3636 3641 Returns 0 on success.
3637 3642 """
3638 3643
3639 3644 if not patch1:
3640 3645 raise util.Abort(_('need at least one patch to import'))
3641 3646
3642 3647 patches = (patch1,) + patches
3643 3648
3644 3649 date = opts.get('date')
3645 3650 if date:
3646 3651 opts['date'] = util.parsedate(date)
3647 3652
3648 3653 editor = cmdutil.commiteditor
3649 3654 if opts.get('edit'):
3650 3655 editor = cmdutil.commitforceeditor
3651 3656
3652 3657 update = not opts.get('bypass')
3653 3658 if not update and opts.get('no_commit'):
3654 3659 raise util.Abort(_('cannot use --no-commit with --bypass'))
3655 3660 try:
3656 3661 sim = float(opts.get('similarity') or 0)
3657 3662 except ValueError:
3658 3663 raise util.Abort(_('similarity must be a number'))
3659 3664 if sim < 0 or sim > 100:
3660 3665 raise util.Abort(_('similarity must be between 0 and 100'))
3661 3666 if sim and not update:
3662 3667 raise util.Abort(_('cannot use --similarity with --bypass'))
3663 3668
3664 3669 if update:
3665 3670 cmdutil.checkunfinished(repo)
3666 3671 if (opts.get('exact') or not opts.get('force')) and update:
3667 3672 cmdutil.bailifchanged(repo)
3668 3673
3669 3674 base = opts["base"]
3670 3675 strip = opts["strip"]
3671 3676 wlock = lock = tr = None
3672 3677 msgs = []
3673 3678
3674 3679 def tryone(ui, hunk, parents):
3675 3680 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3676 3681 patch.extract(ui, hunk)
3677 3682
3678 3683 if not tmpname:
3679 3684 return (None, None)
3680 3685 msg = _('applied to working directory')
3681 3686
3682 3687 try:
3683 3688 cmdline_message = cmdutil.logmessage(ui, opts)
3684 3689 if cmdline_message:
3685 3690 # pickup the cmdline msg
3686 3691 message = cmdline_message
3687 3692 elif message:
3688 3693 # pickup the patch msg
3689 3694 message = message.strip()
3690 3695 else:
3691 3696 # launch the editor
3692 3697 message = None
3693 3698 ui.debug('message:\n%s\n' % message)
3694 3699
3695 3700 if len(parents) == 1:
3696 3701 parents.append(repo[nullid])
3697 3702 if opts.get('exact'):
3698 3703 if not nodeid or not p1:
3699 3704 raise util.Abort(_('not a Mercurial patch'))
3700 3705 p1 = repo[p1]
3701 3706 p2 = repo[p2 or nullid]
3702 3707 elif p2:
3703 3708 try:
3704 3709 p1 = repo[p1]
3705 3710 p2 = repo[p2]
3706 3711 # Without any options, consider p2 only if the
3707 3712 # patch is being applied on top of the recorded
3708 3713 # first parent.
3709 3714 if p1 != parents[0]:
3710 3715 p1 = parents[0]
3711 3716 p2 = repo[nullid]
3712 3717 except error.RepoError:
3713 3718 p1, p2 = parents
3714 3719 else:
3715 3720 p1, p2 = parents
3716 3721
3717 3722 n = None
3718 3723 if update:
3719 3724 if p1 != parents[0]:
3720 3725 hg.clean(repo, p1.node())
3721 3726 if p2 != parents[1]:
3722 3727 repo.setparents(p1.node(), p2.node())
3723 3728
3724 3729 if opts.get('exact') or opts.get('import_branch'):
3725 3730 repo.dirstate.setbranch(branch or 'default')
3726 3731
3727 3732 files = set()
3728 3733 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3729 3734 eolmode=None, similarity=sim / 100.0)
3730 3735 files = list(files)
3731 3736 if opts.get('no_commit'):
3732 3737 if message:
3733 3738 msgs.append(message)
3734 3739 else:
3735 3740 if opts.get('exact') or p2:
3736 3741 # If you got here, you either use --force and know what
3737 3742 # you are doing or used --exact or a merge patch while
3738 3743 # being updated to its first parent.
3739 3744 m = None
3740 3745 else:
3741 3746 m = scmutil.matchfiles(repo, files or [])
3742 3747 n = repo.commit(message, opts.get('user') or user,
3743 3748 opts.get('date') or date, match=m,
3744 3749 editor=editor)
3745 3750 else:
3746 3751 if opts.get('exact') or opts.get('import_branch'):
3747 3752 branch = branch or 'default'
3748 3753 else:
3749 3754 branch = p1.branch()
3750 3755 store = patch.filestore()
3751 3756 try:
3752 3757 files = set()
3753 3758 try:
3754 3759 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3755 3760 files, eolmode=None)
3756 3761 except patch.PatchError, e:
3757 3762 raise util.Abort(str(e))
3758 3763 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3759 3764 message,
3760 3765 opts.get('user') or user,
3761 3766 opts.get('date') or date,
3762 3767 branch, files, store,
3763 3768 editor=cmdutil.commiteditor)
3764 3769 repo.savecommitmessage(memctx.description())
3765 3770 n = memctx.commit()
3766 3771 finally:
3767 3772 store.close()
3768 3773 if opts.get('exact') and hex(n) != nodeid:
3769 3774 raise util.Abort(_('patch is damaged or loses information'))
3770 3775 if n:
3771 3776 # i18n: refers to a short changeset id
3772 3777 msg = _('created %s') % short(n)
3773 3778 return (msg, n)
3774 3779 finally:
3775 3780 os.unlink(tmpname)
3776 3781
3777 3782 try:
3778 3783 try:
3779 3784 wlock = repo.wlock()
3780 3785 if not opts.get('no_commit'):
3781 3786 lock = repo.lock()
3782 3787 tr = repo.transaction('import')
3783 3788 parents = repo.parents()
3784 3789 for patchurl in patches:
3785 3790 if patchurl == '-':
3786 3791 ui.status(_('applying patch from stdin\n'))
3787 3792 patchfile = ui.fin
3788 3793 patchurl = 'stdin' # for error message
3789 3794 else:
3790 3795 patchurl = os.path.join(base, patchurl)
3791 3796 ui.status(_('applying %s\n') % patchurl)
3792 3797 patchfile = hg.openpath(ui, patchurl)
3793 3798
3794 3799 haspatch = False
3795 3800 for hunk in patch.split(patchfile):
3796 3801 (msg, node) = tryone(ui, hunk, parents)
3797 3802 if msg:
3798 3803 haspatch = True
3799 3804 ui.note(msg + '\n')
3800 3805 if update or opts.get('exact'):
3801 3806 parents = repo.parents()
3802 3807 else:
3803 3808 parents = [repo[node]]
3804 3809
3805 3810 if not haspatch:
3806 3811 raise util.Abort(_('%s: no diffs found') % patchurl)
3807 3812
3808 3813 if tr:
3809 3814 tr.close()
3810 3815 if msgs:
3811 3816 repo.savecommitmessage('\n* * *\n'.join(msgs))
3812 3817 except: # re-raises
3813 3818 # wlock.release() indirectly calls dirstate.write(): since
3814 3819 # we're crashing, we do not want to change the working dir
3815 3820 # parent after all, so make sure it writes nothing
3816 3821 repo.dirstate.invalidate()
3817 3822 raise
3818 3823 finally:
3819 3824 if tr:
3820 3825 tr.release()
3821 3826 release(lock, wlock)
3822 3827
3823 3828 @command('incoming|in',
3824 3829 [('f', 'force', None,
3825 3830 _('run even if remote repository is unrelated')),
3826 3831 ('n', 'newest-first', None, _('show newest record first')),
3827 3832 ('', 'bundle', '',
3828 3833 _('file to store the bundles into'), _('FILE')),
3829 3834 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3830 3835 ('B', 'bookmarks', False, _("compare bookmarks")),
3831 3836 ('b', 'branch', [],
3832 3837 _('a specific branch you would like to pull'), _('BRANCH')),
3833 3838 ] + logopts + remoteopts + subrepoopts,
3834 3839 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3835 3840 def incoming(ui, repo, source="default", **opts):
3836 3841 """show new changesets found in source
3837 3842
3838 3843 Show new changesets found in the specified path/URL or the default
3839 3844 pull location. These are the changesets that would have been pulled
3840 3845 if a pull at the time you issued this command.
3841 3846
3842 3847 For remote repository, using --bundle avoids downloading the
3843 3848 changesets twice if the incoming is followed by a pull.
3844 3849
3845 3850 See pull for valid source format details.
3846 3851
3847 3852 Returns 0 if there are incoming changes, 1 otherwise.
3848 3853 """
3849 3854 if opts.get('graph'):
3850 3855 cmdutil.checkunsupportedgraphflags([], opts)
3851 3856 def display(other, chlist, displayer):
3852 3857 revdag = cmdutil.graphrevs(other, chlist, opts)
3853 3858 showparents = [ctx.node() for ctx in repo[None].parents()]
3854 3859 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3855 3860 graphmod.asciiedges)
3856 3861
3857 3862 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3858 3863 return 0
3859 3864
3860 3865 if opts.get('bundle') and opts.get('subrepos'):
3861 3866 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3862 3867
3863 3868 if opts.get('bookmarks'):
3864 3869 source, branches = hg.parseurl(ui.expandpath(source),
3865 3870 opts.get('branch'))
3866 3871 other = hg.peer(repo, opts, source)
3867 3872 if 'bookmarks' not in other.listkeys('namespaces'):
3868 3873 ui.warn(_("remote doesn't support bookmarks\n"))
3869 3874 return 0
3870 3875 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3871 3876 return bookmarks.diff(ui, repo, other)
3872 3877
3873 3878 repo._subtoppath = ui.expandpath(source)
3874 3879 try:
3875 3880 return hg.incoming(ui, repo, source, opts)
3876 3881 finally:
3877 3882 del repo._subtoppath
3878 3883
3879 3884
3880 3885 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3881 3886 def init(ui, dest=".", **opts):
3882 3887 """create a new repository in the given directory
3883 3888
3884 3889 Initialize a new repository in the given directory. If the given
3885 3890 directory does not exist, it will be created.
3886 3891
3887 3892 If no directory is given, the current directory is used.
3888 3893
3889 3894 It is possible to specify an ``ssh://`` URL as the destination.
3890 3895 See :hg:`help urls` for more information.
3891 3896
3892 3897 Returns 0 on success.
3893 3898 """
3894 3899 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3895 3900
3896 3901 @command('locate',
3897 3902 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3898 3903 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3899 3904 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3900 3905 ] + walkopts,
3901 3906 _('[OPTION]... [PATTERN]...'))
3902 3907 def locate(ui, repo, *pats, **opts):
3903 3908 """locate files matching specific patterns
3904 3909
3905 3910 Print files under Mercurial control in the working directory whose
3906 3911 names match the given patterns.
3907 3912
3908 3913 By default, this command searches all directories in the working
3909 3914 directory. To search just the current directory and its
3910 3915 subdirectories, use "--include .".
3911 3916
3912 3917 If no patterns are given to match, this command prints the names
3913 3918 of all files under Mercurial control in the working directory.
3914 3919
3915 3920 If you want to feed the output of this command into the "xargs"
3916 3921 command, use the -0 option to both this command and "xargs". This
3917 3922 will avoid the problem of "xargs" treating single filenames that
3918 3923 contain whitespace as multiple filenames.
3919 3924
3920 3925 Returns 0 if a match is found, 1 otherwise.
3921 3926 """
3922 3927 end = opts.get('print0') and '\0' or '\n'
3923 3928 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3924 3929
3925 3930 ret = 1
3926 3931 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3927 3932 m.bad = lambda x, y: False
3928 3933 for abs in repo[rev].walk(m):
3929 3934 if not rev and abs not in repo.dirstate:
3930 3935 continue
3931 3936 if opts.get('fullpath'):
3932 3937 ui.write(repo.wjoin(abs), end)
3933 3938 else:
3934 3939 ui.write(((pats and m.rel(abs)) or abs), end)
3935 3940 ret = 0
3936 3941
3937 3942 return ret
3938 3943
3939 3944 @command('^log|history',
3940 3945 [('f', 'follow', None,
3941 3946 _('follow changeset history, or file history across copies and renames')),
3942 3947 ('', 'follow-first', None,
3943 3948 _('only follow the first parent of merge changesets (DEPRECATED)')),
3944 3949 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3945 3950 ('C', 'copies', None, _('show copied files')),
3946 3951 ('k', 'keyword', [],
3947 3952 _('do case-insensitive search for a given text'), _('TEXT')),
3948 3953 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3949 3954 ('', 'removed', None, _('include revisions where files were removed')),
3950 3955 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3951 3956 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3952 3957 ('', 'only-branch', [],
3953 3958 _('show only changesets within the given named branch (DEPRECATED)'),
3954 3959 _('BRANCH')),
3955 3960 ('b', 'branch', [],
3956 3961 _('show changesets within the given named branch'), _('BRANCH')),
3957 3962 ('P', 'prune', [],
3958 3963 _('do not display revision or any of its ancestors'), _('REV')),
3959 3964 ] + logopts + walkopts,
3960 3965 _('[OPTION]... [FILE]'))
3961 3966 def log(ui, repo, *pats, **opts):
3962 3967 """show revision history of entire repository or files
3963 3968
3964 3969 Print the revision history of the specified files or the entire
3965 3970 project.
3966 3971
3967 3972 If no revision range is specified, the default is ``tip:0`` unless
3968 3973 --follow is set, in which case the working directory parent is
3969 3974 used as the starting revision.
3970 3975
3971 3976 File history is shown without following rename or copy history of
3972 3977 files. Use -f/--follow with a filename to follow history across
3973 3978 renames and copies. --follow without a filename will only show
3974 3979 ancestors or descendants of the starting revision.
3975 3980
3976 3981 By default this command prints revision number and changeset id,
3977 3982 tags, non-trivial parents, user, date and time, and a summary for
3978 3983 each commit. When the -v/--verbose switch is used, the list of
3979 3984 changed files and full commit message are shown.
3980 3985
3981 3986 .. note::
3987
3982 3988 log -p/--patch may generate unexpected diff output for merge
3983 3989 changesets, as it will only compare the merge changeset against
3984 3990 its first parent. Also, only files different from BOTH parents
3985 3991 will appear in files:.
3986 3992
3987 3993 .. note::
3994
3988 3995 for performance reasons, log FILE may omit duplicate changes
3989 3996 made on branches and will not show deletions. To see all
3990 3997 changes including duplicates and deletions, use the --removed
3991 3998 switch.
3992 3999
3993 4000 .. container:: verbose
3994 4001
3995 4002 Some examples:
3996 4003
3997 4004 - changesets with full descriptions and file lists::
3998 4005
3999 4006 hg log -v
4000 4007
4001 4008 - changesets ancestral to the working directory::
4002 4009
4003 4010 hg log -f
4004 4011
4005 4012 - last 10 commits on the current branch::
4006 4013
4007 4014 hg log -l 10 -b .
4008 4015
4009 4016 - changesets showing all modifications of a file, including removals::
4010 4017
4011 4018 hg log --removed file.c
4012 4019
4013 4020 - all changesets that touch a directory, with diffs, excluding merges::
4014 4021
4015 4022 hg log -Mp lib/
4016 4023
4017 4024 - all revision numbers that match a keyword::
4018 4025
4019 4026 hg log -k bug --template "{rev}\\n"
4020 4027
4021 4028 - check if a given changeset is included is a tagged release::
4022 4029
4023 4030 hg log -r "a21ccf and ancestor(1.9)"
4024 4031
4025 4032 - find all changesets by some user in a date range::
4026 4033
4027 4034 hg log -k alice -d "may 2008 to jul 2008"
4028 4035
4029 4036 - summary of all changesets after the last tag::
4030 4037
4031 4038 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4032 4039
4033 4040 See :hg:`help dates` for a list of formats valid for -d/--date.
4034 4041
4035 4042 See :hg:`help revisions` and :hg:`help revsets` for more about
4036 4043 specifying revisions.
4037 4044
4038 4045 See :hg:`help templates` for more about pre-packaged styles and
4039 4046 specifying custom templates.
4040 4047
4041 4048 Returns 0 on success.
4042 4049 """
4043 4050 if opts.get('graph'):
4044 4051 return cmdutil.graphlog(ui, repo, *pats, **opts)
4045 4052
4046 4053 matchfn = scmutil.match(repo[None], pats, opts)
4047 4054 limit = cmdutil.loglimit(opts)
4048 4055 count = 0
4049 4056
4050 4057 getrenamed, endrev = None, None
4051 4058 if opts.get('copies'):
4052 4059 if opts.get('rev'):
4053 4060 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
4054 4061 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4055 4062
4056 4063 df = False
4057 4064 if opts.get("date"):
4058 4065 df = util.matchdate(opts["date"])
4059 4066
4060 4067 branches = opts.get('branch', []) + opts.get('only_branch', [])
4061 4068 opts['branch'] = [repo.lookupbranch(b) for b in branches]
4062 4069
4063 4070 displayer = cmdutil.show_changeset(ui, repo, opts, True)
4064 4071 def prep(ctx, fns):
4065 4072 rev = ctx.rev()
4066 4073 parents = [p for p in repo.changelog.parentrevs(rev)
4067 4074 if p != nullrev]
4068 4075 if opts.get('no_merges') and len(parents) == 2:
4069 4076 return
4070 4077 if opts.get('only_merges') and len(parents) != 2:
4071 4078 return
4072 4079 if opts.get('branch') and ctx.branch() not in opts['branch']:
4073 4080 return
4074 4081 if df and not df(ctx.date()[0]):
4075 4082 return
4076 4083
4077 4084 lower = encoding.lower
4078 4085 if opts.get('user'):
4079 4086 luser = lower(ctx.user())
4080 4087 for k in [lower(x) for x in opts['user']]:
4081 4088 if (k in luser):
4082 4089 break
4083 4090 else:
4084 4091 return
4085 4092 if opts.get('keyword'):
4086 4093 luser = lower(ctx.user())
4087 4094 ldesc = lower(ctx.description())
4088 4095 lfiles = lower(" ".join(ctx.files()))
4089 4096 for k in [lower(x) for x in opts['keyword']]:
4090 4097 if (k in luser or k in ldesc or k in lfiles):
4091 4098 break
4092 4099 else:
4093 4100 return
4094 4101
4095 4102 copies = None
4096 4103 if getrenamed is not None and rev:
4097 4104 copies = []
4098 4105 for fn in ctx.files():
4099 4106 rename = getrenamed(fn, rev)
4100 4107 if rename:
4101 4108 copies.append((fn, rename[0]))
4102 4109
4103 4110 revmatchfn = None
4104 4111 if opts.get('patch') or opts.get('stat'):
4105 4112 if opts.get('follow') or opts.get('follow_first'):
4106 4113 # note: this might be wrong when following through merges
4107 4114 revmatchfn = scmutil.match(repo[None], fns, default='path')
4108 4115 else:
4109 4116 revmatchfn = matchfn
4110 4117
4111 4118 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4112 4119
4113 4120 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4114 4121 if displayer.flush(ctx.rev()):
4115 4122 count += 1
4116 4123 if count == limit:
4117 4124 break
4118 4125 displayer.close()
4119 4126
4120 4127 @command('manifest',
4121 4128 [('r', 'rev', '', _('revision to display'), _('REV')),
4122 4129 ('', 'all', False, _("list files from all revisions"))],
4123 4130 _('[-r REV]'))
4124 4131 def manifest(ui, repo, node=None, rev=None, **opts):
4125 4132 """output the current or given revision of the project manifest
4126 4133
4127 4134 Print a list of version controlled files for the given revision.
4128 4135 If no revision is given, the first parent of the working directory
4129 4136 is used, or the null revision if no revision is checked out.
4130 4137
4131 4138 With -v, print file permissions, symlink and executable bits.
4132 4139 With --debug, print file revision hashes.
4133 4140
4134 4141 If option --all is specified, the list of all files from all revisions
4135 4142 is printed. This includes deleted and renamed files.
4136 4143
4137 4144 Returns 0 on success.
4138 4145 """
4139 4146
4140 4147 fm = ui.formatter('manifest', opts)
4141 4148
4142 4149 if opts.get('all'):
4143 4150 if rev or node:
4144 4151 raise util.Abort(_("can't specify a revision with --all"))
4145 4152
4146 4153 res = []
4147 4154 prefix = "data/"
4148 4155 suffix = ".i"
4149 4156 plen = len(prefix)
4150 4157 slen = len(suffix)
4151 4158 lock = repo.lock()
4152 4159 try:
4153 4160 for fn, b, size in repo.store.datafiles():
4154 4161 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4155 4162 res.append(fn[plen:-slen])
4156 4163 finally:
4157 4164 lock.release()
4158 4165 for f in res:
4159 4166 fm.startitem()
4160 4167 fm.write("path", '%s\n', f)
4161 4168 fm.end()
4162 4169 return
4163 4170
4164 4171 if rev and node:
4165 4172 raise util.Abort(_("please specify just one revision"))
4166 4173
4167 4174 if not node:
4168 4175 node = rev
4169 4176
4170 4177 char = {'l': '@', 'x': '*', '': ''}
4171 4178 mode = {'l': '644', 'x': '755', '': '644'}
4172 4179 ctx = scmutil.revsingle(repo, node)
4173 4180 mf = ctx.manifest()
4174 4181 for f in ctx:
4175 4182 fm.startitem()
4176 4183 fl = ctx[f].flags()
4177 4184 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4178 4185 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4179 4186 fm.write('path', '%s\n', f)
4180 4187 fm.end()
4181 4188
4182 4189 @command('^merge',
4183 4190 [('f', 'force', None,
4184 4191 _('force a merge including outstanding changes (DEPRECATED)')),
4185 4192 ('r', 'rev', '', _('revision to merge'), _('REV')),
4186 4193 ('P', 'preview', None,
4187 4194 _('review revisions to merge (no merge is performed)'))
4188 4195 ] + mergetoolopts,
4189 4196 _('[-P] [-f] [[-r] REV]'))
4190 4197 def merge(ui, repo, node=None, **opts):
4191 4198 """merge working directory with another revision
4192 4199
4193 4200 The current working directory is updated with all changes made in
4194 4201 the requested revision since the last common predecessor revision.
4195 4202
4196 4203 Files that changed between either parent are marked as changed for
4197 4204 the next commit and a commit must be performed before any further
4198 4205 updates to the repository are allowed. The next commit will have
4199 4206 two parents.
4200 4207
4201 4208 ``--tool`` can be used to specify the merge tool used for file
4202 4209 merges. It overrides the HGMERGE environment variable and your
4203 4210 configuration files. See :hg:`help merge-tools` for options.
4204 4211
4205 4212 If no revision is specified, the working directory's parent is a
4206 4213 head revision, and the current branch contains exactly one other
4207 4214 head, the other head is merged with by default. Otherwise, an
4208 4215 explicit revision with which to merge with must be provided.
4209 4216
4210 4217 :hg:`resolve` must be used to resolve unresolved files.
4211 4218
4212 4219 To undo an uncommitted merge, use :hg:`update --clean .` which
4213 4220 will check out a clean copy of the original merge parent, losing
4214 4221 all changes.
4215 4222
4216 4223 Returns 0 on success, 1 if there are unresolved files.
4217 4224 """
4218 4225
4219 4226 if opts.get('rev') and node:
4220 4227 raise util.Abort(_("please specify just one revision"))
4221 4228 if not node:
4222 4229 node = opts.get('rev')
4223 4230
4224 4231 if node:
4225 4232 node = scmutil.revsingle(repo, node).node()
4226 4233
4227 4234 if not node and repo._bookmarkcurrent:
4228 4235 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4229 4236 curhead = repo[repo._bookmarkcurrent].node()
4230 4237 if len(bmheads) == 2:
4231 4238 if curhead == bmheads[0]:
4232 4239 node = bmheads[1]
4233 4240 else:
4234 4241 node = bmheads[0]
4235 4242 elif len(bmheads) > 2:
4236 4243 raise util.Abort(_("multiple matching bookmarks to merge - "
4237 4244 "please merge with an explicit rev or bookmark"),
4238 4245 hint=_("run 'hg heads' to see all heads"))
4239 4246 elif len(bmheads) <= 1:
4240 4247 raise util.Abort(_("no matching bookmark to merge - "
4241 4248 "please merge with an explicit rev or bookmark"),
4242 4249 hint=_("run 'hg heads' to see all heads"))
4243 4250
4244 4251 if not node and not repo._bookmarkcurrent:
4245 4252 branch = repo[None].branch()
4246 4253 bheads = repo.branchheads(branch)
4247 4254 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4248 4255
4249 4256 if len(nbhs) > 2:
4250 4257 raise util.Abort(_("branch '%s' has %d heads - "
4251 4258 "please merge with an explicit rev")
4252 4259 % (branch, len(bheads)),
4253 4260 hint=_("run 'hg heads .' to see heads"))
4254 4261
4255 4262 parent = repo.dirstate.p1()
4256 4263 if len(nbhs) <= 1:
4257 4264 if len(bheads) > 1:
4258 4265 raise util.Abort(_("heads are bookmarked - "
4259 4266 "please merge with an explicit rev"),
4260 4267 hint=_("run 'hg heads' to see all heads"))
4261 4268 if len(repo.heads()) > 1:
4262 4269 raise util.Abort(_("branch '%s' has one head - "
4263 4270 "please merge with an explicit rev")
4264 4271 % branch,
4265 4272 hint=_("run 'hg heads' to see all heads"))
4266 4273 msg, hint = _('nothing to merge'), None
4267 4274 if parent != repo.lookup(branch):
4268 4275 hint = _("use 'hg update' instead")
4269 4276 raise util.Abort(msg, hint=hint)
4270 4277
4271 4278 if parent not in bheads:
4272 4279 raise util.Abort(_('working directory not at a head revision'),
4273 4280 hint=_("use 'hg update' or merge with an "
4274 4281 "explicit revision"))
4275 4282 if parent == nbhs[0]:
4276 4283 node = nbhs[-1]
4277 4284 else:
4278 4285 node = nbhs[0]
4279 4286
4280 4287 if opts.get('preview'):
4281 4288 # find nodes that are ancestors of p2 but not of p1
4282 4289 p1 = repo.lookup('.')
4283 4290 p2 = repo.lookup(node)
4284 4291 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4285 4292
4286 4293 displayer = cmdutil.show_changeset(ui, repo, opts)
4287 4294 for node in nodes:
4288 4295 displayer.show(repo[node])
4289 4296 displayer.close()
4290 4297 return 0
4291 4298
4292 4299 try:
4293 4300 # ui.forcemerge is an internal variable, do not document
4294 4301 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4295 4302 return hg.merge(repo, node, force=opts.get('force'))
4296 4303 finally:
4297 4304 ui.setconfig('ui', 'forcemerge', '')
4298 4305
4299 4306 @command('outgoing|out',
4300 4307 [('f', 'force', None, _('run even when the destination is unrelated')),
4301 4308 ('r', 'rev', [],
4302 4309 _('a changeset intended to be included in the destination'), _('REV')),
4303 4310 ('n', 'newest-first', None, _('show newest record first')),
4304 4311 ('B', 'bookmarks', False, _('compare bookmarks')),
4305 4312 ('b', 'branch', [], _('a specific branch you would like to push'),
4306 4313 _('BRANCH')),
4307 4314 ] + logopts + remoteopts + subrepoopts,
4308 4315 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4309 4316 def outgoing(ui, repo, dest=None, **opts):
4310 4317 """show changesets not found in the destination
4311 4318
4312 4319 Show changesets not found in the specified destination repository
4313 4320 or the default push location. These are the changesets that would
4314 4321 be pushed if a push was requested.
4315 4322
4316 4323 See pull for details of valid destination formats.
4317 4324
4318 4325 Returns 0 if there are outgoing changes, 1 otherwise.
4319 4326 """
4320 4327 if opts.get('graph'):
4321 4328 cmdutil.checkunsupportedgraphflags([], opts)
4322 4329 o = hg._outgoing(ui, repo, dest, opts)
4323 4330 if o is None:
4324 4331 return
4325 4332
4326 4333 revdag = cmdutil.graphrevs(repo, o, opts)
4327 4334 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4328 4335 showparents = [ctx.node() for ctx in repo[None].parents()]
4329 4336 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4330 4337 graphmod.asciiedges)
4331 4338 return 0
4332 4339
4333 4340 if opts.get('bookmarks'):
4334 4341 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4335 4342 dest, branches = hg.parseurl(dest, opts.get('branch'))
4336 4343 other = hg.peer(repo, opts, dest)
4337 4344 if 'bookmarks' not in other.listkeys('namespaces'):
4338 4345 ui.warn(_("remote doesn't support bookmarks\n"))
4339 4346 return 0
4340 4347 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4341 4348 return bookmarks.diff(ui, other, repo)
4342 4349
4343 4350 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4344 4351 try:
4345 4352 return hg.outgoing(ui, repo, dest, opts)
4346 4353 finally:
4347 4354 del repo._subtoppath
4348 4355
4349 4356 @command('parents',
4350 4357 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4351 4358 ] + templateopts,
4352 4359 _('[-r REV] [FILE]'))
4353 4360 def parents(ui, repo, file_=None, **opts):
4354 4361 """show the parents of the working directory or revision
4355 4362
4356 4363 Print the working directory's parent revisions. If a revision is
4357 4364 given via -r/--rev, the parent of that revision will be printed.
4358 4365 If a file argument is given, the revision in which the file was
4359 4366 last changed (before the working directory revision or the
4360 4367 argument to --rev if given) is printed.
4361 4368
4362 4369 Returns 0 on success.
4363 4370 """
4364 4371
4365 4372 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4366 4373
4367 4374 if file_:
4368 4375 m = scmutil.match(ctx, (file_,), opts)
4369 4376 if m.anypats() or len(m.files()) != 1:
4370 4377 raise util.Abort(_('can only specify an explicit filename'))
4371 4378 file_ = m.files()[0]
4372 4379 filenodes = []
4373 4380 for cp in ctx.parents():
4374 4381 if not cp:
4375 4382 continue
4376 4383 try:
4377 4384 filenodes.append(cp.filenode(file_))
4378 4385 except error.LookupError:
4379 4386 pass
4380 4387 if not filenodes:
4381 4388 raise util.Abort(_("'%s' not found in manifest!") % file_)
4382 4389 p = []
4383 4390 for fn in filenodes:
4384 4391 fctx = repo.filectx(file_, fileid=fn)
4385 4392 p.append(fctx.node())
4386 4393 else:
4387 4394 p = [cp.node() for cp in ctx.parents()]
4388 4395
4389 4396 displayer = cmdutil.show_changeset(ui, repo, opts)
4390 4397 for n in p:
4391 4398 if n != nullid:
4392 4399 displayer.show(repo[n])
4393 4400 displayer.close()
4394 4401
4395 4402 @command('paths', [], _('[NAME]'))
4396 4403 def paths(ui, repo, search=None):
4397 4404 """show aliases for remote repositories
4398 4405
4399 4406 Show definition of symbolic path name NAME. If no name is given,
4400 4407 show definition of all available names.
4401 4408
4402 4409 Option -q/--quiet suppresses all output when searching for NAME
4403 4410 and shows only the path names when listing all definitions.
4404 4411
4405 4412 Path names are defined in the [paths] section of your
4406 4413 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4407 4414 repository, ``.hg/hgrc`` is used, too.
4408 4415
4409 4416 The path names ``default`` and ``default-push`` have a special
4410 4417 meaning. When performing a push or pull operation, they are used
4411 4418 as fallbacks if no location is specified on the command-line.
4412 4419 When ``default-push`` is set, it will be used for push and
4413 4420 ``default`` will be used for pull; otherwise ``default`` is used
4414 4421 as the fallback for both. When cloning a repository, the clone
4415 4422 source is written as ``default`` in ``.hg/hgrc``. Note that
4416 4423 ``default`` and ``default-push`` apply to all inbound (e.g.
4417 4424 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4418 4425 :hg:`bundle`) operations.
4419 4426
4420 4427 See :hg:`help urls` for more information.
4421 4428
4422 4429 Returns 0 on success.
4423 4430 """
4424 4431 if search:
4425 4432 for name, path in ui.configitems("paths"):
4426 4433 if name == search:
4427 4434 ui.status("%s\n" % util.hidepassword(path))
4428 4435 return
4429 4436 if not ui.quiet:
4430 4437 ui.warn(_("not found!\n"))
4431 4438 return 1
4432 4439 else:
4433 4440 for name, path in ui.configitems("paths"):
4434 4441 if ui.quiet:
4435 4442 ui.write("%s\n" % name)
4436 4443 else:
4437 4444 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4438 4445
4439 4446 @command('phase',
4440 4447 [('p', 'public', False, _('set changeset phase to public')),
4441 4448 ('d', 'draft', False, _('set changeset phase to draft')),
4442 4449 ('s', 'secret', False, _('set changeset phase to secret')),
4443 4450 ('f', 'force', False, _('allow to move boundary backward')),
4444 4451 ('r', 'rev', [], _('target revision'), _('REV')),
4445 4452 ],
4446 4453 _('[-p|-d|-s] [-f] [-r] REV...'))
4447 4454 def phase(ui, repo, *revs, **opts):
4448 4455 """set or show the current phase name
4449 4456
4450 4457 With no argument, show the phase name of specified revisions.
4451 4458
4452 4459 With one of -p/--public, -d/--draft or -s/--secret, change the
4453 4460 phase value of the specified revisions.
4454 4461
4455 4462 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4456 4463 lower phase to an higher phase. Phases are ordered as follows::
4457 4464
4458 4465 public < draft < secret
4459 4466
4460 4467 Return 0 on success, 1 if no phases were changed or some could not
4461 4468 be changed.
4462 4469 """
4463 4470 # search for a unique phase argument
4464 4471 targetphase = None
4465 4472 for idx, name in enumerate(phases.phasenames):
4466 4473 if opts[name]:
4467 4474 if targetphase is not None:
4468 4475 raise util.Abort(_('only one phase can be specified'))
4469 4476 targetphase = idx
4470 4477
4471 4478 # look for specified revision
4472 4479 revs = list(revs)
4473 4480 revs.extend(opts['rev'])
4474 4481 if not revs:
4475 4482 raise util.Abort(_('no revisions specified'))
4476 4483
4477 4484 revs = scmutil.revrange(repo, revs)
4478 4485
4479 4486 lock = None
4480 4487 ret = 0
4481 4488 if targetphase is None:
4482 4489 # display
4483 4490 for r in revs:
4484 4491 ctx = repo[r]
4485 4492 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4486 4493 else:
4487 4494 lock = repo.lock()
4488 4495 try:
4489 4496 # set phase
4490 4497 if not revs:
4491 4498 raise util.Abort(_('empty revision set'))
4492 4499 nodes = [repo[r].node() for r in revs]
4493 4500 olddata = repo._phasecache.getphaserevs(repo)[:]
4494 4501 phases.advanceboundary(repo, targetphase, nodes)
4495 4502 if opts['force']:
4496 4503 phases.retractboundary(repo, targetphase, nodes)
4497 4504 finally:
4498 4505 lock.release()
4499 4506 # moving revision from public to draft may hide them
4500 4507 # We have to check result on an unfiltered repository
4501 4508 unfi = repo.unfiltered()
4502 4509 newdata = repo._phasecache.getphaserevs(unfi)
4503 4510 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4504 4511 cl = unfi.changelog
4505 4512 rejected = [n for n in nodes
4506 4513 if newdata[cl.rev(n)] < targetphase]
4507 4514 if rejected:
4508 4515 ui.warn(_('cannot move %i changesets to a more permissive '
4509 4516 'phase, use --force\n') % len(rejected))
4510 4517 ret = 1
4511 4518 if changes:
4512 4519 msg = _('phase changed for %i changesets\n') % changes
4513 4520 if ret:
4514 4521 ui.status(msg)
4515 4522 else:
4516 4523 ui.note(msg)
4517 4524 else:
4518 4525 ui.warn(_('no phases changed\n'))
4519 4526 ret = 1
4520 4527 return ret
4521 4528
4522 4529 def postincoming(ui, repo, modheads, optupdate, checkout):
4523 4530 if modheads == 0:
4524 4531 return
4525 4532 if optupdate:
4526 4533 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
4527 4534 try:
4528 4535 ret = hg.update(repo, checkout)
4529 4536 except util.Abort, inst:
4530 4537 ui.warn(_("not updating: %s\n") % str(inst))
4531 4538 if inst.hint:
4532 4539 ui.warn(_("(%s)\n") % inst.hint)
4533 4540 return 0
4534 4541 if not ret and not checkout:
4535 4542 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4536 4543 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4537 4544 return ret
4538 4545 if modheads > 1:
4539 4546 currentbranchheads = len(repo.branchheads())
4540 4547 if currentbranchheads == modheads:
4541 4548 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4542 4549 elif currentbranchheads > 1:
4543 4550 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4544 4551 "merge)\n"))
4545 4552 else:
4546 4553 ui.status(_("(run 'hg heads' to see heads)\n"))
4547 4554 else:
4548 4555 ui.status(_("(run 'hg update' to get a working copy)\n"))
4549 4556
4550 4557 @command('^pull',
4551 4558 [('u', 'update', None,
4552 4559 _('update to new branch head if changesets were pulled')),
4553 4560 ('f', 'force', None, _('run even when remote repository is unrelated')),
4554 4561 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4555 4562 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4556 4563 ('b', 'branch', [], _('a specific branch you would like to pull'),
4557 4564 _('BRANCH')),
4558 4565 ] + remoteopts,
4559 4566 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4560 4567 def pull(ui, repo, source="default", **opts):
4561 4568 """pull changes from the specified source
4562 4569
4563 4570 Pull changes from a remote repository to a local one.
4564 4571
4565 4572 This finds all changes from the repository at the specified path
4566 4573 or URL and adds them to a local repository (the current one unless
4567 4574 -R is specified). By default, this does not update the copy of the
4568 4575 project in the working directory.
4569 4576
4570 4577 Use :hg:`incoming` if you want to see what would have been added
4571 4578 by a pull at the time you issued this command. If you then decide
4572 4579 to add those changes to the repository, you should use :hg:`pull
4573 4580 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4574 4581
4575 4582 If SOURCE is omitted, the 'default' path will be used.
4576 4583 See :hg:`help urls` for more information.
4577 4584
4578 4585 Returns 0 on success, 1 if an update had unresolved files.
4579 4586 """
4580 4587 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4581 4588 other = hg.peer(repo, opts, source)
4582 4589 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4583 4590 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4584 4591
4585 4592 remotebookmarks = other.listkeys('bookmarks')
4586 4593
4587 4594 if opts.get('bookmark'):
4588 4595 if not revs:
4589 4596 revs = []
4590 4597 for b in opts['bookmark']:
4591 4598 if b not in remotebookmarks:
4592 4599 raise util.Abort(_('remote bookmark %s not found!') % b)
4593 4600 revs.append(remotebookmarks[b])
4594 4601
4595 4602 if revs:
4596 4603 try:
4597 4604 revs = [other.lookup(rev) for rev in revs]
4598 4605 except error.CapabilityError:
4599 4606 err = _("other repository doesn't support revision lookup, "
4600 4607 "so a rev cannot be specified.")
4601 4608 raise util.Abort(err)
4602 4609
4603 4610 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4604 4611 bookmarks.updatefromremote(ui, repo, remotebookmarks, source)
4605 4612 if checkout:
4606 4613 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4607 4614 repo._subtoppath = source
4608 4615 try:
4609 4616 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4610 4617
4611 4618 finally:
4612 4619 del repo._subtoppath
4613 4620
4614 4621 # update specified bookmarks
4615 4622 if opts.get('bookmark'):
4616 4623 marks = repo._bookmarks
4617 4624 for b in opts['bookmark']:
4618 4625 # explicit pull overrides local bookmark if any
4619 4626 ui.status(_("importing bookmark %s\n") % b)
4620 4627 marks[b] = repo[remotebookmarks[b]].node()
4621 4628 marks.write()
4622 4629
4623 4630 return ret
4624 4631
4625 4632 @command('^push',
4626 4633 [('f', 'force', None, _('force push')),
4627 4634 ('r', 'rev', [],
4628 4635 _('a changeset intended to be included in the destination'),
4629 4636 _('REV')),
4630 4637 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4631 4638 ('b', 'branch', [],
4632 4639 _('a specific branch you would like to push'), _('BRANCH')),
4633 4640 ('', 'new-branch', False, _('allow pushing a new branch')),
4634 4641 ] + remoteopts,
4635 4642 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4636 4643 def push(ui, repo, dest=None, **opts):
4637 4644 """push changes to the specified destination
4638 4645
4639 4646 Push changesets from the local repository to the specified
4640 4647 destination.
4641 4648
4642 4649 This operation is symmetrical to pull: it is identical to a pull
4643 4650 in the destination repository from the current one.
4644 4651
4645 4652 By default, push will not allow creation of new heads at the
4646 4653 destination, since multiple heads would make it unclear which head
4647 4654 to use. In this situation, it is recommended to pull and merge
4648 4655 before pushing.
4649 4656
4650 4657 Use --new-branch if you want to allow push to create a new named
4651 4658 branch that is not present at the destination. This allows you to
4652 4659 only create a new branch without forcing other changes.
4653 4660
4654 4661 .. note::
4662
4655 4663 Extra care should be taken with the -f/--force option,
4656 4664 which will push all new heads on all branches, an action which will
4657 4665 almost always cause confusion for collaborators.
4658 4666
4659 4667 If -r/--rev is used, the specified revision and all its ancestors
4660 4668 will be pushed to the remote repository.
4661 4669
4662 4670 If -B/--bookmark is used, the specified bookmarked revision, its
4663 4671 ancestors, and the bookmark will be pushed to the remote
4664 4672 repository.
4665 4673
4666 4674 Please see :hg:`help urls` for important details about ``ssh://``
4667 4675 URLs. If DESTINATION is omitted, a default path will be used.
4668 4676
4669 4677 Returns 0 if push was successful, 1 if nothing to push.
4670 4678 """
4671 4679
4672 4680 if opts.get('bookmark'):
4673 4681 for b in opts['bookmark']:
4674 4682 # translate -B options to -r so changesets get pushed
4675 4683 if b in repo._bookmarks:
4676 4684 opts.setdefault('rev', []).append(b)
4677 4685 else:
4678 4686 # if we try to push a deleted bookmark, translate it to null
4679 4687 # this lets simultaneous -r, -b options continue working
4680 4688 opts.setdefault('rev', []).append("null")
4681 4689
4682 4690 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4683 4691 dest, branches = hg.parseurl(dest, opts.get('branch'))
4684 4692 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4685 4693 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4686 4694 other = hg.peer(repo, opts, dest)
4687 4695 if revs:
4688 4696 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4689 4697
4690 4698 repo._subtoppath = dest
4691 4699 try:
4692 4700 # push subrepos depth-first for coherent ordering
4693 4701 c = repo['']
4694 4702 subs = c.substate # only repos that are committed
4695 4703 for s in sorted(subs):
4696 4704 if c.sub(s).push(opts) == 0:
4697 4705 return False
4698 4706 finally:
4699 4707 del repo._subtoppath
4700 4708 result = repo.push(other, opts.get('force'), revs=revs,
4701 4709 newbranch=opts.get('new_branch'))
4702 4710
4703 4711 result = not result
4704 4712
4705 4713 if opts.get('bookmark'):
4706 4714 rb = other.listkeys('bookmarks')
4707 4715 for b in opts['bookmark']:
4708 4716 # explicit push overrides remote bookmark if any
4709 4717 if b in repo._bookmarks:
4710 4718 ui.status(_("exporting bookmark %s\n") % b)
4711 4719 new = repo[b].hex()
4712 4720 elif b in rb:
4713 4721 ui.status(_("deleting remote bookmark %s\n") % b)
4714 4722 new = '' # delete
4715 4723 else:
4716 4724 ui.warn(_('bookmark %s does not exist on the local '
4717 4725 'or remote repository!\n') % b)
4718 4726 return 2
4719 4727 old = rb.get(b, '')
4720 4728 r = other.pushkey('bookmarks', b, old, new)
4721 4729 if not r:
4722 4730 ui.warn(_('updating bookmark %s failed!\n') % b)
4723 4731 if not result:
4724 4732 result = 2
4725 4733
4726 4734 return result
4727 4735
4728 4736 @command('recover', [])
4729 4737 def recover(ui, repo):
4730 4738 """roll back an interrupted transaction
4731 4739
4732 4740 Recover from an interrupted commit or pull.
4733 4741
4734 4742 This command tries to fix the repository status after an
4735 4743 interrupted operation. It should only be necessary when Mercurial
4736 4744 suggests it.
4737 4745
4738 4746 Returns 0 if successful, 1 if nothing to recover or verify fails.
4739 4747 """
4740 4748 if repo.recover():
4741 4749 return hg.verify(repo)
4742 4750 return 1
4743 4751
4744 4752 @command('^remove|rm',
4745 4753 [('A', 'after', None, _('record delete for missing files')),
4746 4754 ('f', 'force', None,
4747 4755 _('remove (and delete) file even if added or modified')),
4748 4756 ] + walkopts,
4749 4757 _('[OPTION]... FILE...'))
4750 4758 def remove(ui, repo, *pats, **opts):
4751 4759 """remove the specified files on the next commit
4752 4760
4753 4761 Schedule the indicated files for removal from the current branch.
4754 4762
4755 4763 This command schedules the files to be removed at the next commit.
4756 4764 To undo a remove before that, see :hg:`revert`. To undo added
4757 4765 files, see :hg:`forget`.
4758 4766
4759 4767 .. container:: verbose
4760 4768
4761 4769 -A/--after can be used to remove only files that have already
4762 4770 been deleted, -f/--force can be used to force deletion, and -Af
4763 4771 can be used to remove files from the next revision without
4764 4772 deleting them from the working directory.
4765 4773
4766 4774 The following table details the behavior of remove for different
4767 4775 file states (columns) and option combinations (rows). The file
4768 4776 states are Added [A], Clean [C], Modified [M] and Missing [!]
4769 4777 (as reported by :hg:`status`). The actions are Warn, Remove
4770 4778 (from branch) and Delete (from disk):
4771 4779
4772 4780 ========= == == == ==
4773 4781 opt/state A C M !
4774 4782 ========= == == == ==
4775 4783 none W RD W R
4776 4784 -f R RD RD R
4777 4785 -A W W W R
4778 4786 -Af R R R R
4779 4787 ========= == == == ==
4780 4788
4781 4789 Note that remove never deletes files in Added [A] state from the
4782 4790 working directory, not even if option --force is specified.
4783 4791
4784 4792 Returns 0 on success, 1 if any warnings encountered.
4785 4793 """
4786 4794
4787 4795 ret = 0
4788 4796 after, force = opts.get('after'), opts.get('force')
4789 4797 if not pats and not after:
4790 4798 raise util.Abort(_('no files specified'))
4791 4799
4792 4800 m = scmutil.match(repo[None], pats, opts)
4793 4801 s = repo.status(match=m, clean=True)
4794 4802 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4795 4803
4796 4804 # warn about failure to delete explicit files/dirs
4797 4805 wctx = repo[None]
4798 4806 for f in m.files():
4799 4807 if f in repo.dirstate or f in wctx.dirs():
4800 4808 continue
4801 4809 if os.path.exists(m.rel(f)):
4802 4810 if os.path.isdir(m.rel(f)):
4803 4811 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4804 4812 else:
4805 4813 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4806 4814 # missing files will generate a warning elsewhere
4807 4815 ret = 1
4808 4816
4809 4817 if force:
4810 4818 list = modified + deleted + clean + added
4811 4819 elif after:
4812 4820 list = deleted
4813 4821 for f in modified + added + clean:
4814 4822 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
4815 4823 ret = 1
4816 4824 else:
4817 4825 list = deleted + clean
4818 4826 for f in modified:
4819 4827 ui.warn(_('not removing %s: file is modified (use -f'
4820 4828 ' to force removal)\n') % m.rel(f))
4821 4829 ret = 1
4822 4830 for f in added:
4823 4831 ui.warn(_('not removing %s: file has been marked for add'
4824 4832 ' (use forget to undo)\n') % m.rel(f))
4825 4833 ret = 1
4826 4834
4827 4835 for f in sorted(list):
4828 4836 if ui.verbose or not m.exact(f):
4829 4837 ui.status(_('removing %s\n') % m.rel(f))
4830 4838
4831 4839 wlock = repo.wlock()
4832 4840 try:
4833 4841 if not after:
4834 4842 for f in list:
4835 4843 if f in added:
4836 4844 continue # we never unlink added files on remove
4837 4845 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
4838 4846 repo[None].forget(list)
4839 4847 finally:
4840 4848 wlock.release()
4841 4849
4842 4850 return ret
4843 4851
4844 4852 @command('rename|move|mv',
4845 4853 [('A', 'after', None, _('record a rename that has already occurred')),
4846 4854 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4847 4855 ] + walkopts + dryrunopts,
4848 4856 _('[OPTION]... SOURCE... DEST'))
4849 4857 def rename(ui, repo, *pats, **opts):
4850 4858 """rename files; equivalent of copy + remove
4851 4859
4852 4860 Mark dest as copies of sources; mark sources for deletion. If dest
4853 4861 is a directory, copies are put in that directory. If dest is a
4854 4862 file, there can only be one source.
4855 4863
4856 4864 By default, this command copies the contents of files as they
4857 4865 exist in the working directory. If invoked with -A/--after, the
4858 4866 operation is recorded, but no copying is performed.
4859 4867
4860 4868 This command takes effect at the next commit. To undo a rename
4861 4869 before that, see :hg:`revert`.
4862 4870
4863 4871 Returns 0 on success, 1 if errors are encountered.
4864 4872 """
4865 4873 wlock = repo.wlock(False)
4866 4874 try:
4867 4875 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4868 4876 finally:
4869 4877 wlock.release()
4870 4878
4871 4879 @command('resolve',
4872 4880 [('a', 'all', None, _('select all unresolved files')),
4873 4881 ('l', 'list', None, _('list state of files needing merge')),
4874 4882 ('m', 'mark', None, _('mark files as resolved')),
4875 4883 ('u', 'unmark', None, _('mark files as unresolved')),
4876 4884 ('n', 'no-status', None, _('hide status prefix'))]
4877 4885 + mergetoolopts + walkopts,
4878 4886 _('[OPTION]... [FILE]...'))
4879 4887 def resolve(ui, repo, *pats, **opts):
4880 4888 """redo merges or set/view the merge status of files
4881 4889
4882 4890 Merges with unresolved conflicts are often the result of
4883 4891 non-interactive merging using the ``internal:merge`` configuration
4884 4892 setting, or a command-line merge tool like ``diff3``. The resolve
4885 4893 command is used to manage the files involved in a merge, after
4886 4894 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4887 4895 working directory must have two parents). See :hg:`help
4888 4896 merge-tools` for information on configuring merge tools.
4889 4897
4890 4898 The resolve command can be used in the following ways:
4891 4899
4892 4900 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4893 4901 files, discarding any previous merge attempts. Re-merging is not
4894 4902 performed for files already marked as resolved. Use ``--all/-a``
4895 4903 to select all unresolved files. ``--tool`` can be used to specify
4896 4904 the merge tool used for the given files. It overrides the HGMERGE
4897 4905 environment variable and your configuration files. Previous file
4898 4906 contents are saved with a ``.orig`` suffix.
4899 4907
4900 4908 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4901 4909 (e.g. after having manually fixed-up the files). The default is
4902 4910 to mark all unresolved files.
4903 4911
4904 4912 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4905 4913 default is to mark all resolved files.
4906 4914
4907 4915 - :hg:`resolve -l`: list files which had or still have conflicts.
4908 4916 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4909 4917
4910 4918 Note that Mercurial will not let you commit files with unresolved
4911 4919 merge conflicts. You must use :hg:`resolve -m ...` before you can
4912 4920 commit after a conflicting merge.
4913 4921
4914 4922 Returns 0 on success, 1 if any files fail a resolve attempt.
4915 4923 """
4916 4924
4917 4925 all, mark, unmark, show, nostatus = \
4918 4926 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4919 4927
4920 4928 if (show and (mark or unmark)) or (mark and unmark):
4921 4929 raise util.Abort(_("too many options specified"))
4922 4930 if pats and all:
4923 4931 raise util.Abort(_("can't specify --all and patterns"))
4924 4932 if not (all or pats or show or mark or unmark):
4925 4933 raise util.Abort(_('no files or directories specified; '
4926 4934 'use --all to remerge all files'))
4927 4935
4928 4936 ms = mergemod.mergestate(repo)
4929 4937 m = scmutil.match(repo[None], pats, opts)
4930 4938 ret = 0
4931 4939
4932 4940 for f in ms:
4933 4941 if m(f):
4934 4942 if show:
4935 4943 if nostatus:
4936 4944 ui.write("%s\n" % f)
4937 4945 else:
4938 4946 ui.write("%s %s\n" % (ms[f].upper(), f),
4939 4947 label='resolve.' +
4940 4948 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4941 4949 elif mark:
4942 4950 ms.mark(f, "r")
4943 4951 elif unmark:
4944 4952 ms.mark(f, "u")
4945 4953 else:
4946 4954 wctx = repo[None]
4947 4955 mctx = wctx.parents()[-1]
4948 4956
4949 4957 # backup pre-resolve (merge uses .orig for its own purposes)
4950 4958 a = repo.wjoin(f)
4951 4959 util.copyfile(a, a + ".resolve")
4952 4960
4953 4961 try:
4954 4962 # resolve file
4955 4963 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4956 4964 if ms.resolve(f, wctx, mctx):
4957 4965 ret = 1
4958 4966 finally:
4959 4967 ui.setconfig('ui', 'forcemerge', '')
4960 4968 ms.commit()
4961 4969
4962 4970 # replace filemerge's .orig file with our resolve file
4963 4971 util.rename(a + ".resolve", a + ".orig")
4964 4972
4965 4973 ms.commit()
4966 4974 return ret
4967 4975
4968 4976 @command('revert',
4969 4977 [('a', 'all', None, _('revert all changes when no arguments given')),
4970 4978 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4971 4979 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4972 4980 ('C', 'no-backup', None, _('do not save backup copies of files')),
4973 4981 ] + walkopts + dryrunopts,
4974 4982 _('[OPTION]... [-r REV] [NAME]...'))
4975 4983 def revert(ui, repo, *pats, **opts):
4976 4984 """restore files to their checkout state
4977 4985
4978 4986 .. note::
4987
4979 4988 To check out earlier revisions, you should use :hg:`update REV`.
4980 4989 To cancel an uncommitted merge (and lose your changes),
4981 4990 use :hg:`update --clean .`.
4982 4991
4983 4992 With no revision specified, revert the specified files or directories
4984 4993 to the contents they had in the parent of the working directory.
4985 4994 This restores the contents of files to an unmodified
4986 4995 state and unschedules adds, removes, copies, and renames. If the
4987 4996 working directory has two parents, you must explicitly specify a
4988 4997 revision.
4989 4998
4990 4999 Using the -r/--rev or -d/--date options, revert the given files or
4991 5000 directories to their states as of a specific revision. Because
4992 5001 revert does not change the working directory parents, this will
4993 5002 cause these files to appear modified. This can be helpful to "back
4994 5003 out" some or all of an earlier change. See :hg:`backout` for a
4995 5004 related method.
4996 5005
4997 5006 Modified files are saved with a .orig suffix before reverting.
4998 5007 To disable these backups, use --no-backup.
4999 5008
5000 5009 See :hg:`help dates` for a list of formats valid for -d/--date.
5001 5010
5002 5011 Returns 0 on success.
5003 5012 """
5004 5013
5005 5014 if opts.get("date"):
5006 5015 if opts.get("rev"):
5007 5016 raise util.Abort(_("you can't specify a revision and a date"))
5008 5017 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5009 5018
5010 5019 parent, p2 = repo.dirstate.parents()
5011 5020 if not opts.get('rev') and p2 != nullid:
5012 5021 # revert after merge is a trap for new users (issue2915)
5013 5022 raise util.Abort(_('uncommitted merge with no revision specified'),
5014 5023 hint=_('use "hg update" or see "hg help revert"'))
5015 5024
5016 5025 ctx = scmutil.revsingle(repo, opts.get('rev'))
5017 5026
5018 5027 if not pats and not opts.get('all'):
5019 5028 msg = _("no files or directories specified")
5020 5029 if p2 != nullid:
5021 5030 hint = _("uncommitted merge, use --all to discard all changes,"
5022 5031 " or 'hg update -C .' to abort the merge")
5023 5032 raise util.Abort(msg, hint=hint)
5024 5033 dirty = util.any(repo.status())
5025 5034 node = ctx.node()
5026 5035 if node != parent:
5027 5036 if dirty:
5028 5037 hint = _("uncommitted changes, use --all to discard all"
5029 5038 " changes, or 'hg update %s' to update") % ctx.rev()
5030 5039 else:
5031 5040 hint = _("use --all to revert all files,"
5032 5041 " or 'hg update %s' to update") % ctx.rev()
5033 5042 elif dirty:
5034 5043 hint = _("uncommitted changes, use --all to discard all changes")
5035 5044 else:
5036 5045 hint = _("use --all to revert all files")
5037 5046 raise util.Abort(msg, hint=hint)
5038 5047
5039 5048 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5040 5049
5041 5050 @command('rollback', dryrunopts +
5042 5051 [('f', 'force', False, _('ignore safety measures'))])
5043 5052 def rollback(ui, repo, **opts):
5044 5053 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5045 5054
5046 5055 Please use :hg:`commit --amend` instead of rollback to correct
5047 5056 mistakes in the last commit.
5048 5057
5049 5058 This command should be used with care. There is only one level of
5050 5059 rollback, and there is no way to undo a rollback. It will also
5051 5060 restore the dirstate at the time of the last transaction, losing
5052 5061 any dirstate changes since that time. This command does not alter
5053 5062 the working directory.
5054 5063
5055 5064 Transactions are used to encapsulate the effects of all commands
5056 5065 that create new changesets or propagate existing changesets into a
5057 5066 repository.
5058 5067
5059 5068 .. container:: verbose
5060 5069
5061 5070 For example, the following commands are transactional, and their
5062 5071 effects can be rolled back:
5063 5072
5064 5073 - commit
5065 5074 - import
5066 5075 - pull
5067 5076 - push (with this repository as the destination)
5068 5077 - unbundle
5069 5078
5070 5079 To avoid permanent data loss, rollback will refuse to rollback a
5071 5080 commit transaction if it isn't checked out. Use --force to
5072 5081 override this protection.
5073 5082
5074 5083 This command is not intended for use on public repositories. Once
5075 5084 changes are visible for pull by other users, rolling a transaction
5076 5085 back locally is ineffective (someone else may already have pulled
5077 5086 the changes). Furthermore, a race is possible with readers of the
5078 5087 repository; for example an in-progress pull from the repository
5079 5088 may fail if a rollback is performed.
5080 5089
5081 5090 Returns 0 on success, 1 if no rollback data is available.
5082 5091 """
5083 5092 return repo.rollback(dryrun=opts.get('dry_run'),
5084 5093 force=opts.get('force'))
5085 5094
5086 5095 @command('root', [])
5087 5096 def root(ui, repo):
5088 5097 """print the root (top) of the current working directory
5089 5098
5090 5099 Print the root directory of the current repository.
5091 5100
5092 5101 Returns 0 on success.
5093 5102 """
5094 5103 ui.write(repo.root + "\n")
5095 5104
5096 5105 @command('^serve',
5097 5106 [('A', 'accesslog', '', _('name of access log file to write to'),
5098 5107 _('FILE')),
5099 5108 ('d', 'daemon', None, _('run server in background')),
5100 5109 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5101 5110 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5102 5111 # use string type, then we can check if something was passed
5103 5112 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5104 5113 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5105 5114 _('ADDR')),
5106 5115 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5107 5116 _('PREFIX')),
5108 5117 ('n', 'name', '',
5109 5118 _('name to show in web pages (default: working directory)'), _('NAME')),
5110 5119 ('', 'web-conf', '',
5111 5120 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5112 5121 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5113 5122 _('FILE')),
5114 5123 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5115 5124 ('', 'stdio', None, _('for remote clients')),
5116 5125 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5117 5126 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5118 5127 ('', 'style', '', _('template style to use'), _('STYLE')),
5119 5128 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5120 5129 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5121 5130 _('[OPTION]...'))
5122 5131 def serve(ui, repo, **opts):
5123 5132 """start stand-alone webserver
5124 5133
5125 5134 Start a local HTTP repository browser and pull server. You can use
5126 5135 this for ad-hoc sharing and browsing of repositories. It is
5127 5136 recommended to use a real web server to serve a repository for
5128 5137 longer periods of time.
5129 5138
5130 5139 Please note that the server does not implement access control.
5131 5140 This means that, by default, anybody can read from the server and
5132 5141 nobody can write to it by default. Set the ``web.allow_push``
5133 5142 option to ``*`` to allow everybody to push to the server. You
5134 5143 should use a real web server if you need to authenticate users.
5135 5144
5136 5145 By default, the server logs accesses to stdout and errors to
5137 5146 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5138 5147 files.
5139 5148
5140 5149 To have the server choose a free port number to listen on, specify
5141 5150 a port number of 0; in this case, the server will print the port
5142 5151 number it uses.
5143 5152
5144 5153 Returns 0 on success.
5145 5154 """
5146 5155
5147 5156 if opts["stdio"] and opts["cmdserver"]:
5148 5157 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5149 5158
5150 5159 def checkrepo():
5151 5160 if repo is None:
5152 5161 raise error.RepoError(_("there is no Mercurial repository here"
5153 5162 " (.hg not found)"))
5154 5163
5155 5164 if opts["stdio"]:
5156 5165 checkrepo()
5157 5166 s = sshserver.sshserver(ui, repo)
5158 5167 s.serve_forever()
5159 5168
5160 5169 if opts["cmdserver"]:
5161 5170 checkrepo()
5162 5171 s = commandserver.server(ui, repo, opts["cmdserver"])
5163 5172 return s.serve()
5164 5173
5165 5174 # this way we can check if something was given in the command-line
5166 5175 if opts.get('port'):
5167 5176 opts['port'] = util.getport(opts.get('port'))
5168 5177
5169 5178 baseui = repo and repo.baseui or ui
5170 5179 optlist = ("name templates style address port prefix ipv6"
5171 5180 " accesslog errorlog certificate encoding")
5172 5181 for o in optlist.split():
5173 5182 val = opts.get(o, '')
5174 5183 if val in (None, ''): # should check against default options instead
5175 5184 continue
5176 5185 baseui.setconfig("web", o, val)
5177 5186 if repo and repo.ui != baseui:
5178 5187 repo.ui.setconfig("web", o, val)
5179 5188
5180 5189 o = opts.get('web_conf') or opts.get('webdir_conf')
5181 5190 if not o:
5182 5191 if not repo:
5183 5192 raise error.RepoError(_("there is no Mercurial repository"
5184 5193 " here (.hg not found)"))
5185 5194 o = repo
5186 5195
5187 5196 app = hgweb.hgweb(o, baseui=baseui)
5188 5197 service = httpservice(ui, app, opts)
5189 5198 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5190 5199
5191 5200 class httpservice(object):
5192 5201 def __init__(self, ui, app, opts):
5193 5202 self.ui = ui
5194 5203 self.app = app
5195 5204 self.opts = opts
5196 5205
5197 5206 def init(self):
5198 5207 util.setsignalhandler()
5199 5208 self.httpd = hgweb_server.create_server(self.ui, self.app)
5200 5209
5201 5210 if self.opts['port'] and not self.ui.verbose:
5202 5211 return
5203 5212
5204 5213 if self.httpd.prefix:
5205 5214 prefix = self.httpd.prefix.strip('/') + '/'
5206 5215 else:
5207 5216 prefix = ''
5208 5217
5209 5218 port = ':%d' % self.httpd.port
5210 5219 if port == ':80':
5211 5220 port = ''
5212 5221
5213 5222 bindaddr = self.httpd.addr
5214 5223 if bindaddr == '0.0.0.0':
5215 5224 bindaddr = '*'
5216 5225 elif ':' in bindaddr: # IPv6
5217 5226 bindaddr = '[%s]' % bindaddr
5218 5227
5219 5228 fqaddr = self.httpd.fqaddr
5220 5229 if ':' in fqaddr:
5221 5230 fqaddr = '[%s]' % fqaddr
5222 5231 if self.opts['port']:
5223 5232 write = self.ui.status
5224 5233 else:
5225 5234 write = self.ui.write
5226 5235 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5227 5236 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5228 5237
5229 5238 def run(self):
5230 5239 self.httpd.serve_forever()
5231 5240
5232 5241
5233 5242 @command('showconfig|debugconfig',
5234 5243 [('u', 'untrusted', None, _('show untrusted configuration options'))],
5235 5244 _('[-u] [NAME]...'))
5236 5245 def showconfig(ui, repo, *values, **opts):
5237 5246 """show combined config settings from all hgrc files
5238 5247
5239 5248 With no arguments, print names and values of all config items.
5240 5249
5241 5250 With one argument of the form section.name, print just the value
5242 5251 of that config item.
5243 5252
5244 5253 With multiple arguments, print names and values of all config
5245 5254 items with matching section names.
5246 5255
5247 5256 With --debug, the source (filename and line number) is printed
5248 5257 for each config item.
5249 5258
5250 5259 Returns 0 on success.
5251 5260 """
5252 5261
5253 5262 for f in scmutil.rcpath():
5254 5263 ui.debug('read config from: %s\n' % f)
5255 5264 untrusted = bool(opts.get('untrusted'))
5256 5265 if values:
5257 5266 sections = [v for v in values if '.' not in v]
5258 5267 items = [v for v in values if '.' in v]
5259 5268 if len(items) > 1 or items and sections:
5260 5269 raise util.Abort(_('only one config item permitted'))
5261 5270 for section, name, value in ui.walkconfig(untrusted=untrusted):
5262 5271 value = str(value).replace('\n', '\\n')
5263 5272 sectname = section + '.' + name
5264 5273 if values:
5265 5274 for v in values:
5266 5275 if v == section:
5267 5276 ui.debug('%s: ' %
5268 5277 ui.configsource(section, name, untrusted))
5269 5278 ui.write('%s=%s\n' % (sectname, value))
5270 5279 elif v == sectname:
5271 5280 ui.debug('%s: ' %
5272 5281 ui.configsource(section, name, untrusted))
5273 5282 ui.write(value, '\n')
5274 5283 else:
5275 5284 ui.debug('%s: ' %
5276 5285 ui.configsource(section, name, untrusted))
5277 5286 ui.write('%s=%s\n' % (sectname, value))
5278 5287
5279 5288 @command('^status|st',
5280 5289 [('A', 'all', None, _('show status of all files')),
5281 5290 ('m', 'modified', None, _('show only modified files')),
5282 5291 ('a', 'added', None, _('show only added files')),
5283 5292 ('r', 'removed', None, _('show only removed files')),
5284 5293 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5285 5294 ('c', 'clean', None, _('show only files without changes')),
5286 5295 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5287 5296 ('i', 'ignored', None, _('show only ignored files')),
5288 5297 ('n', 'no-status', None, _('hide status prefix')),
5289 5298 ('C', 'copies', None, _('show source of copied files')),
5290 5299 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5291 5300 ('', 'rev', [], _('show difference from revision'), _('REV')),
5292 5301 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5293 5302 ] + walkopts + subrepoopts,
5294 5303 _('[OPTION]... [FILE]...'))
5295 5304 def status(ui, repo, *pats, **opts):
5296 5305 """show changed files in the working directory
5297 5306
5298 5307 Show status of files in the repository. If names are given, only
5299 5308 files that match are shown. Files that are clean or ignored or
5300 5309 the source of a copy/move operation, are not listed unless
5301 5310 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5302 5311 Unless options described with "show only ..." are given, the
5303 5312 options -mardu are used.
5304 5313
5305 5314 Option -q/--quiet hides untracked (unknown and ignored) files
5306 5315 unless explicitly requested with -u/--unknown or -i/--ignored.
5307 5316
5308 5317 .. note::
5318
5309 5319 status may appear to disagree with diff if permissions have
5310 5320 changed or a merge has occurred. The standard diff format does
5311 5321 not report permission changes and diff only reports changes
5312 5322 relative to one merge parent.
5313 5323
5314 5324 If one revision is given, it is used as the base revision.
5315 5325 If two revisions are given, the differences between them are
5316 5326 shown. The --change option can also be used as a shortcut to list
5317 5327 the changed files of a revision from its first parent.
5318 5328
5319 5329 The codes used to show the status of files are::
5320 5330
5321 5331 M = modified
5322 5332 A = added
5323 5333 R = removed
5324 5334 C = clean
5325 5335 ! = missing (deleted by non-hg command, but still tracked)
5326 5336 ? = not tracked
5327 5337 I = ignored
5328 5338 = origin of the previous file listed as A (added)
5329 5339
5330 5340 .. container:: verbose
5331 5341
5332 5342 Examples:
5333 5343
5334 5344 - show changes in the working directory relative to a
5335 5345 changeset::
5336 5346
5337 5347 hg status --rev 9353
5338 5348
5339 5349 - show all changes including copies in an existing changeset::
5340 5350
5341 5351 hg status --copies --change 9353
5342 5352
5343 5353 - get a NUL separated list of added files, suitable for xargs::
5344 5354
5345 5355 hg status -an0
5346 5356
5347 5357 Returns 0 on success.
5348 5358 """
5349 5359
5350 5360 revs = opts.get('rev')
5351 5361 change = opts.get('change')
5352 5362
5353 5363 if revs and change:
5354 5364 msg = _('cannot specify --rev and --change at the same time')
5355 5365 raise util.Abort(msg)
5356 5366 elif change:
5357 5367 node2 = scmutil.revsingle(repo, change, None).node()
5358 5368 node1 = repo[node2].p1().node()
5359 5369 else:
5360 5370 node1, node2 = scmutil.revpair(repo, revs)
5361 5371
5362 5372 cwd = (pats and repo.getcwd()) or ''
5363 5373 end = opts.get('print0') and '\0' or '\n'
5364 5374 copy = {}
5365 5375 states = 'modified added removed deleted unknown ignored clean'.split()
5366 5376 show = [k for k in states if opts.get(k)]
5367 5377 if opts.get('all'):
5368 5378 show += ui.quiet and (states[:4] + ['clean']) or states
5369 5379 if not show:
5370 5380 show = ui.quiet and states[:4] or states[:5]
5371 5381
5372 5382 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5373 5383 'ignored' in show, 'clean' in show, 'unknown' in show,
5374 5384 opts.get('subrepos'))
5375 5385 changestates = zip(states, 'MAR!?IC', stat)
5376 5386
5377 5387 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5378 5388 copy = copies.pathcopies(repo[node1], repo[node2])
5379 5389
5380 5390 fm = ui.formatter('status', opts)
5381 5391 fmt = '%s' + end
5382 5392 showchar = not opts.get('no_status')
5383 5393
5384 5394 for state, char, files in changestates:
5385 5395 if state in show:
5386 5396 label = 'status.' + state
5387 5397 for f in files:
5388 5398 fm.startitem()
5389 5399 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5390 5400 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5391 5401 if f in copy:
5392 5402 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5393 5403 label='status.copied')
5394 5404 fm.end()
5395 5405
5396 5406 @command('^summary|sum',
5397 5407 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5398 5408 def summary(ui, repo, **opts):
5399 5409 """summarize working directory state
5400 5410
5401 5411 This generates a brief summary of the working directory state,
5402 5412 including parents, branch, commit status, and available updates.
5403 5413
5404 5414 With the --remote option, this will check the default paths for
5405 5415 incoming and outgoing changes. This can be time-consuming.
5406 5416
5407 5417 Returns 0 on success.
5408 5418 """
5409 5419
5410 5420 ctx = repo[None]
5411 5421 parents = ctx.parents()
5412 5422 pnode = parents[0].node()
5413 5423 marks = []
5414 5424
5415 5425 for p in parents:
5416 5426 # label with log.changeset (instead of log.parent) since this
5417 5427 # shows a working directory parent *changeset*:
5418 5428 # i18n: column positioning for "hg summary"
5419 5429 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5420 5430 label='log.changeset changeset.%s' % p.phasestr())
5421 5431 ui.write(' '.join(p.tags()), label='log.tag')
5422 5432 if p.bookmarks():
5423 5433 marks.extend(p.bookmarks())
5424 5434 if p.rev() == -1:
5425 5435 if not len(repo):
5426 5436 ui.write(_(' (empty repository)'))
5427 5437 else:
5428 5438 ui.write(_(' (no revision checked out)'))
5429 5439 ui.write('\n')
5430 5440 if p.description():
5431 5441 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5432 5442 label='log.summary')
5433 5443
5434 5444 branch = ctx.branch()
5435 5445 bheads = repo.branchheads(branch)
5436 5446 # i18n: column positioning for "hg summary"
5437 5447 m = _('branch: %s\n') % branch
5438 5448 if branch != 'default':
5439 5449 ui.write(m, label='log.branch')
5440 5450 else:
5441 5451 ui.status(m, label='log.branch')
5442 5452
5443 5453 if marks:
5444 5454 current = repo._bookmarkcurrent
5445 5455 # i18n: column positioning for "hg summary"
5446 5456 ui.write(_('bookmarks:'), label='log.bookmark')
5447 5457 if current is not None:
5448 5458 if current in marks:
5449 5459 ui.write(' *' + current, label='bookmarks.current')
5450 5460 marks.remove(current)
5451 5461 else:
5452 5462 ui.write(' [%s]' % current, label='bookmarks.current')
5453 5463 for m in marks:
5454 5464 ui.write(' ' + m, label='log.bookmark')
5455 5465 ui.write('\n', label='log.bookmark')
5456 5466
5457 5467 st = list(repo.status(unknown=True))[:6]
5458 5468
5459 5469 c = repo.dirstate.copies()
5460 5470 copied, renamed = [], []
5461 5471 for d, s in c.iteritems():
5462 5472 if s in st[2]:
5463 5473 st[2].remove(s)
5464 5474 renamed.append(d)
5465 5475 else:
5466 5476 copied.append(d)
5467 5477 if d in st[1]:
5468 5478 st[1].remove(d)
5469 5479 st.insert(3, renamed)
5470 5480 st.insert(4, copied)
5471 5481
5472 5482 ms = mergemod.mergestate(repo)
5473 5483 st.append([f for f in ms if ms[f] == 'u'])
5474 5484
5475 5485 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5476 5486 st.append(subs)
5477 5487
5478 5488 labels = [ui.label(_('%d modified'), 'status.modified'),
5479 5489 ui.label(_('%d added'), 'status.added'),
5480 5490 ui.label(_('%d removed'), 'status.removed'),
5481 5491 ui.label(_('%d renamed'), 'status.copied'),
5482 5492 ui.label(_('%d copied'), 'status.copied'),
5483 5493 ui.label(_('%d deleted'), 'status.deleted'),
5484 5494 ui.label(_('%d unknown'), 'status.unknown'),
5485 5495 ui.label(_('%d ignored'), 'status.ignored'),
5486 5496 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5487 5497 ui.label(_('%d subrepos'), 'status.modified')]
5488 5498 t = []
5489 5499 for s, l in zip(st, labels):
5490 5500 if s:
5491 5501 t.append(l % len(s))
5492 5502
5493 5503 t = ', '.join(t)
5494 5504 cleanworkdir = False
5495 5505
5496 5506 if repo.vfs.exists('updatestate'):
5497 5507 t += _(' (interrupted update)')
5498 5508 elif len(parents) > 1:
5499 5509 t += _(' (merge)')
5500 5510 elif branch != parents[0].branch():
5501 5511 t += _(' (new branch)')
5502 5512 elif (parents[0].closesbranch() and
5503 5513 pnode in repo.branchheads(branch, closed=True)):
5504 5514 t += _(' (head closed)')
5505 5515 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5506 5516 t += _(' (clean)')
5507 5517 cleanworkdir = True
5508 5518 elif pnode not in bheads:
5509 5519 t += _(' (new branch head)')
5510 5520
5511 5521 if cleanworkdir:
5512 5522 # i18n: column positioning for "hg summary"
5513 5523 ui.status(_('commit: %s\n') % t.strip())
5514 5524 else:
5515 5525 # i18n: column positioning for "hg summary"
5516 5526 ui.write(_('commit: %s\n') % t.strip())
5517 5527
5518 5528 # all ancestors of branch heads - all ancestors of parent = new csets
5519 5529 new = len(repo.changelog.findmissing([ctx.node() for ctx in parents],
5520 5530 bheads))
5521 5531
5522 5532 if new == 0:
5523 5533 # i18n: column positioning for "hg summary"
5524 5534 ui.status(_('update: (current)\n'))
5525 5535 elif pnode not in bheads:
5526 5536 # i18n: column positioning for "hg summary"
5527 5537 ui.write(_('update: %d new changesets (update)\n') % new)
5528 5538 else:
5529 5539 # i18n: column positioning for "hg summary"
5530 5540 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5531 5541 (new, len(bheads)))
5532 5542
5533 5543 cmdutil.summaryhooks(ui, repo)
5534 5544
5535 5545 if opts.get('remote'):
5536 5546 t = []
5537 5547 source, branches = hg.parseurl(ui.expandpath('default'))
5538 5548 sbranch = branches[0]
5539 5549 other = hg.peer(repo, {}, source)
5540 5550 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5541 5551 if revs:
5542 5552 revs = [other.lookup(rev) for rev in revs]
5543 5553 ui.debug('comparing with %s\n' % util.hidepassword(source))
5544 5554 repo.ui.pushbuffer()
5545 5555 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5546 5556 _common, incoming, _rheads = commoninc
5547 5557 repo.ui.popbuffer()
5548 5558 if incoming:
5549 5559 t.append(_('1 or more incoming'))
5550 5560
5551 5561 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5552 5562 dbranch = branches[0]
5553 5563 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5554 5564 if source != dest:
5555 5565 other = hg.peer(repo, {}, dest)
5556 5566 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5557 5567 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5558 5568 commoninc = None
5559 5569 if revs:
5560 5570 revs = [repo.lookup(rev) for rev in revs]
5561 5571 repo.ui.pushbuffer()
5562 5572 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs,
5563 5573 commoninc=commoninc)
5564 5574 repo.ui.popbuffer()
5565 5575 o = outgoing.missing
5566 5576 if o:
5567 5577 t.append(_('%d outgoing') % len(o))
5568 5578 if 'bookmarks' in other.listkeys('namespaces'):
5569 5579 lmarks = repo.listkeys('bookmarks')
5570 5580 rmarks = other.listkeys('bookmarks')
5571 5581 diff = set(rmarks) - set(lmarks)
5572 5582 if len(diff) > 0:
5573 5583 t.append(_('%d incoming bookmarks') % len(diff))
5574 5584 diff = set(lmarks) - set(rmarks)
5575 5585 if len(diff) > 0:
5576 5586 t.append(_('%d outgoing bookmarks') % len(diff))
5577 5587
5578 5588 if t:
5579 5589 # i18n: column positioning for "hg summary"
5580 5590 ui.write(_('remote: %s\n') % (', '.join(t)))
5581 5591 else:
5582 5592 # i18n: column positioning for "hg summary"
5583 5593 ui.status(_('remote: (synced)\n'))
5584 5594
5585 5595 @command('tag',
5586 5596 [('f', 'force', None, _('force tag')),
5587 5597 ('l', 'local', None, _('make the tag local')),
5588 5598 ('r', 'rev', '', _('revision to tag'), _('REV')),
5589 5599 ('', 'remove', None, _('remove a tag')),
5590 5600 # -l/--local is already there, commitopts cannot be used
5591 5601 ('e', 'edit', None, _('edit commit message')),
5592 5602 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5593 5603 ] + commitopts2,
5594 5604 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5595 5605 def tag(ui, repo, name1, *names, **opts):
5596 5606 """add one or more tags for the current or given revision
5597 5607
5598 5608 Name a particular revision using <name>.
5599 5609
5600 5610 Tags are used to name particular revisions of the repository and are
5601 5611 very useful to compare different revisions, to go back to significant
5602 5612 earlier versions or to mark branch points as releases, etc. Changing
5603 5613 an existing tag is normally disallowed; use -f/--force to override.
5604 5614
5605 5615 If no revision is given, the parent of the working directory is
5606 5616 used.
5607 5617
5608 5618 To facilitate version control, distribution, and merging of tags,
5609 5619 they are stored as a file named ".hgtags" which is managed similarly
5610 5620 to other project files and can be hand-edited if necessary. This
5611 5621 also means that tagging creates a new commit. The file
5612 5622 ".hg/localtags" is used for local tags (not shared among
5613 5623 repositories).
5614 5624
5615 5625 Tag commits are usually made at the head of a branch. If the parent
5616 5626 of the working directory is not a branch head, :hg:`tag` aborts; use
5617 5627 -f/--force to force the tag commit to be based on a non-head
5618 5628 changeset.
5619 5629
5620 5630 See :hg:`help dates` for a list of formats valid for -d/--date.
5621 5631
5622 5632 Since tag names have priority over branch names during revision
5623 5633 lookup, using an existing branch name as a tag name is discouraged.
5624 5634
5625 5635 Returns 0 on success.
5626 5636 """
5627 5637 wlock = lock = None
5628 5638 try:
5629 5639 wlock = repo.wlock()
5630 5640 lock = repo.lock()
5631 5641 rev_ = "."
5632 5642 names = [t.strip() for t in (name1,) + names]
5633 5643 if len(names) != len(set(names)):
5634 5644 raise util.Abort(_('tag names must be unique'))
5635 5645 for n in names:
5636 5646 scmutil.checknewlabel(repo, n, 'tag')
5637 5647 if not n:
5638 5648 raise util.Abort(_('tag names cannot consist entirely of '
5639 5649 'whitespace'))
5640 5650 if opts.get('rev') and opts.get('remove'):
5641 5651 raise util.Abort(_("--rev and --remove are incompatible"))
5642 5652 if opts.get('rev'):
5643 5653 rev_ = opts['rev']
5644 5654 message = opts.get('message')
5645 5655 if opts.get('remove'):
5646 5656 expectedtype = opts.get('local') and 'local' or 'global'
5647 5657 for n in names:
5648 5658 if not repo.tagtype(n):
5649 5659 raise util.Abort(_("tag '%s' does not exist") % n)
5650 5660 if repo.tagtype(n) != expectedtype:
5651 5661 if expectedtype == 'global':
5652 5662 raise util.Abort(_("tag '%s' is not a global tag") % n)
5653 5663 else:
5654 5664 raise util.Abort(_("tag '%s' is not a local tag") % n)
5655 5665 rev_ = nullid
5656 5666 if not message:
5657 5667 # we don't translate commit messages
5658 5668 message = 'Removed tag %s' % ', '.join(names)
5659 5669 elif not opts.get('force'):
5660 5670 for n in names:
5661 5671 if n in repo.tags():
5662 5672 raise util.Abort(_("tag '%s' already exists "
5663 5673 "(use -f to force)") % n)
5664 5674 if not opts.get('local'):
5665 5675 p1, p2 = repo.dirstate.parents()
5666 5676 if p2 != nullid:
5667 5677 raise util.Abort(_('uncommitted merge'))
5668 5678 bheads = repo.branchheads()
5669 5679 if not opts.get('force') and bheads and p1 not in bheads:
5670 5680 raise util.Abort(_('not at a branch head (use -f to force)'))
5671 5681 r = scmutil.revsingle(repo, rev_).node()
5672 5682
5673 5683 if not message:
5674 5684 # we don't translate commit messages
5675 5685 message = ('Added tag %s for changeset %s' %
5676 5686 (', '.join(names), short(r)))
5677 5687
5678 5688 date = opts.get('date')
5679 5689 if date:
5680 5690 date = util.parsedate(date)
5681 5691
5682 5692 if opts.get('edit'):
5683 5693 message = ui.edit(message, ui.username())
5684 5694
5685 5695 # don't allow tagging the null rev
5686 5696 if (not opts.get('remove') and
5687 5697 scmutil.revsingle(repo, rev_).rev() == nullrev):
5688 5698 raise util.Abort(_("cannot tag null revision"))
5689 5699
5690 5700 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5691 5701 finally:
5692 5702 release(lock, wlock)
5693 5703
5694 5704 @command('tags', [], '')
5695 5705 def tags(ui, repo, **opts):
5696 5706 """list repository tags
5697 5707
5698 5708 This lists both regular and local tags. When the -v/--verbose
5699 5709 switch is used, a third column "local" is printed for local tags.
5700 5710
5701 5711 Returns 0 on success.
5702 5712 """
5703 5713
5704 5714 fm = ui.formatter('tags', opts)
5705 5715 hexfunc = ui.debugflag and hex or short
5706 5716 tagtype = ""
5707 5717
5708 5718 for t, n in reversed(repo.tagslist()):
5709 5719 hn = hexfunc(n)
5710 5720 label = 'tags.normal'
5711 5721 tagtype = ''
5712 5722 if repo.tagtype(t) == 'local':
5713 5723 label = 'tags.local'
5714 5724 tagtype = 'local'
5715 5725
5716 5726 fm.startitem()
5717 5727 fm.write('tag', '%s', t, label=label)
5718 5728 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5719 5729 fm.condwrite(not ui.quiet, 'rev id', fmt,
5720 5730 repo.changelog.rev(n), hn, label=label)
5721 5731 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5722 5732 tagtype, label=label)
5723 5733 fm.plain('\n')
5724 5734 fm.end()
5725 5735
5726 5736 @command('tip',
5727 5737 [('p', 'patch', None, _('show patch')),
5728 5738 ('g', 'git', None, _('use git extended diff format')),
5729 5739 ] + templateopts,
5730 5740 _('[-p] [-g]'))
5731 5741 def tip(ui, repo, **opts):
5732 5742 """show the tip revision (DEPRECATED)
5733 5743
5734 5744 The tip revision (usually just called the tip) is the changeset
5735 5745 most recently added to the repository (and therefore the most
5736 5746 recently changed head).
5737 5747
5738 5748 If you have just made a commit, that commit will be the tip. If
5739 5749 you have just pulled changes from another repository, the tip of
5740 5750 that repository becomes the current tip. The "tip" tag is special
5741 5751 and cannot be renamed or assigned to a different changeset.
5742 5752
5743 5753 This command is deprecated, please use :hg:`heads` instead.
5744 5754
5745 5755 Returns 0 on success.
5746 5756 """
5747 5757 displayer = cmdutil.show_changeset(ui, repo, opts)
5748 5758 displayer.show(repo['tip'])
5749 5759 displayer.close()
5750 5760
5751 5761 @command('unbundle',
5752 5762 [('u', 'update', None,
5753 5763 _('update to new branch head if changesets were unbundled'))],
5754 5764 _('[-u] FILE...'))
5755 5765 def unbundle(ui, repo, fname1, *fnames, **opts):
5756 5766 """apply one or more changegroup files
5757 5767
5758 5768 Apply one or more compressed changegroup files generated by the
5759 5769 bundle command.
5760 5770
5761 5771 Returns 0 on success, 1 if an update has unresolved files.
5762 5772 """
5763 5773 fnames = (fname1,) + fnames
5764 5774
5765 5775 lock = repo.lock()
5766 5776 wc = repo['.']
5767 5777 try:
5768 5778 for fname in fnames:
5769 5779 f = hg.openpath(ui, fname)
5770 5780 gen = changegroup.readbundle(f, fname)
5771 5781 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5772 5782 finally:
5773 5783 lock.release()
5774 5784 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5775 5785 return postincoming(ui, repo, modheads, opts.get('update'), None)
5776 5786
5777 5787 @command('^update|up|checkout|co',
5778 5788 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5779 5789 ('c', 'check', None,
5780 5790 _('update across branches if no uncommitted changes')),
5781 5791 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5782 5792 ('r', 'rev', '', _('revision'), _('REV'))],
5783 5793 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5784 5794 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5785 5795 """update working directory (or switch revisions)
5786 5796
5787 5797 Update the repository's working directory to the specified
5788 5798 changeset. If no changeset is specified, update to the tip of the
5789 5799 current named branch and move the current bookmark (see :hg:`help
5790 5800 bookmarks`).
5791 5801
5792 5802 Update sets the working directory's parent revision to the specified
5793 5803 changeset (see :hg:`help parents`).
5794 5804
5795 5805 If the changeset is not a descendant or ancestor of the working
5796 5806 directory's parent, the update is aborted. With the -c/--check
5797 5807 option, the working directory is checked for uncommitted changes; if
5798 5808 none are found, the working directory is updated to the specified
5799 5809 changeset.
5800 5810
5801 5811 .. container:: verbose
5802 5812
5803 5813 The following rules apply when the working directory contains
5804 5814 uncommitted changes:
5805 5815
5806 5816 1. If neither -c/--check nor -C/--clean is specified, and if
5807 5817 the requested changeset is an ancestor or descendant of
5808 5818 the working directory's parent, the uncommitted changes
5809 5819 are merged into the requested changeset and the merged
5810 5820 result is left uncommitted. If the requested changeset is
5811 5821 not an ancestor or descendant (that is, it is on another
5812 5822 branch), the update is aborted and the uncommitted changes
5813 5823 are preserved.
5814 5824
5815 5825 2. With the -c/--check option, the update is aborted and the
5816 5826 uncommitted changes are preserved.
5817 5827
5818 5828 3. With the -C/--clean option, uncommitted changes are discarded and
5819 5829 the working directory is updated to the requested changeset.
5820 5830
5821 5831 To cancel an uncommitted merge (and lose your changes), use
5822 5832 :hg:`update --clean .`.
5823 5833
5824 5834 Use null as the changeset to remove the working directory (like
5825 5835 :hg:`clone -U`).
5826 5836
5827 5837 If you want to revert just one file to an older revision, use
5828 5838 :hg:`revert [-r REV] NAME`.
5829 5839
5830 5840 See :hg:`help dates` for a list of formats valid for -d/--date.
5831 5841
5832 5842 Returns 0 on success, 1 if there are unresolved files.
5833 5843 """
5834 5844 if rev and node:
5835 5845 raise util.Abort(_("please specify just one revision"))
5836 5846
5837 5847 if rev is None or rev == '':
5838 5848 rev = node
5839 5849
5840 5850 cmdutil.clearunfinished(repo)
5841 5851
5842 5852 # with no argument, we also move the current bookmark, if any
5843 5853 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
5844 5854
5845 5855 # if we defined a bookmark, we have to remember the original bookmark name
5846 5856 brev = rev
5847 5857 rev = scmutil.revsingle(repo, rev, rev).rev()
5848 5858
5849 5859 if check and clean:
5850 5860 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5851 5861
5852 5862 if date:
5853 5863 if rev is not None:
5854 5864 raise util.Abort(_("you can't specify a revision and a date"))
5855 5865 rev = cmdutil.finddate(ui, repo, date)
5856 5866
5857 5867 if check:
5858 5868 c = repo[None]
5859 5869 if c.dirty(merge=False, branch=False, missing=True):
5860 5870 raise util.Abort(_("uncommitted changes"))
5861 5871 if rev is None:
5862 5872 rev = repo[repo[None].branch()].rev()
5863 5873 mergemod._checkunknown(repo, repo[None], repo[rev])
5864 5874
5865 5875 if clean:
5866 5876 ret = hg.clean(repo, rev)
5867 5877 else:
5868 5878 ret = hg.update(repo, rev)
5869 5879
5870 5880 if not ret and movemarkfrom:
5871 5881 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5872 5882 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5873 5883 elif brev in repo._bookmarks:
5874 5884 bookmarks.setcurrent(repo, brev)
5875 5885 elif brev:
5876 5886 bookmarks.unsetcurrent(repo)
5877 5887
5878 5888 return ret
5879 5889
5880 5890 @command('verify', [])
5881 5891 def verify(ui, repo):
5882 5892 """verify the integrity of the repository
5883 5893
5884 5894 Verify the integrity of the current repository.
5885 5895
5886 5896 This will perform an extensive check of the repository's
5887 5897 integrity, validating the hashes and checksums of each entry in
5888 5898 the changelog, manifest, and tracked files, as well as the
5889 5899 integrity of their crosslinks and indices.
5890 5900
5891 5901 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
5892 5902 for more information about recovery from corruption of the
5893 5903 repository.
5894 5904
5895 5905 Returns 0 on success, 1 if errors are encountered.
5896 5906 """
5897 5907 return hg.verify(repo)
5898 5908
5899 5909 @command('version', [])
5900 5910 def version_(ui):
5901 5911 """output version and copyright information"""
5902 5912 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5903 5913 % util.version())
5904 5914 ui.status(_(
5905 5915 "(see http://mercurial.selenic.com for more information)\n"
5906 5916 "\nCopyright (C) 2005-2013 Matt Mackall and others\n"
5907 5917 "This is free software; see the source for copying conditions. "
5908 5918 "There is NO\nwarranty; "
5909 5919 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5910 5920 ))
5911 5921
5912 5922 norepo = ("clone init version help debugcommands debugcomplete"
5913 5923 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5914 5924 " debugknown debuggetbundle debugbundle")
5915 5925 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5916 5926 " debugdata debugindex debugindexdot debugrevlog")
5917 5927 inferrepo = ("add addremove annotate cat commit diff grep forget log parents"
5918 5928 " remove resolve status debugwalk")
General Comments 0
You need to be logged in to leave comments. Login now