##// END OF EJS Templates
Use hg role in help strings
Martin Geisler -
r10973:49a07f44 default
parent child Browse files
Show More
@@ -1,343 +1,343
1 1 # Mercurial extension to provide the 'hg bookmark' command
2 2 #
3 3 # Copyright 2008 David Soria Parra <dsp@php.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 '''track a line of development with movable markers
9 9
10 10 Bookmarks are local movable markers to changesets. Every bookmark
11 11 points to a changeset identified by its hash. If you commit a
12 12 changeset that is based on a changeset that has a bookmark on it, the
13 13 bookmark shifts to the new changeset.
14 14
15 15 It is possible to use bookmark names in every revision lookup (e.g. hg
16 16 merge, hg update).
17 17
18 18 By default, when several bookmarks point to the same changeset, they
19 19 will all move forward together. It is possible to obtain a more
20 20 git-like experience by adding the following configuration option to
21 21 your .hgrc::
22 22
23 23 [bookmarks]
24 24 track.current = True
25 25
26 26 This will cause Mercurial to track the bookmark that you are currently
27 27 using, and only update it. This is similar to git's approach to
28 28 branching.
29 29 '''
30 30
31 31 from mercurial.i18n import _
32 32 from mercurial.node import nullid, nullrev, hex, short
33 33 from mercurial import util, commands, repair, extensions
34 34 import os
35 35
36 36 def write(repo):
37 37 '''Write bookmarks
38 38
39 39 Write the given bookmark => hash dictionary to the .hg/bookmarks file
40 40 in a format equal to those of localtags.
41 41
42 42 We also store a backup of the previous state in undo.bookmarks that
43 43 can be copied back on rollback.
44 44 '''
45 45 refs = repo._bookmarks
46 46 if os.path.exists(repo.join('bookmarks')):
47 47 util.copyfile(repo.join('bookmarks'), repo.join('undo.bookmarks'))
48 48 if repo._bookmarkcurrent not in refs:
49 49 setcurrent(repo, None)
50 50 wlock = repo.wlock()
51 51 try:
52 52 file = repo.opener('bookmarks', 'w', atomictemp=True)
53 53 for refspec, node in refs.iteritems():
54 54 file.write("%s %s\n" % (hex(node), refspec))
55 55 file.rename()
56 56 finally:
57 57 wlock.release()
58 58
59 59 def setcurrent(repo, mark):
60 60 '''Set the name of the bookmark that we are currently on
61 61
62 62 Set the name of the bookmark that we are on (hg update <bookmark>).
63 63 The name is recorded in .hg/bookmarks.current
64 64 '''
65 65 current = repo._bookmarkcurrent
66 66 if current == mark:
67 67 return
68 68
69 69 refs = repo._bookmarks
70 70
71 71 # do not update if we do update to a rev equal to the current bookmark
72 72 if (mark and mark not in refs and
73 73 current and refs[current] == repo.changectx('.').node()):
74 74 return
75 75 if mark not in refs:
76 76 mark = ''
77 77 wlock = repo.wlock()
78 78 try:
79 79 file = repo.opener('bookmarks.current', 'w', atomictemp=True)
80 80 file.write(mark)
81 81 file.rename()
82 82 finally:
83 83 wlock.release()
84 84 repo._bookmarkcurrent = mark
85 85
86 86 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False, rename=None):
87 87 '''track a line of development with movable markers
88 88
89 89 Bookmarks are pointers to certain commits that move when
90 90 committing. Bookmarks are local. They can be renamed, copied and
91 deleted. It is possible to use bookmark names in 'hg merge' and
92 'hg update' to merge and update respectively to a given bookmark.
91 deleted. It is possible to use bookmark names in :hg:`merge` and
92 :hg:`update` to merge and update respectively to a given bookmark.
93 93
94 You can use 'hg bookmark NAME' to set a bookmark on the working
94 You can use :hg:`bookmark NAME` to set a bookmark on the working
95 95 directory's parent revision with the given name. If you specify
96 96 a revision using -r REV (where REV may be an existing bookmark),
97 97 the bookmark is assigned to that revision.
98 98 '''
99 99 hexfn = ui.debugflag and hex or short
100 100 marks = repo._bookmarks
101 101 cur = repo.changectx('.').node()
102 102
103 103 if rename:
104 104 if rename not in marks:
105 105 raise util.Abort(_("a bookmark of this name does not exist"))
106 106 if mark in marks and not force:
107 107 raise util.Abort(_("a bookmark of the same name already exists"))
108 108 if mark is None:
109 109 raise util.Abort(_("new bookmark name required"))
110 110 marks[mark] = marks[rename]
111 111 del marks[rename]
112 112 if repo._bookmarkcurrent == rename:
113 113 setcurrent(repo, mark)
114 114 write(repo)
115 115 return
116 116
117 117 if delete:
118 118 if mark is None:
119 119 raise util.Abort(_("bookmark name required"))
120 120 if mark not in marks:
121 121 raise util.Abort(_("a bookmark of this name does not exist"))
122 122 if mark == repo._bookmarkcurrent:
123 123 setcurrent(repo, None)
124 124 del marks[mark]
125 125 write(repo)
126 126 return
127 127
128 128 if mark != None:
129 129 if "\n" in mark:
130 130 raise util.Abort(_("bookmark name cannot contain newlines"))
131 131 mark = mark.strip()
132 132 if mark in marks and not force:
133 133 raise util.Abort(_("a bookmark of the same name already exists"))
134 134 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
135 135 and not force):
136 136 raise util.Abort(
137 137 _("a bookmark cannot have the name of an existing branch"))
138 138 if rev:
139 139 marks[mark] = repo.lookup(rev)
140 140 else:
141 141 marks[mark] = repo.changectx('.').node()
142 142 setcurrent(repo, mark)
143 143 write(repo)
144 144 return
145 145
146 146 if mark is None:
147 147 if rev:
148 148 raise util.Abort(_("bookmark name required"))
149 149 if len(marks) == 0:
150 150 ui.status(_("no bookmarks set\n"))
151 151 else:
152 152 for bmark, n in marks.iteritems():
153 153 if ui.configbool('bookmarks', 'track.current'):
154 154 current = repo._bookmarkcurrent
155 155 if bmark == current and n == cur:
156 156 prefix, label = '*', 'bookmarks.current'
157 157 else:
158 158 prefix, label = ' ', ''
159 159 else:
160 160 if n == cur:
161 161 prefix, label = '*', 'bookmarks.current'
162 162 else:
163 163 prefix, label = ' ', ''
164 164
165 165 if ui.quiet:
166 166 ui.write("%s\n" % bmark, label=label)
167 167 else:
168 168 ui.write(" %s %-25s %d:%s\n" % (
169 169 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
170 170 label=label)
171 171 return
172 172
173 173 def _revstostrip(changelog, node):
174 174 srev = changelog.rev(node)
175 175 tostrip = [srev]
176 176 saveheads = []
177 177 for r in xrange(srev, len(changelog)):
178 178 parents = changelog.parentrevs(r)
179 179 if parents[0] in tostrip or parents[1] in tostrip:
180 180 tostrip.append(r)
181 181 if parents[1] != nullrev:
182 182 for p in parents:
183 183 if p not in tostrip and p > srev:
184 184 saveheads.append(p)
185 185 return [r for r in tostrip if r not in saveheads]
186 186
187 187 def strip(oldstrip, ui, repo, node, backup="all"):
188 188 """Strip bookmarks if revisions are stripped using
189 189 the mercurial.strip method. This usually happens during
190 190 qpush and qpop"""
191 191 revisions = _revstostrip(repo.changelog, node)
192 192 marks = repo._bookmarks
193 193 update = []
194 194 for mark, n in marks.iteritems():
195 195 if repo.changelog.rev(n) in revisions:
196 196 update.append(mark)
197 197 oldstrip(ui, repo, node, backup)
198 198 if len(update) > 0:
199 199 for m in update:
200 200 marks[m] = repo.changectx('.').node()
201 201 write(repo)
202 202
203 203 def reposetup(ui, repo):
204 204 if not repo.local():
205 205 return
206 206
207 207 class bookmark_repo(repo.__class__):
208 208
209 209 @util.propertycache
210 210 def _bookmarks(self):
211 211 '''Parse .hg/bookmarks file and return a dictionary
212 212
213 213 Bookmarks are stored as {HASH}\\s{NAME}\\n (localtags format) values
214 214 in the .hg/bookmarks file. They are read returned as a dictionary
215 215 with name => hash values.
216 216 '''
217 217 try:
218 218 bookmarks = {}
219 219 for line in self.opener('bookmarks'):
220 220 sha, refspec = line.strip().split(' ', 1)
221 221 bookmarks[refspec] = super(bookmark_repo, self).lookup(sha)
222 222 except:
223 223 pass
224 224 return bookmarks
225 225
226 226 @util.propertycache
227 227 def _bookmarkcurrent(self):
228 228 '''Get the current bookmark
229 229
230 230 If we use gittishsh branches we have a current bookmark that
231 231 we are on. This function returns the name of the bookmark. It
232 232 is stored in .hg/bookmarks.current
233 233 '''
234 234 mark = None
235 235 if os.path.exists(self.join('bookmarks.current')):
236 236 file = self.opener('bookmarks.current')
237 237 # No readline() in posixfile_nt, reading everything is cheap
238 238 mark = (file.readlines() or [''])[0]
239 239 if mark == '':
240 240 mark = None
241 241 file.close()
242 242 return mark
243 243
244 244 def rollback(self, *args):
245 245 if os.path.exists(self.join('undo.bookmarks')):
246 246 util.rename(self.join('undo.bookmarks'), self.join('bookmarks'))
247 247 return super(bookmark_repo, self).rollback(*args)
248 248
249 249 def lookup(self, key):
250 250 if key in self._bookmarks:
251 251 key = self._bookmarks[key]
252 252 return super(bookmark_repo, self).lookup(key)
253 253
254 254 def _bookmarksupdate(self, parents, node):
255 255 marks = self._bookmarks
256 256 update = False
257 257 if ui.configbool('bookmarks', 'track.current'):
258 258 mark = self._bookmarkcurrent
259 259 if mark and marks[mark] in parents:
260 260 marks[mark] = node
261 261 update = True
262 262 else:
263 263 for mark, n in marks.items():
264 264 if n in parents:
265 265 marks[mark] = node
266 266 update = True
267 267 if update:
268 268 write(self)
269 269
270 270 def commitctx(self, ctx, error=False):
271 271 """Add a revision to the repository and
272 272 move the bookmark"""
273 273 wlock = self.wlock() # do both commit and bookmark with lock held
274 274 try:
275 275 node = super(bookmark_repo, self).commitctx(ctx, error)
276 276 if node is None:
277 277 return None
278 278 parents = self.changelog.parents(node)
279 279 if parents[1] == nullid:
280 280 parents = (parents[0],)
281 281
282 282 self._bookmarksupdate(parents, node)
283 283 return node
284 284 finally:
285 285 wlock.release()
286 286
287 287 def addchangegroup(self, source, srctype, url, emptyok=False):
288 288 parents = self.dirstate.parents()
289 289
290 290 result = super(bookmark_repo, self).addchangegroup(
291 291 source, srctype, url, emptyok)
292 292 if result > 1:
293 293 # We have more heads than before
294 294 return result
295 295 node = self.changelog.tip()
296 296
297 297 self._bookmarksupdate(parents, node)
298 298 return result
299 299
300 300 def _findtags(self):
301 301 """Merge bookmarks with normal tags"""
302 302 (tags, tagtypes) = super(bookmark_repo, self)._findtags()
303 303 tags.update(self._bookmarks)
304 304 return (tags, tagtypes)
305 305
306 306 if hasattr(repo, 'invalidate'):
307 307 def invalidate(self):
308 308 super(bookmark_repo, self).invalidate()
309 309 for attr in ('_bookmarks', '_bookmarkcurrent'):
310 310 if attr in self.__dict__:
311 311 delattr(self, attr)
312 312
313 313 repo.__class__ = bookmark_repo
314 314
315 315 def uisetup(ui):
316 316 extensions.wrapfunction(repair, "strip", strip)
317 317 if ui.configbool('bookmarks', 'track.current'):
318 318 extensions.wrapcommand(commands.table, 'update', updatecurbookmark)
319 319
320 320 def updatecurbookmark(orig, ui, repo, *args, **opts):
321 321 '''Set the current bookmark
322 322
323 323 If the user updates to a bookmark we update the .hg/bookmarks.current
324 324 file.
325 325 '''
326 326 res = orig(ui, repo, *args, **opts)
327 327 rev = opts['rev']
328 328 if not rev and len(args) > 0:
329 329 rev = args[0]
330 330 setcurrent(repo, rev)
331 331 return res
332 332
333 333 cmdtable = {
334 334 "bookmarks":
335 335 (bookmark,
336 336 [('f', 'force', False, _('force')),
337 337 ('r', 'rev', '', _('revision')),
338 338 ('d', 'delete', False, _('delete a given bookmark')),
339 339 ('m', 'rename', '', _('rename a given bookmark'))],
340 340 _('hg bookmarks [-f] [-d] [-m NAME] [-r REV] [NAME]')),
341 341 }
342 342
343 343 colortable = {'bookmarks.current': 'green'}
@@ -1,147 +1,147
1 1 # fetch.py - pull and merge remote changes
2 2 #
3 3 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.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 '''pull, update and merge in one command'''
9 9
10 10 from mercurial.i18n import _
11 11 from mercurial.node import nullid, short
12 12 from mercurial import commands, cmdutil, hg, util, url, error
13 13 from mercurial.lock import release
14 14
15 15 def fetch(ui, repo, source='default', **opts):
16 16 '''pull changes from a remote repository, merge new changes if needed.
17 17
18 18 This finds all changes from the repository at the specified path
19 19 or URL and adds them to the local repository.
20 20
21 21 If the pulled changes add a new branch head, the head is
22 22 automatically merged, and the result of the merge is committed.
23 23 Otherwise, the working directory is updated to include the new
24 24 changes.
25 25
26 26 When a merge occurs, the newly pulled changes are assumed to be
27 27 "authoritative". The head of the new changes is used as the first
28 28 parent, with local changes as the second. To switch the merge
29 29 order, use --switch-parent.
30 30
31 See 'hg help dates' for a list of formats valid for -d/--date.
31 See :hg:`help dates` for a list of formats valid for -d/--date.
32 32 '''
33 33
34 34 date = opts.get('date')
35 35 if date:
36 36 opts['date'] = util.parsedate(date)
37 37
38 38 parent, p2 = repo.dirstate.parents()
39 39 branch = repo.dirstate.branch()
40 40 branchnode = repo.branchtags().get(branch)
41 41 if parent != branchnode:
42 42 raise util.Abort(_('working dir not at branch tip '
43 43 '(use "hg update" to check out branch tip)'))
44 44
45 45 if p2 != nullid:
46 46 raise util.Abort(_('outstanding uncommitted merge'))
47 47
48 48 wlock = lock = None
49 49 try:
50 50 wlock = repo.wlock()
51 51 lock = repo.lock()
52 52 mod, add, rem, del_ = repo.status()[:4]
53 53
54 54 if mod or add or rem:
55 55 raise util.Abort(_('outstanding uncommitted changes'))
56 56 if del_:
57 57 raise util.Abort(_('working directory is missing some files'))
58 58 bheads = repo.branchheads(branch)
59 59 bheads = [head for head in bheads if len(repo[head].children()) == 0]
60 60 if len(bheads) > 1:
61 61 raise util.Abort(_('multiple heads in this branch '
62 62 '(use "hg heads ." and "hg merge" to merge)'))
63 63
64 64 other = hg.repository(cmdutil.remoteui(repo, opts),
65 65 ui.expandpath(source))
66 66 ui.status(_('pulling from %s\n') %
67 67 url.hidepassword(ui.expandpath(source)))
68 68 revs = None
69 69 if opts['rev']:
70 70 try:
71 71 revs = [other.lookup(rev) for rev in opts['rev']]
72 72 except error.CapabilityError:
73 73 err = _("Other repository doesn't support revision lookup, "
74 74 "so a rev cannot be specified.")
75 75 raise util.Abort(err)
76 76
77 77 # Are there any changes at all?
78 78 modheads = repo.pull(other, heads=revs)
79 79 if modheads == 0:
80 80 return 0
81 81
82 82 # Is this a simple fast-forward along the current branch?
83 83 newheads = repo.branchheads(branch)
84 84 newchildren = repo.changelog.nodesbetween([parent], newheads)[2]
85 85 if len(newheads) == 1:
86 86 if newchildren[0] != parent:
87 87 return hg.clean(repo, newchildren[0])
88 88 else:
89 89 return
90 90
91 91 # Are there more than one additional branch heads?
92 92 newchildren = [n for n in newchildren if n != parent]
93 93 newparent = parent
94 94 if newchildren:
95 95 newparent = newchildren[0]
96 96 hg.clean(repo, newparent)
97 97 newheads = [n for n in newheads if n != newparent]
98 98 if len(newheads) > 1:
99 99 ui.status(_('not merging with %d other new branch heads '
100 100 '(use "hg heads ." and "hg merge" to merge them)\n') %
101 101 (len(newheads) - 1))
102 102 return
103 103
104 104 # Otherwise, let's merge.
105 105 err = False
106 106 if newheads:
107 107 # By default, we consider the repository we're pulling
108 108 # *from* as authoritative, so we merge our changes into
109 109 # theirs.
110 110 if opts['switch_parent']:
111 111 firstparent, secondparent = newparent, newheads[0]
112 112 else:
113 113 firstparent, secondparent = newheads[0], newparent
114 114 ui.status(_('updating to %d:%s\n') %
115 115 (repo.changelog.rev(firstparent),
116 116 short(firstparent)))
117 117 hg.clean(repo, firstparent)
118 118 ui.status(_('merging with %d:%s\n') %
119 119 (repo.changelog.rev(secondparent), short(secondparent)))
120 120 err = hg.merge(repo, secondparent, remind=False)
121 121
122 122 if not err:
123 123 # we don't translate commit messages
124 124 message = (cmdutil.logmessage(opts) or
125 125 ('Automated merge with %s' %
126 126 url.removeauth(other.url())))
127 127 editor = cmdutil.commiteditor
128 128 if opts.get('force_editor') or opts.get('edit'):
129 129 editor = cmdutil.commitforceeditor
130 130 n = repo.commit(message, opts['user'], opts['date'], editor=editor)
131 131 ui.status(_('new changeset %d:%s merges remote changes '
132 132 'with local\n') % (repo.changelog.rev(n),
133 133 short(n)))
134 134
135 135 finally:
136 136 release(lock, wlock)
137 137
138 138 cmdtable = {
139 139 'fetch':
140 140 (fetch,
141 141 [('r', 'rev', [], _('a specific revision you would like to pull')),
142 142 ('e', 'edit', None, _('edit commit message')),
143 143 ('', 'force-editor', None, _('edit commit message (DEPRECATED)')),
144 144 ('', 'switch-parent', None, _('switch parents when merging')),
145 145 ] + commands.commitopts + commands.commitopts2 + commands.remoteopts,
146 146 _('hg fetch [SOURCE]')),
147 147 }
@@ -1,521 +1,521
1 1 # keyword.py - $Keyword$ expansion for Mercurial
2 2 #
3 3 # Copyright 2007-2010 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 DSCM
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 Configuration is done in the [keyword] and [keywordmaps] sections of
39 39 hgrc files.
40 40
41 41 Example::
42 42
43 43 [keyword]
44 44 # expand keywords in every python file except those matching "x*"
45 45 **.py =
46 46 x* = ignore
47 47
48 48 NOTE: the more specific you are in your filename patterns the less you
49 49 lose speed in huge repositories.
50 50
51 51 For [keywordmaps] template mapping and expansion demonstration and
52 control run "hg kwdemo". See "hg help templates" for a list of
52 control run :hg:`kwdemo`. See :hg:`help templates` for a list of
53 53 available templates and filters.
54 54
55 55 An additional date template filter {date|utcdate} is provided. It
56 56 returns a date like "2006/09/18 15:13:13".
57 57
58 The default template mappings (view with "hg kwdemo -d") can be
59 replaced with customized keywords and templates. Again, run "hg
60 kwdemo" to control the results of your config changes.
58 The default template mappings (view with :hg:`kwdemo -d`) can be
59 replaced with customized keywords and templates. Again, run
60 :hg:`kwdemo` to control the results of your config changes.
61 61
62 Before changing/disabling active keywords, run "hg kwshrink" to avoid
62 Before changing/disabling active keywords, run :hg:`kwshrink` to avoid
63 63 the risk of inadvertently storing expanded keywords in the change
64 64 history.
65 65
66 66 To force expansion after enabling it, or a configuration change, run
67 "hg kwexpand".
67 :hg:`kwexpand`.
68 68
69 69 Also, when committing with the record extension or using mq's qrecord,
70 be aware that keywords cannot be updated. Again, run "hg kwexpand" on
70 be aware that keywords cannot be updated. Again, run :hg:`kwexpand` on
71 71 the files in question to update keyword expansions after all changes
72 72 have been checked in.
73 73
74 74 Expansions spanning more than one line and incremental expansions,
75 75 like CVS' $Log$, are not supported. A keyword template map "Log =
76 76 {desc}" expands to the first line of the changeset description.
77 77 '''
78 78
79 79 from mercurial import commands, cmdutil, dispatch, filelog, revlog, extensions
80 80 from mercurial import patch, localrepo, templater, templatefilters, util, match
81 81 from mercurial.hgweb import webcommands
82 82 from mercurial.node import nullid
83 83 from mercurial.i18n import _
84 84 import re, shutil, tempfile
85 85
86 86 commands.optionalrepo += ' kwdemo'
87 87
88 88 # hg commands that do not act on keywords
89 89 nokwcommands = ('add addremove annotate bundle copy export grep incoming init'
90 90 ' log outgoing push rename rollback tip verify'
91 91 ' convert email glog')
92 92
93 93 # hg commands that trigger expansion only when writing to working dir,
94 94 # not when reading filelog, and unexpand when reading from working dir
95 95 restricted = ('merge record resolve qfold qimport qnew qpush qrefresh qrecord'
96 96 ' transplant')
97 97
98 98 # provide cvs-like UTC date filter
99 99 utcdate = lambda x: util.datestr((x[0], 0), '%Y/%m/%d %H:%M:%S')
100 100
101 101 # make keyword tools accessible
102 102 kwtools = {'templater': None, 'hgcmd': '', 'inc': [], 'exc': ['.hg*']}
103 103
104 104
105 105 class kwtemplater(object):
106 106 '''
107 107 Sets up keyword templates, corresponding keyword regex, and
108 108 provides keyword substitution functions.
109 109 '''
110 110 templates = {
111 111 'Revision': '{node|short}',
112 112 'Author': '{author|user}',
113 113 'Date': '{date|utcdate}',
114 114 'RCSfile': '{file|basename},v',
115 115 'RCSFile': '{file|basename},v', # kept for backwards compatibility
116 116 # with hg-keyword
117 117 'Source': '{root}/{file},v',
118 118 'Id': '{file|basename},v {node|short} {date|utcdate} {author|user}',
119 119 'Header': '{root}/{file},v {node|short} {date|utcdate} {author|user}',
120 120 }
121 121
122 122 def __init__(self, ui, repo):
123 123 self.ui = ui
124 124 self.repo = repo
125 125 self.match = match.match(repo.root, '', [],
126 126 kwtools['inc'], kwtools['exc'])
127 127 self.restrict = kwtools['hgcmd'] in restricted.split()
128 128
129 129 kwmaps = self.ui.configitems('keywordmaps')
130 130 if kwmaps: # override default templates
131 131 self.templates = dict((k, templater.parsestring(v, False))
132 132 for k, v in kwmaps)
133 133 escaped = map(re.escape, self.templates.keys())
134 134 kwpat = r'\$(%s)(: [^$\n\r]*? )??\$' % '|'.join(escaped)
135 135 self.re_kw = re.compile(kwpat)
136 136
137 137 templatefilters.filters['utcdate'] = utcdate
138 138
139 139 def substitute(self, data, path, ctx, subfunc):
140 140 '''Replaces keywords in data with expanded template.'''
141 141 def kwsub(mobj):
142 142 kw = mobj.group(1)
143 143 ct = cmdutil.changeset_templater(self.ui, self.repo,
144 144 False, None, '', False)
145 145 ct.use_template(self.templates[kw])
146 146 self.ui.pushbuffer()
147 147 ct.show(ctx, root=self.repo.root, file=path)
148 148 ekw = templatefilters.firstline(self.ui.popbuffer())
149 149 return '$%s: %s $' % (kw, ekw)
150 150 return subfunc(kwsub, data)
151 151
152 152 def expand(self, path, node, data):
153 153 '''Returns data with keywords expanded.'''
154 154 if not self.restrict and self.match(path) and not util.binary(data):
155 155 ctx = self.repo.filectx(path, fileid=node).changectx()
156 156 return self.substitute(data, path, ctx, self.re_kw.sub)
157 157 return data
158 158
159 159 def iskwfile(self, path, flagfunc):
160 160 '''Returns true if path matches [keyword] pattern
161 161 and is not a symbolic link.
162 162 Caveat: localrepository._link fails on Windows.'''
163 163 return self.match(path) and not 'l' in flagfunc(path)
164 164
165 165 def overwrite(self, node, expand, candidates):
166 166 '''Overwrites selected files expanding/shrinking keywords.'''
167 167 ctx = self.repo[node]
168 168 mf = ctx.manifest()
169 169 if node is not None: # commit
170 170 candidates = [f for f in ctx.files() if f in mf]
171 171 candidates = [f for f in candidates if self.iskwfile(f, ctx.flags)]
172 172 if candidates:
173 173 self.restrict = True # do not expand when reading
174 174 msg = (expand and _('overwriting %s expanding keywords\n')
175 175 or _('overwriting %s shrinking keywords\n'))
176 176 for f in candidates:
177 177 fp = self.repo.file(f)
178 178 data = fp.read(mf[f])
179 179 if util.binary(data):
180 180 continue
181 181 if expand:
182 182 if node is None:
183 183 ctx = self.repo.filectx(f, fileid=mf[f]).changectx()
184 184 data, found = self.substitute(data, f, ctx,
185 185 self.re_kw.subn)
186 186 else:
187 187 found = self.re_kw.search(data)
188 188 if found:
189 189 self.ui.note(msg % f)
190 190 self.repo.wwrite(f, data, mf.flags(f))
191 191 if node is None:
192 192 self.repo.dirstate.normal(f)
193 193 self.restrict = False
194 194
195 195 def shrinktext(self, text):
196 196 '''Unconditionally removes all keyword substitutions from text.'''
197 197 return self.re_kw.sub(r'$\1$', text)
198 198
199 199 def shrink(self, fname, text):
200 200 '''Returns text with all keyword substitutions removed.'''
201 201 if self.match(fname) and not util.binary(text):
202 202 return self.shrinktext(text)
203 203 return text
204 204
205 205 def shrinklines(self, fname, lines):
206 206 '''Returns lines with keyword substitutions removed.'''
207 207 if self.match(fname):
208 208 text = ''.join(lines)
209 209 if not util.binary(text):
210 210 return self.shrinktext(text).splitlines(True)
211 211 return lines
212 212
213 213 def wread(self, fname, data):
214 214 '''If in restricted mode returns data read from wdir with
215 215 keyword substitutions removed.'''
216 216 return self.restrict and self.shrink(fname, data) or data
217 217
218 218 class kwfilelog(filelog.filelog):
219 219 '''
220 220 Subclass of filelog to hook into its read, add, cmp methods.
221 221 Keywords are "stored" unexpanded, and processed on reading.
222 222 '''
223 223 def __init__(self, opener, kwt, path):
224 224 super(kwfilelog, self).__init__(opener, path)
225 225 self.kwt = kwt
226 226 self.path = path
227 227
228 228 def read(self, node):
229 229 '''Expands keywords when reading filelog.'''
230 230 data = super(kwfilelog, self).read(node)
231 231 return self.kwt.expand(self.path, node, data)
232 232
233 233 def add(self, text, meta, tr, link, p1=None, p2=None):
234 234 '''Removes keyword substitutions when adding to filelog.'''
235 235 text = self.kwt.shrink(self.path, text)
236 236 return super(kwfilelog, self).add(text, meta, tr, link, p1, p2)
237 237
238 238 def cmp(self, node, text):
239 239 '''Removes keyword substitutions for comparison.'''
240 240 text = self.kwt.shrink(self.path, text)
241 241 if self.renamed(node):
242 242 t2 = super(kwfilelog, self).read(node)
243 243 return t2 != text
244 244 return revlog.revlog.cmp(self, node, text)
245 245
246 246 def _status(ui, repo, kwt, *pats, **opts):
247 247 '''Bails out if [keyword] configuration is not active.
248 248 Returns status of working directory.'''
249 249 if kwt:
250 250 return repo.status(match=cmdutil.match(repo, pats, opts), clean=True,
251 251 unknown=opts.get('unknown') or opts.get('all'))
252 252 if ui.configitems('keyword'):
253 253 raise util.Abort(_('[keyword] patterns cannot match'))
254 254 raise util.Abort(_('no [keyword] patterns configured'))
255 255
256 256 def _kwfwrite(ui, repo, expand, *pats, **opts):
257 257 '''Selects files and passes them to kwtemplater.overwrite.'''
258 258 if repo.dirstate.parents()[1] != nullid:
259 259 raise util.Abort(_('outstanding uncommitted merge'))
260 260 kwt = kwtools['templater']
261 261 wlock = repo.wlock()
262 262 try:
263 263 status = _status(ui, repo, kwt, *pats, **opts)
264 264 modified, added, removed, deleted, unknown, ignored, clean = status
265 265 if modified or added or removed or deleted:
266 266 raise util.Abort(_('outstanding uncommitted changes'))
267 267 kwt.overwrite(None, expand, clean)
268 268 finally:
269 269 wlock.release()
270 270
271 271 def demo(ui, repo, *args, **opts):
272 272 '''print [keywordmaps] configuration and an expansion example
273 273
274 274 Show current, custom, or default keyword template maps and their
275 275 expansions.
276 276
277 277 Extend the current configuration by specifying maps as arguments
278 278 and using -f/--rcfile to source an external hgrc file.
279 279
280 280 Use -d/--default to disable current configuration.
281 281
282 282 See "hg help templates" for information on templates and filters.
283 283 '''
284 284 def demoitems(section, items):
285 285 ui.write('[%s]\n' % section)
286 286 for k, v in sorted(items):
287 287 ui.write('%s = %s\n' % (k, v))
288 288
289 289 fn = 'demo.txt'
290 290 tmpdir = tempfile.mkdtemp('', 'kwdemo.')
291 291 ui.note(_('creating temporary repository at %s\n') % tmpdir)
292 292 repo = localrepo.localrepository(ui, tmpdir, True)
293 293 ui.setconfig('keyword', fn, '')
294 294
295 295 uikwmaps = ui.configitems('keywordmaps')
296 296 if args or opts.get('rcfile'):
297 297 ui.status(_('\n\tconfiguration using custom keyword template maps\n'))
298 298 if uikwmaps:
299 299 ui.status(_('\textending current template maps\n'))
300 300 if opts.get('default') or not uikwmaps:
301 301 ui.status(_('\toverriding default template maps\n'))
302 302 if opts.get('rcfile'):
303 303 ui.readconfig(opts.get('rcfile'))
304 304 if args:
305 305 # simulate hgrc parsing
306 306 rcmaps = ['[keywordmaps]\n'] + [a + '\n' for a in args]
307 307 fp = repo.opener('hgrc', 'w')
308 308 fp.writelines(rcmaps)
309 309 fp.close()
310 310 ui.readconfig(repo.join('hgrc'))
311 311 kwmaps = dict(ui.configitems('keywordmaps'))
312 312 elif opts.get('default'):
313 313 ui.status(_('\n\tconfiguration using default keyword template maps\n'))
314 314 kwmaps = kwtemplater.templates
315 315 if uikwmaps:
316 316 ui.status(_('\tdisabling current template maps\n'))
317 317 for k, v in kwmaps.iteritems():
318 318 ui.setconfig('keywordmaps', k, v)
319 319 else:
320 320 ui.status(_('\n\tconfiguration using current keyword template maps\n'))
321 321 kwmaps = dict(uikwmaps) or kwtemplater.templates
322 322
323 323 uisetup(ui)
324 324 reposetup(ui, repo)
325 325 ui.write('[extensions]\nkeyword =\n')
326 326 demoitems('keyword', ui.configitems('keyword'))
327 327 demoitems('keywordmaps', kwmaps.iteritems())
328 328 keywords = '$' + '$\n$'.join(sorted(kwmaps.keys())) + '$\n'
329 329 repo.wopener(fn, 'w').write(keywords)
330 330 repo.add([fn])
331 331 ui.note(_('\nkeywords written to %s:\n') % fn)
332 332 ui.note(keywords)
333 333 repo.dirstate.setbranch('demobranch')
334 334 for name, cmd in ui.configitems('hooks'):
335 335 if name.split('.', 1)[0].find('commit') > -1:
336 336 repo.ui.setconfig('hooks', name, '')
337 337 msg = _('hg keyword configuration and expansion example')
338 338 ui.note("hg ci -m '%s'\n" % msg)
339 339 repo.commit(text=msg)
340 340 ui.status(_('\n\tkeywords expanded\n'))
341 341 ui.write(repo.wread(fn))
342 342 shutil.rmtree(tmpdir, ignore_errors=True)
343 343
344 344 def expand(ui, repo, *pats, **opts):
345 345 '''expand keywords in the working directory
346 346
347 347 Run after (re)enabling keyword expansion.
348 348
349 349 kwexpand refuses to run if given files contain local changes.
350 350 '''
351 351 # 3rd argument sets expansion to True
352 352 _kwfwrite(ui, repo, True, *pats, **opts)
353 353
354 354 def files(ui, repo, *pats, **opts):
355 355 '''show files configured for keyword expansion
356 356
357 357 List which files in the working directory are matched by the
358 358 [keyword] configuration patterns.
359 359
360 360 Useful to prevent inadvertent keyword expansion and to speed up
361 361 execution by including only files that are actual candidates for
362 362 expansion.
363 363
364 See "hg help keyword" on how to construct patterns both for
364 See :hg:`help keyword` on how to construct patterns both for
365 365 inclusion and exclusion of files.
366 366
367 367 With -A/--all and -v/--verbose the codes used to show the status
368 368 of files are::
369 369
370 370 K = keyword expansion candidate
371 371 k = keyword expansion candidate (not tracked)
372 372 I = ignored
373 373 i = ignored (not tracked)
374 374 '''
375 375 kwt = kwtools['templater']
376 376 status = _status(ui, repo, kwt, *pats, **opts)
377 377 cwd = pats and repo.getcwd() or ''
378 378 modified, added, removed, deleted, unknown, ignored, clean = status
379 379 files = []
380 380 if not opts.get('unknown') or opts.get('all'):
381 381 files = sorted(modified + added + clean)
382 382 wctx = repo[None]
383 383 kwfiles = [f for f in files if kwt.iskwfile(f, wctx.flags)]
384 384 kwunknown = [f for f in unknown if kwt.iskwfile(f, wctx.flags)]
385 385 if not opts.get('ignore') or opts.get('all'):
386 386 showfiles = kwfiles, kwunknown
387 387 else:
388 388 showfiles = [], []
389 389 if opts.get('all') or opts.get('ignore'):
390 390 showfiles += ([f for f in files if f not in kwfiles],
391 391 [f for f in unknown if f not in kwunknown])
392 392 for char, filenames in zip('KkIi', showfiles):
393 393 fmt = (opts.get('all') or ui.verbose) and '%s %%s\n' % char or '%s\n'
394 394 for f in filenames:
395 395 ui.write(fmt % repo.pathto(f, cwd))
396 396
397 397 def shrink(ui, repo, *pats, **opts):
398 398 '''revert expanded keywords in the working directory
399 399
400 400 Run before changing/disabling active keywords or if you experience
401 problems with "hg import" or "hg merge".
401 problems with :hg:`import` or :hg:`merge`.
402 402
403 403 kwshrink refuses to run if given files contain local changes.
404 404 '''
405 405 # 3rd argument sets expansion to False
406 406 _kwfwrite(ui, repo, False, *pats, **opts)
407 407
408 408
409 409 def uisetup(ui):
410 410 '''Collects [keyword] config in kwtools.
411 411 Monkeypatches dispatch._parse if needed.'''
412 412
413 413 for pat, opt in ui.configitems('keyword'):
414 414 if opt != 'ignore':
415 415 kwtools['inc'].append(pat)
416 416 else:
417 417 kwtools['exc'].append(pat)
418 418
419 419 if kwtools['inc']:
420 420 def kwdispatch_parse(orig, ui, args):
421 421 '''Monkeypatch dispatch._parse to obtain running hg command.'''
422 422 cmd, func, args, options, cmdoptions = orig(ui, args)
423 423 kwtools['hgcmd'] = cmd
424 424 return cmd, func, args, options, cmdoptions
425 425
426 426 extensions.wrapfunction(dispatch, '_parse', kwdispatch_parse)
427 427
428 428 def reposetup(ui, repo):
429 429 '''Sets up repo as kwrepo for keyword substitution.
430 430 Overrides file method to return kwfilelog instead of filelog
431 431 if file matches user configuration.
432 432 Wraps commit to overwrite configured files with updated
433 433 keyword substitutions.
434 434 Monkeypatches patch and webcommands.'''
435 435
436 436 try:
437 437 if (not repo.local() or not kwtools['inc']
438 438 or kwtools['hgcmd'] in nokwcommands.split()
439 439 or '.hg' in util.splitpath(repo.root)
440 440 or repo._url.startswith('bundle:')):
441 441 return
442 442 except AttributeError:
443 443 pass
444 444
445 445 kwtools['templater'] = kwt = kwtemplater(ui, repo)
446 446
447 447 class kwrepo(repo.__class__):
448 448 def file(self, f):
449 449 if f[0] == '/':
450 450 f = f[1:]
451 451 return kwfilelog(self.sopener, kwt, f)
452 452
453 453 def wread(self, filename):
454 454 data = super(kwrepo, self).wread(filename)
455 455 return kwt.wread(filename, data)
456 456
457 457 def commit(self, *args, **opts):
458 458 # use custom commitctx for user commands
459 459 # other extensions can still wrap repo.commitctx directly
460 460 self.commitctx = self.kwcommitctx
461 461 try:
462 462 return super(kwrepo, self).commit(*args, **opts)
463 463 finally:
464 464 del self.commitctx
465 465
466 466 def kwcommitctx(self, ctx, error=False):
467 467 n = super(kwrepo, self).commitctx(ctx, error)
468 468 # no lock needed, only called from repo.commit() which already locks
469 469 kwt.overwrite(n, True, None)
470 470 return n
471 471
472 472 # monkeypatches
473 473 def kwpatchfile_init(orig, self, ui, fname, opener,
474 474 missing=False, eolmode=None):
475 475 '''Monkeypatch/wrap patch.patchfile.__init__ to avoid
476 476 rejects or conflicts due to expanded keywords in working dir.'''
477 477 orig(self, ui, fname, opener, missing, eolmode)
478 478 # shrink keywords read from working dir
479 479 self.lines = kwt.shrinklines(self.fname, self.lines)
480 480
481 481 def kw_diff(orig, repo, node1=None, node2=None, match=None, changes=None,
482 482 opts=None):
483 483 '''Monkeypatch patch.diff to avoid expansion except when
484 484 comparing against working dir.'''
485 485 if node2 is not None:
486 486 kwt.match = util.never
487 487 elif node1 is not None and node1 != repo['.'].node():
488 488 kwt.restrict = True
489 489 return orig(repo, node1, node2, match, changes, opts)
490 490
491 491 def kwweb_skip(orig, web, req, tmpl):
492 492 '''Wraps webcommands.x turning off keyword expansion.'''
493 493 kwt.match = util.never
494 494 return orig(web, req, tmpl)
495 495
496 496 repo.__class__ = kwrepo
497 497
498 498 extensions.wrapfunction(patch.patchfile, '__init__', kwpatchfile_init)
499 499 if not kwt.restrict:
500 500 extensions.wrapfunction(patch, 'diff', kw_diff)
501 501 for c in 'annotate changeset rev filediff diff'.split():
502 502 extensions.wrapfunction(webcommands, c, kwweb_skip)
503 503
504 504 cmdtable = {
505 505 'kwdemo':
506 506 (demo,
507 507 [('d', 'default', None, _('show default keyword template maps')),
508 508 ('f', 'rcfile', '', _('read maps from rcfile'))],
509 509 _('hg kwdemo [-d] [-f RCFILE] [TEMPLATEMAP]...')),
510 510 'kwexpand': (expand, commands.walkopts,
511 511 _('hg kwexpand [OPTION]... [FILE]...')),
512 512 'kwfiles':
513 513 (files,
514 514 [('A', 'all', None, _('show keyword status flags of all files')),
515 515 ('i', 'ignore', None, _('show files excluded from expansion')),
516 516 ('u', 'unknown', None, _('only show unknown (not tracked) files')),
517 517 ] + commands.walkopts,
518 518 _('hg kwfiles [OPTION]... [FILE]...')),
519 519 'kwshrink': (shrink, commands.walkopts,
520 520 _('hg kwshrink [OPTION]... [FILE]...')),
521 521 }
@@ -1,2822 +1,2822
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 Common tasks (use "hg help command" for more details)::
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
42 42 from mercurial.i18n import _
43 43 from mercurial.node import bin, hex, short, nullid, nullrev
44 44 from mercurial.lock import release
45 45 from mercurial import commands, cmdutil, hg, patch, util
46 46 from mercurial import repair, extensions, url, error
47 47 import os, sys, re, errno
48 48
49 49 commands.norepo += " qclone"
50 50
51 51 # Patch names looks like unix-file names.
52 52 # They must be joinable with queue directory and result in the patch path.
53 53 normname = util.normpath
54 54
55 55 class statusentry(object):
56 56 def __init__(self, node, name):
57 57 self.node, self.name = node, name
58 58
59 59 def __str__(self):
60 60 return hex(self.node) + ':' + self.name
61 61
62 62 class patchheader(object):
63 63 def __init__(self, pf, plainmode=False):
64 64 def eatdiff(lines):
65 65 while lines:
66 66 l = lines[-1]
67 67 if (l.startswith("diff -") or
68 68 l.startswith("Index:") or
69 69 l.startswith("===========")):
70 70 del lines[-1]
71 71 else:
72 72 break
73 73 def eatempty(lines):
74 74 while lines:
75 75 if not lines[-1].strip():
76 76 del lines[-1]
77 77 else:
78 78 break
79 79
80 80 message = []
81 81 comments = []
82 82 user = None
83 83 date = None
84 84 parent = None
85 85 format = None
86 86 subject = None
87 87 diffstart = 0
88 88
89 89 for line in file(pf):
90 90 line = line.rstrip()
91 91 if (line.startswith('diff --git')
92 92 or (diffstart and line.startswith('+++ '))):
93 93 diffstart = 2
94 94 break
95 95 diffstart = 0 # reset
96 96 if line.startswith("--- "):
97 97 diffstart = 1
98 98 continue
99 99 elif format == "hgpatch":
100 100 # parse values when importing the result of an hg export
101 101 if line.startswith("# User "):
102 102 user = line[7:]
103 103 elif line.startswith("# Date "):
104 104 date = line[7:]
105 105 elif line.startswith("# Parent "):
106 106 parent = line[9:]
107 107 elif not line.startswith("# ") and line:
108 108 message.append(line)
109 109 format = None
110 110 elif line == '# HG changeset patch':
111 111 message = []
112 112 format = "hgpatch"
113 113 elif (format != "tagdone" and (line.startswith("Subject: ") or
114 114 line.startswith("subject: "))):
115 115 subject = line[9:]
116 116 format = "tag"
117 117 elif (format != "tagdone" and (line.startswith("From: ") or
118 118 line.startswith("from: "))):
119 119 user = line[6:]
120 120 format = "tag"
121 121 elif (format != "tagdone" and (line.startswith("Date: ") or
122 122 line.startswith("date: "))):
123 123 date = line[6:]
124 124 format = "tag"
125 125 elif format == "tag" and line == "":
126 126 # when looking for tags (subject: from: etc) they
127 127 # end once you find a blank line in the source
128 128 format = "tagdone"
129 129 elif message or line:
130 130 message.append(line)
131 131 comments.append(line)
132 132
133 133 eatdiff(message)
134 134 eatdiff(comments)
135 135 eatempty(message)
136 136 eatempty(comments)
137 137
138 138 # make sure message isn't empty
139 139 if format and format.startswith("tag") and subject:
140 140 message.insert(0, "")
141 141 message.insert(0, subject)
142 142
143 143 self.message = message
144 144 self.comments = comments
145 145 self.user = user
146 146 self.date = date
147 147 self.parent = parent
148 148 self.haspatch = diffstart > 1
149 149 self.plainmode = plainmode
150 150
151 151 def setuser(self, user):
152 152 if not self.updateheader(['From: ', '# User '], user):
153 153 try:
154 154 patchheaderat = self.comments.index('# HG changeset patch')
155 155 self.comments.insert(patchheaderat + 1, '# User ' + user)
156 156 except ValueError:
157 157 if self.plainmode or self._hasheader(['Date: ']):
158 158 self.comments = ['From: ' + user] + self.comments
159 159 else:
160 160 tmp = ['# HG changeset patch', '# User ' + user, '']
161 161 self.comments = tmp + self.comments
162 162 self.user = user
163 163
164 164 def setdate(self, date):
165 165 if not self.updateheader(['Date: ', '# Date '], date):
166 166 try:
167 167 patchheaderat = self.comments.index('# HG changeset patch')
168 168 self.comments.insert(patchheaderat + 1, '# Date ' + date)
169 169 except ValueError:
170 170 if self.plainmode or self._hasheader(['From: ']):
171 171 self.comments = ['Date: ' + date] + self.comments
172 172 else:
173 173 tmp = ['# HG changeset patch', '# Date ' + date, '']
174 174 self.comments = tmp + self.comments
175 175 self.date = date
176 176
177 177 def setparent(self, parent):
178 178 if not self.updateheader(['# Parent '], parent):
179 179 try:
180 180 patchheaderat = self.comments.index('# HG changeset patch')
181 181 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
182 182 except ValueError:
183 183 pass
184 184 self.parent = parent
185 185
186 186 def setmessage(self, message):
187 187 if self.comments:
188 188 self._delmsg()
189 189 self.message = [message]
190 190 self.comments += self.message
191 191
192 192 def updateheader(self, prefixes, new):
193 193 '''Update all references to a field in the patch header.
194 194 Return whether the field is present.'''
195 195 res = False
196 196 for prefix in prefixes:
197 197 for i in xrange(len(self.comments)):
198 198 if self.comments[i].startswith(prefix):
199 199 self.comments[i] = prefix + new
200 200 res = True
201 201 break
202 202 return res
203 203
204 204 def _hasheader(self, prefixes):
205 205 '''Check if a header starts with any of the given prefixes.'''
206 206 for prefix in prefixes:
207 207 for comment in self.comments:
208 208 if comment.startswith(prefix):
209 209 return True
210 210 return False
211 211
212 212 def __str__(self):
213 213 if not self.comments:
214 214 return ''
215 215 return '\n'.join(self.comments) + '\n\n'
216 216
217 217 def _delmsg(self):
218 218 '''Remove existing message, keeping the rest of the comments fields.
219 219 If comments contains 'subject: ', message will prepend
220 220 the field and a blank line.'''
221 221 if self.message:
222 222 subj = 'subject: ' + self.message[0].lower()
223 223 for i in xrange(len(self.comments)):
224 224 if subj == self.comments[i].lower():
225 225 del self.comments[i]
226 226 self.message = self.message[2:]
227 227 break
228 228 ci = 0
229 229 for mi in self.message:
230 230 while mi != self.comments[ci]:
231 231 ci += 1
232 232 del self.comments[ci]
233 233
234 234 class queue(object):
235 235 def __init__(self, ui, path, patchdir=None):
236 236 self.basepath = path
237 237 self.path = patchdir or os.path.join(path, "patches")
238 238 self.opener = util.opener(self.path)
239 239 self.ui = ui
240 240 self.applied_dirty = 0
241 241 self.series_dirty = 0
242 242 self.series_path = "series"
243 243 self.status_path = "status"
244 244 self.guards_path = "guards"
245 245 self.active_guards = None
246 246 self.guards_dirty = False
247 247 # Handle mq.git as a bool with extended values
248 248 try:
249 249 gitmode = ui.configbool('mq', 'git', None)
250 250 if gitmode is None:
251 251 raise error.ConfigError()
252 252 self.gitmode = gitmode and 'yes' or 'no'
253 253 except error.ConfigError:
254 254 self.gitmode = ui.config('mq', 'git', 'auto').lower()
255 255 self.plainmode = ui.configbool('mq', 'plain', False)
256 256
257 257 @util.propertycache
258 258 def applied(self):
259 259 if os.path.exists(self.join(self.status_path)):
260 260 def parse(l):
261 261 n, name = l.split(':', 1)
262 262 return statusentry(bin(n), name)
263 263 lines = self.opener(self.status_path).read().splitlines()
264 264 return [parse(l) for l in lines]
265 265 return []
266 266
267 267 @util.propertycache
268 268 def full_series(self):
269 269 if os.path.exists(self.join(self.series_path)):
270 270 return self.opener(self.series_path).read().splitlines()
271 271 return []
272 272
273 273 @util.propertycache
274 274 def series(self):
275 275 self.parse_series()
276 276 return self.series
277 277
278 278 @util.propertycache
279 279 def series_guards(self):
280 280 self.parse_series()
281 281 return self.series_guards
282 282
283 283 def invalidate(self):
284 284 for a in 'applied full_series series series_guards'.split():
285 285 if a in self.__dict__:
286 286 delattr(self, a)
287 287 self.applied_dirty = 0
288 288 self.series_dirty = 0
289 289 self.guards_dirty = False
290 290 self.active_guards = None
291 291
292 292 def diffopts(self, opts={}, patchfn=None):
293 293 diffopts = patch.diffopts(self.ui, opts)
294 294 if self.gitmode == 'auto':
295 295 diffopts.upgrade = True
296 296 elif self.gitmode == 'keep':
297 297 pass
298 298 elif self.gitmode in ('yes', 'no'):
299 299 diffopts.git = self.gitmode == 'yes'
300 300 else:
301 301 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
302 302 ' got %s') % self.gitmode)
303 303 if patchfn:
304 304 diffopts = self.patchopts(diffopts, patchfn)
305 305 return diffopts
306 306
307 307 def patchopts(self, diffopts, *patches):
308 308 """Return a copy of input diff options with git set to true if
309 309 referenced patch is a git patch and should be preserved as such.
310 310 """
311 311 diffopts = diffopts.copy()
312 312 if not diffopts.git and self.gitmode == 'keep':
313 313 for patchfn in patches:
314 314 patchf = self.opener(patchfn, 'r')
315 315 # if the patch was a git patch, refresh it as a git patch
316 316 for line in patchf:
317 317 if line.startswith('diff --git'):
318 318 diffopts.git = True
319 319 break
320 320 patchf.close()
321 321 return diffopts
322 322
323 323 def join(self, *p):
324 324 return os.path.join(self.path, *p)
325 325
326 326 def find_series(self, patch):
327 327 def matchpatch(l):
328 328 l = l.split('#', 1)[0]
329 329 return l.strip() == patch
330 330 for index, l in enumerate(self.full_series):
331 331 if matchpatch(l):
332 332 return index
333 333 return None
334 334
335 335 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
336 336
337 337 def parse_series(self):
338 338 self.series = []
339 339 self.series_guards = []
340 340 for l in self.full_series:
341 341 h = l.find('#')
342 342 if h == -1:
343 343 patch = l
344 344 comment = ''
345 345 elif h == 0:
346 346 continue
347 347 else:
348 348 patch = l[:h]
349 349 comment = l[h:]
350 350 patch = patch.strip()
351 351 if patch:
352 352 if patch in self.series:
353 353 raise util.Abort(_('%s appears more than once in %s') %
354 354 (patch, self.join(self.series_path)))
355 355 self.series.append(patch)
356 356 self.series_guards.append(self.guard_re.findall(comment))
357 357
358 358 def check_guard(self, guard):
359 359 if not guard:
360 360 return _('guard cannot be an empty string')
361 361 bad_chars = '# \t\r\n\f'
362 362 first = guard[0]
363 363 if first in '-+':
364 364 return (_('guard %r starts with invalid character: %r') %
365 365 (guard, first))
366 366 for c in bad_chars:
367 367 if c in guard:
368 368 return _('invalid character in guard %r: %r') % (guard, c)
369 369
370 370 def set_active(self, guards):
371 371 for guard in guards:
372 372 bad = self.check_guard(guard)
373 373 if bad:
374 374 raise util.Abort(bad)
375 375 guards = sorted(set(guards))
376 376 self.ui.debug('active guards: %s\n' % ' '.join(guards))
377 377 self.active_guards = guards
378 378 self.guards_dirty = True
379 379
380 380 def active(self):
381 381 if self.active_guards is None:
382 382 self.active_guards = []
383 383 try:
384 384 guards = self.opener(self.guards_path).read().split()
385 385 except IOError, err:
386 386 if err.errno != errno.ENOENT:
387 387 raise
388 388 guards = []
389 389 for i, guard in enumerate(guards):
390 390 bad = self.check_guard(guard)
391 391 if bad:
392 392 self.ui.warn('%s:%d: %s\n' %
393 393 (self.join(self.guards_path), i + 1, bad))
394 394 else:
395 395 self.active_guards.append(guard)
396 396 return self.active_guards
397 397
398 398 def set_guards(self, idx, guards):
399 399 for g in guards:
400 400 if len(g) < 2:
401 401 raise util.Abort(_('guard %r too short') % g)
402 402 if g[0] not in '-+':
403 403 raise util.Abort(_('guard %r starts with invalid char') % g)
404 404 bad = self.check_guard(g[1:])
405 405 if bad:
406 406 raise util.Abort(bad)
407 407 drop = self.guard_re.sub('', self.full_series[idx])
408 408 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
409 409 self.parse_series()
410 410 self.series_dirty = True
411 411
412 412 def pushable(self, idx):
413 413 if isinstance(idx, str):
414 414 idx = self.series.index(idx)
415 415 patchguards = self.series_guards[idx]
416 416 if not patchguards:
417 417 return True, None
418 418 guards = self.active()
419 419 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
420 420 if exactneg:
421 421 return False, exactneg[0]
422 422 pos = [g for g in patchguards if g[0] == '+']
423 423 exactpos = [g for g in pos if g[1:] in guards]
424 424 if pos:
425 425 if exactpos:
426 426 return True, exactpos[0]
427 427 return False, pos
428 428 return True, ''
429 429
430 430 def explain_pushable(self, idx, all_patches=False):
431 431 write = all_patches and self.ui.write or self.ui.warn
432 432 if all_patches or self.ui.verbose:
433 433 if isinstance(idx, str):
434 434 idx = self.series.index(idx)
435 435 pushable, why = self.pushable(idx)
436 436 if all_patches and pushable:
437 437 if why is None:
438 438 write(_('allowing %s - no guards in effect\n') %
439 439 self.series[idx])
440 440 else:
441 441 if not why:
442 442 write(_('allowing %s - no matching negative guards\n') %
443 443 self.series[idx])
444 444 else:
445 445 write(_('allowing %s - guarded by %r\n') %
446 446 (self.series[idx], why))
447 447 if not pushable:
448 448 if why:
449 449 write(_('skipping %s - guarded by %r\n') %
450 450 (self.series[idx], why))
451 451 else:
452 452 write(_('skipping %s - no matching guards\n') %
453 453 self.series[idx])
454 454
455 455 def save_dirty(self):
456 456 def write_list(items, path):
457 457 fp = self.opener(path, 'w')
458 458 for i in items:
459 459 fp.write("%s\n" % i)
460 460 fp.close()
461 461 if self.applied_dirty:
462 462 write_list(map(str, self.applied), self.status_path)
463 463 if self.series_dirty:
464 464 write_list(self.full_series, self.series_path)
465 465 if self.guards_dirty:
466 466 write_list(self.active_guards, self.guards_path)
467 467
468 468 def removeundo(self, repo):
469 469 undo = repo.sjoin('undo')
470 470 if not os.path.exists(undo):
471 471 return
472 472 try:
473 473 os.unlink(undo)
474 474 except OSError, inst:
475 475 self.ui.warn(_('error removing undo: %s\n') % str(inst))
476 476
477 477 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
478 478 fp=None, changes=None, opts={}):
479 479 stat = opts.get('stat')
480 480 if stat:
481 481 opts['unified'] = '0'
482 482
483 483 m = cmdutil.match(repo, files, opts)
484 484 if fp is None:
485 485 write = repo.ui.write
486 486 else:
487 487 def write(s, **kw):
488 488 fp.write(s)
489 489 if stat:
490 490 width = self.ui.interactive() and util.termwidth() or 80
491 491 chunks = patch.diff(repo, node1, node2, m, changes, diffopts)
492 492 for chunk, label in patch.diffstatui(util.iterlines(chunks),
493 493 width=width,
494 494 git=diffopts.git):
495 495 write(chunk, label=label)
496 496 else:
497 497 for chunk, label in patch.diffui(repo, node1, node2, m, changes,
498 498 diffopts):
499 499 write(chunk, label=label)
500 500
501 501 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
502 502 # first try just applying the patch
503 503 (err, n) = self.apply(repo, [patch], update_status=False,
504 504 strict=True, merge=rev)
505 505
506 506 if err == 0:
507 507 return (err, n)
508 508
509 509 if n is None:
510 510 raise util.Abort(_("apply failed for patch %s") % patch)
511 511
512 512 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
513 513
514 514 # apply failed, strip away that rev and merge.
515 515 hg.clean(repo, head)
516 516 self.strip(repo, n, update=False, backup='strip')
517 517
518 518 ctx = repo[rev]
519 519 ret = hg.merge(repo, rev)
520 520 if ret:
521 521 raise util.Abort(_("update returned %d") % ret)
522 522 n = repo.commit(ctx.description(), ctx.user(), force=True)
523 523 if n is None:
524 524 raise util.Abort(_("repo commit failed"))
525 525 try:
526 526 ph = patchheader(mergeq.join(patch), self.plainmode)
527 527 except:
528 528 raise util.Abort(_("unable to read %s") % patch)
529 529
530 530 diffopts = self.patchopts(diffopts, patch)
531 531 patchf = self.opener(patch, "w")
532 532 comments = str(ph)
533 533 if comments:
534 534 patchf.write(comments)
535 535 self.printdiff(repo, diffopts, head, n, fp=patchf)
536 536 patchf.close()
537 537 self.removeundo(repo)
538 538 return (0, n)
539 539
540 540 def qparents(self, repo, rev=None):
541 541 if rev is None:
542 542 (p1, p2) = repo.dirstate.parents()
543 543 if p2 == nullid:
544 544 return p1
545 545 if not self.applied:
546 546 return None
547 547 return self.applied[-1].node
548 548 p1, p2 = repo.changelog.parents(rev)
549 549 if p2 != nullid and p2 in [x.node for x in self.applied]:
550 550 return p2
551 551 return p1
552 552
553 553 def mergepatch(self, repo, mergeq, series, diffopts):
554 554 if not self.applied:
555 555 # each of the patches merged in will have two parents. This
556 556 # can confuse the qrefresh, qdiff, and strip code because it
557 557 # needs to know which parent is actually in the patch queue.
558 558 # so, we insert a merge marker with only one parent. This way
559 559 # the first patch in the queue is never a merge patch
560 560 #
561 561 pname = ".hg.patches.merge.marker"
562 562 n = repo.commit('[mq]: merge marker', force=True)
563 563 self.removeundo(repo)
564 564 self.applied.append(statusentry(n, pname))
565 565 self.applied_dirty = 1
566 566
567 567 head = self.qparents(repo)
568 568
569 569 for patch in series:
570 570 patch = mergeq.lookup(patch, strict=True)
571 571 if not patch:
572 572 self.ui.warn(_("patch %s does not exist\n") % patch)
573 573 return (1, None)
574 574 pushable, reason = self.pushable(patch)
575 575 if not pushable:
576 576 self.explain_pushable(patch, all_patches=True)
577 577 continue
578 578 info = mergeq.isapplied(patch)
579 579 if not info:
580 580 self.ui.warn(_("patch %s is not applied\n") % patch)
581 581 return (1, None)
582 582 rev = info[1]
583 583 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
584 584 if head:
585 585 self.applied.append(statusentry(head, patch))
586 586 self.applied_dirty = 1
587 587 if err:
588 588 return (err, head)
589 589 self.save_dirty()
590 590 return (0, head)
591 591
592 592 def patch(self, repo, patchfile):
593 593 '''Apply patchfile to the working directory.
594 594 patchfile: name of patch file'''
595 595 files = {}
596 596 try:
597 597 fuzz = patch.patch(patchfile, self.ui, strip=1, cwd=repo.root,
598 598 files=files, eolmode=None)
599 599 except Exception, inst:
600 600 self.ui.note(str(inst) + '\n')
601 601 if not self.ui.verbose:
602 602 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
603 603 return (False, files, False)
604 604
605 605 return (True, files, fuzz)
606 606
607 607 def apply(self, repo, series, list=False, update_status=True,
608 608 strict=False, patchdir=None, merge=None, all_files=None):
609 609 wlock = lock = tr = None
610 610 try:
611 611 wlock = repo.wlock()
612 612 lock = repo.lock()
613 613 tr = repo.transaction("qpush")
614 614 try:
615 615 ret = self._apply(repo, series, list, update_status,
616 616 strict, patchdir, merge, all_files=all_files)
617 617 tr.close()
618 618 self.save_dirty()
619 619 return ret
620 620 except:
621 621 try:
622 622 tr.abort()
623 623 finally:
624 624 repo.invalidate()
625 625 repo.dirstate.invalidate()
626 626 raise
627 627 finally:
628 628 del tr
629 629 release(lock, wlock)
630 630 self.removeundo(repo)
631 631
632 632 def _apply(self, repo, series, list=False, update_status=True,
633 633 strict=False, patchdir=None, merge=None, all_files=None):
634 634 '''returns (error, hash)
635 635 error = 1 for unable to read, 2 for patch failed, 3 for patch fuzz'''
636 636 # TODO unify with commands.py
637 637 if not patchdir:
638 638 patchdir = self.path
639 639 err = 0
640 640 n = None
641 641 for patchname in series:
642 642 pushable, reason = self.pushable(patchname)
643 643 if not pushable:
644 644 self.explain_pushable(patchname, all_patches=True)
645 645 continue
646 646 self.ui.status(_("applying %s\n") % patchname)
647 647 pf = os.path.join(patchdir, patchname)
648 648
649 649 try:
650 650 ph = patchheader(self.join(patchname), self.plainmode)
651 651 except:
652 652 self.ui.warn(_("unable to read %s\n") % patchname)
653 653 err = 1
654 654 break
655 655
656 656 message = ph.message
657 657 if not message:
658 658 message = "imported patch %s\n" % patchname
659 659 else:
660 660 if list:
661 661 message.append("\nimported patch %s" % patchname)
662 662 message = '\n'.join(message)
663 663
664 664 if ph.haspatch:
665 665 (patcherr, files, fuzz) = self.patch(repo, pf)
666 666 if all_files is not None:
667 667 all_files.update(files)
668 668 patcherr = not patcherr
669 669 else:
670 670 self.ui.warn(_("patch %s is empty\n") % patchname)
671 671 patcherr, files, fuzz = 0, [], 0
672 672
673 673 if merge and files:
674 674 # Mark as removed/merged and update dirstate parent info
675 675 removed = []
676 676 merged = []
677 677 for f in files:
678 678 if os.path.exists(repo.wjoin(f)):
679 679 merged.append(f)
680 680 else:
681 681 removed.append(f)
682 682 for f in removed:
683 683 repo.dirstate.remove(f)
684 684 for f in merged:
685 685 repo.dirstate.merge(f)
686 686 p1, p2 = repo.dirstate.parents()
687 687 repo.dirstate.setparents(p1, merge)
688 688
689 689 files = patch.updatedir(self.ui, repo, files)
690 690 match = cmdutil.matchfiles(repo, files or [])
691 691 n = repo.commit(message, ph.user, ph.date, match=match, force=True)
692 692
693 693 if n is None:
694 694 raise util.Abort(_("repo commit failed"))
695 695
696 696 if update_status:
697 697 self.applied.append(statusentry(n, patchname))
698 698
699 699 if patcherr:
700 700 self.ui.warn(_("patch failed, rejects left in working dir\n"))
701 701 err = 2
702 702 break
703 703
704 704 if fuzz and strict:
705 705 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
706 706 err = 3
707 707 break
708 708 return (err, n)
709 709
710 710 def _cleanup(self, patches, numrevs, keep=False):
711 711 if not keep:
712 712 r = self.qrepo()
713 713 if r:
714 714 r.remove(patches, True)
715 715 else:
716 716 for p in patches:
717 717 os.unlink(self.join(p))
718 718
719 719 if numrevs:
720 720 del self.applied[:numrevs]
721 721 self.applied_dirty = 1
722 722
723 723 for i in sorted([self.find_series(p) for p in patches], reverse=True):
724 724 del self.full_series[i]
725 725 self.parse_series()
726 726 self.series_dirty = 1
727 727
728 728 def _revpatches(self, repo, revs):
729 729 firstrev = repo[self.applied[0].node].rev()
730 730 patches = []
731 731 for i, rev in enumerate(revs):
732 732
733 733 if rev < firstrev:
734 734 raise util.Abort(_('revision %d is not managed') % rev)
735 735
736 736 ctx = repo[rev]
737 737 base = self.applied[i].node
738 738 if ctx.node() != base:
739 739 msg = _('cannot delete revision %d above applied patches')
740 740 raise util.Abort(msg % rev)
741 741
742 742 patch = self.applied[i].name
743 743 for fmt in ('[mq]: %s', 'imported patch %s'):
744 744 if ctx.description() == fmt % patch:
745 745 msg = _('patch %s finalized without changeset message\n')
746 746 repo.ui.status(msg % patch)
747 747 break
748 748
749 749 patches.append(patch)
750 750 return patches
751 751
752 752 def finish(self, repo, revs):
753 753 patches = self._revpatches(repo, sorted(revs))
754 754 self._cleanup(patches, len(patches))
755 755
756 756 def delete(self, repo, patches, opts):
757 757 if not patches and not opts.get('rev'):
758 758 raise util.Abort(_('qdelete requires at least one revision or '
759 759 'patch name'))
760 760
761 761 realpatches = []
762 762 for patch in patches:
763 763 patch = self.lookup(patch, strict=True)
764 764 info = self.isapplied(patch)
765 765 if info:
766 766 raise util.Abort(_("cannot delete applied patch %s") % patch)
767 767 if patch not in self.series:
768 768 raise util.Abort(_("patch %s not in series file") % patch)
769 769 realpatches.append(patch)
770 770
771 771 numrevs = 0
772 772 if opts.get('rev'):
773 773 if not self.applied:
774 774 raise util.Abort(_('no patches applied'))
775 775 revs = cmdutil.revrange(repo, opts['rev'])
776 776 if len(revs) > 1 and revs[0] > revs[1]:
777 777 revs.reverse()
778 778 revpatches = self._revpatches(repo, revs)
779 779 realpatches += revpatches
780 780 numrevs = len(revpatches)
781 781
782 782 self._cleanup(realpatches, numrevs, opts.get('keep'))
783 783
784 784 def check_toppatch(self, repo):
785 785 if self.applied:
786 786 top = self.applied[-1].node
787 787 patch = self.applied[-1].name
788 788 pp = repo.dirstate.parents()
789 789 if top not in pp:
790 790 raise util.Abort(_("working directory revision is not qtip"))
791 791 return top, patch
792 792 return None, None
793 793
794 794 def check_localchanges(self, repo, force=False, refresh=True):
795 795 m, a, r, d = repo.status()[:4]
796 796 if (m or a or r or d) and not force:
797 797 if refresh:
798 798 raise util.Abort(_("local changes found, refresh first"))
799 799 else:
800 800 raise util.Abort(_("local changes found"))
801 801 return m, a, r, d
802 802
803 803 _reserved = ('series', 'status', 'guards')
804 804 def check_reserved_name(self, name):
805 805 if (name in self._reserved or name.startswith('.hg')
806 806 or name.startswith('.mq') or '#' in name or ':' in name):
807 807 raise util.Abort(_('"%s" cannot be used as the name of a patch')
808 808 % name)
809 809
810 810 def new(self, repo, patchfn, *pats, **opts):
811 811 """options:
812 812 msg: a string or a no-argument function returning a string
813 813 """
814 814 msg = opts.get('msg')
815 815 user = opts.get('user')
816 816 date = opts.get('date')
817 817 if date:
818 818 date = util.parsedate(date)
819 819 diffopts = self.diffopts({'git': opts.get('git')})
820 820 self.check_reserved_name(patchfn)
821 821 if os.path.exists(self.join(patchfn)):
822 822 raise util.Abort(_('patch "%s" already exists') % patchfn)
823 823 if opts.get('include') or opts.get('exclude') or pats:
824 824 match = cmdutil.match(repo, pats, opts)
825 825 # detect missing files in pats
826 826 def badfn(f, msg):
827 827 raise util.Abort('%s: %s' % (f, msg))
828 828 match.bad = badfn
829 829 m, a, r, d = repo.status(match=match)[:4]
830 830 else:
831 831 m, a, r, d = self.check_localchanges(repo, force=True)
832 832 match = cmdutil.matchfiles(repo, m + a + r)
833 833 if len(repo[None].parents()) > 1:
834 834 raise util.Abort(_('cannot manage merge changesets'))
835 835 commitfiles = m + a + r
836 836 self.check_toppatch(repo)
837 837 insert = self.full_series_end()
838 838 wlock = repo.wlock()
839 839 try:
840 840 # if patch file write fails, abort early
841 841 p = self.opener(patchfn, "w")
842 842 try:
843 843 if self.plainmode:
844 844 if user:
845 845 p.write("From: " + user + "\n")
846 846 if not date:
847 847 p.write("\n")
848 848 if date:
849 849 p.write("Date: %d %d\n\n" % date)
850 850 else:
851 851 p.write("# HG changeset patch\n")
852 852 p.write("# Parent "
853 853 + hex(repo[None].parents()[0].node()) + "\n")
854 854 if user:
855 855 p.write("# User " + user + "\n")
856 856 if date:
857 857 p.write("# Date %s %s\n\n" % date)
858 858 if hasattr(msg, '__call__'):
859 859 msg = msg()
860 860 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
861 861 n = repo.commit(commitmsg, user, date, match=match, force=True)
862 862 if n is None:
863 863 raise util.Abort(_("repo commit failed"))
864 864 try:
865 865 self.full_series[insert:insert] = [patchfn]
866 866 self.applied.append(statusentry(n, patchfn))
867 867 self.parse_series()
868 868 self.series_dirty = 1
869 869 self.applied_dirty = 1
870 870 if msg:
871 871 msg = msg + "\n\n"
872 872 p.write(msg)
873 873 if commitfiles:
874 874 parent = self.qparents(repo, n)
875 875 chunks = patch.diff(repo, node1=parent, node2=n,
876 876 match=match, opts=diffopts)
877 877 for chunk in chunks:
878 878 p.write(chunk)
879 879 p.close()
880 880 wlock.release()
881 881 wlock = None
882 882 r = self.qrepo()
883 883 if r:
884 884 r.add([patchfn])
885 885 except:
886 886 repo.rollback()
887 887 raise
888 888 except Exception:
889 889 patchpath = self.join(patchfn)
890 890 try:
891 891 os.unlink(patchpath)
892 892 except:
893 893 self.ui.warn(_('error unlinking %s\n') % patchpath)
894 894 raise
895 895 self.removeundo(repo)
896 896 finally:
897 897 release(wlock)
898 898
899 899 def strip(self, repo, rev, update=True, backup="all", force=None):
900 900 wlock = lock = None
901 901 try:
902 902 wlock = repo.wlock()
903 903 lock = repo.lock()
904 904
905 905 if update:
906 906 self.check_localchanges(repo, force=force, refresh=False)
907 907 urev = self.qparents(repo, rev)
908 908 hg.clean(repo, urev)
909 909 repo.dirstate.write()
910 910
911 911 self.removeundo(repo)
912 912 repair.strip(self.ui, repo, rev, backup)
913 913 # strip may have unbundled a set of backed up revisions after
914 914 # the actual strip
915 915 self.removeundo(repo)
916 916 finally:
917 917 release(lock, wlock)
918 918
919 919 def isapplied(self, patch):
920 920 """returns (index, rev, patch)"""
921 921 for i, a in enumerate(self.applied):
922 922 if a.name == patch:
923 923 return (i, a.node, a.name)
924 924 return None
925 925
926 926 # if the exact patch name does not exist, we try a few
927 927 # variations. If strict is passed, we try only #1
928 928 #
929 929 # 1) a number to indicate an offset in the series file
930 930 # 2) a unique substring of the patch name was given
931 931 # 3) patchname[-+]num to indicate an offset in the series file
932 932 def lookup(self, patch, strict=False):
933 933 patch = patch and str(patch)
934 934
935 935 def partial_name(s):
936 936 if s in self.series:
937 937 return s
938 938 matches = [x for x in self.series if s in x]
939 939 if len(matches) > 1:
940 940 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
941 941 for m in matches:
942 942 self.ui.warn(' %s\n' % m)
943 943 return None
944 944 if matches:
945 945 return matches[0]
946 946 if self.series and self.applied:
947 947 if s == 'qtip':
948 948 return self.series[self.series_end(True)-1]
949 949 if s == 'qbase':
950 950 return self.series[0]
951 951 return None
952 952
953 953 if patch is None:
954 954 return None
955 955 if patch in self.series:
956 956 return patch
957 957
958 958 if not os.path.isfile(self.join(patch)):
959 959 try:
960 960 sno = int(patch)
961 961 except (ValueError, OverflowError):
962 962 pass
963 963 else:
964 964 if -len(self.series) <= sno < len(self.series):
965 965 return self.series[sno]
966 966
967 967 if not strict:
968 968 res = partial_name(patch)
969 969 if res:
970 970 return res
971 971 minus = patch.rfind('-')
972 972 if minus >= 0:
973 973 res = partial_name(patch[:minus])
974 974 if res:
975 975 i = self.series.index(res)
976 976 try:
977 977 off = int(patch[minus + 1:] or 1)
978 978 except (ValueError, OverflowError):
979 979 pass
980 980 else:
981 981 if i - off >= 0:
982 982 return self.series[i - off]
983 983 plus = patch.rfind('+')
984 984 if plus >= 0:
985 985 res = partial_name(patch[:plus])
986 986 if res:
987 987 i = self.series.index(res)
988 988 try:
989 989 off = int(patch[plus + 1:] or 1)
990 990 except (ValueError, OverflowError):
991 991 pass
992 992 else:
993 993 if i + off < len(self.series):
994 994 return self.series[i + off]
995 995 raise util.Abort(_("patch %s not in series") % patch)
996 996
997 997 def push(self, repo, patch=None, force=False, list=False,
998 998 mergeq=None, all=False):
999 999 diffopts = self.diffopts()
1000 1000 wlock = repo.wlock()
1001 1001 try:
1002 1002 heads = []
1003 1003 for b, ls in repo.branchmap().iteritems():
1004 1004 heads += ls
1005 1005 if not heads:
1006 1006 heads = [nullid]
1007 1007 if repo.dirstate.parents()[0] not in heads:
1008 1008 self.ui.status(_("(working directory not at a head)\n"))
1009 1009
1010 1010 if not self.series:
1011 1011 self.ui.warn(_('no patches in series\n'))
1012 1012 return 0
1013 1013
1014 1014 patch = self.lookup(patch)
1015 1015 # Suppose our series file is: A B C and the current 'top'
1016 1016 # patch is B. qpush C should be performed (moving forward)
1017 1017 # qpush B is a NOP (no change) qpush A is an error (can't
1018 1018 # go backwards with qpush)
1019 1019 if patch:
1020 1020 info = self.isapplied(patch)
1021 1021 if info:
1022 1022 if info[0] < len(self.applied) - 1:
1023 1023 raise util.Abort(
1024 1024 _("cannot push to a previous patch: %s") % patch)
1025 1025 self.ui.warn(
1026 1026 _('qpush: %s is already at the top\n') % patch)
1027 1027 return
1028 1028 pushable, reason = self.pushable(patch)
1029 1029 if not pushable:
1030 1030 if reason:
1031 1031 reason = _('guarded by %r') % reason
1032 1032 else:
1033 1033 reason = _('no matching guards')
1034 1034 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1035 1035 return 1
1036 1036 elif all:
1037 1037 patch = self.series[-1]
1038 1038 if self.isapplied(patch):
1039 1039 self.ui.warn(_('all patches are currently applied\n'))
1040 1040 return 0
1041 1041
1042 1042 # Following the above example, starting at 'top' of B:
1043 1043 # qpush should be performed (pushes C), but a subsequent
1044 1044 # qpush without an argument is an error (nothing to
1045 1045 # apply). This allows a loop of "...while hg qpush..." to
1046 1046 # work as it detects an error when done
1047 1047 start = self.series_end()
1048 1048 if start == len(self.series):
1049 1049 self.ui.warn(_('patch series already fully applied\n'))
1050 1050 return 1
1051 1051 if not force:
1052 1052 self.check_localchanges(repo)
1053 1053
1054 1054 self.applied_dirty = 1
1055 1055 if start > 0:
1056 1056 self.check_toppatch(repo)
1057 1057 if not patch:
1058 1058 patch = self.series[start]
1059 1059 end = start + 1
1060 1060 else:
1061 1061 end = self.series.index(patch, start) + 1
1062 1062
1063 1063 s = self.series[start:end]
1064 1064 all_files = set()
1065 1065 try:
1066 1066 if mergeq:
1067 1067 ret = self.mergepatch(repo, mergeq, s, diffopts)
1068 1068 else:
1069 1069 ret = self.apply(repo, s, list, all_files=all_files)
1070 1070 except:
1071 1071 self.ui.warn(_('cleaning up working directory...'))
1072 1072 node = repo.dirstate.parents()[0]
1073 1073 hg.revert(repo, node, None)
1074 1074 # only remove unknown files that we know we touched or
1075 1075 # created while patching
1076 1076 for f in all_files:
1077 1077 if f not in repo.dirstate:
1078 1078 try:
1079 1079 util.unlink(repo.wjoin(f))
1080 1080 except OSError, inst:
1081 1081 if inst.errno != errno.ENOENT:
1082 1082 raise
1083 1083 self.ui.warn(_('done\n'))
1084 1084 raise
1085 1085
1086 1086 if not self.applied:
1087 1087 return ret[0]
1088 1088 top = self.applied[-1].name
1089 1089 if ret[0] and ret[0] > 1:
1090 1090 msg = _("errors during apply, please fix and refresh %s\n")
1091 1091 self.ui.write(msg % top)
1092 1092 else:
1093 1093 self.ui.write(_("now at: %s\n") % top)
1094 1094 return ret[0]
1095 1095
1096 1096 finally:
1097 1097 wlock.release()
1098 1098
1099 1099 def pop(self, repo, patch=None, force=False, update=True, all=False):
1100 1100 wlock = repo.wlock()
1101 1101 try:
1102 1102 if patch:
1103 1103 # index, rev, patch
1104 1104 info = self.isapplied(patch)
1105 1105 if not info:
1106 1106 patch = self.lookup(patch)
1107 1107 info = self.isapplied(patch)
1108 1108 if not info:
1109 1109 raise util.Abort(_("patch %s is not applied") % patch)
1110 1110
1111 1111 if not self.applied:
1112 1112 # Allow qpop -a to work repeatedly,
1113 1113 # but not qpop without an argument
1114 1114 self.ui.warn(_("no patches applied\n"))
1115 1115 return not all
1116 1116
1117 1117 if all:
1118 1118 start = 0
1119 1119 elif patch:
1120 1120 start = info[0] + 1
1121 1121 else:
1122 1122 start = len(self.applied) - 1
1123 1123
1124 1124 if start >= len(self.applied):
1125 1125 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1126 1126 return
1127 1127
1128 1128 if not update:
1129 1129 parents = repo.dirstate.parents()
1130 1130 rr = [x.node for x in self.applied]
1131 1131 for p in parents:
1132 1132 if p in rr:
1133 1133 self.ui.warn(_("qpop: forcing dirstate update\n"))
1134 1134 update = True
1135 1135 else:
1136 1136 parents = [p.node() for p in repo[None].parents()]
1137 1137 needupdate = False
1138 1138 for entry in self.applied[start:]:
1139 1139 if entry.node in parents:
1140 1140 needupdate = True
1141 1141 break
1142 1142 update = needupdate
1143 1143
1144 1144 if not force and update:
1145 1145 self.check_localchanges(repo)
1146 1146
1147 1147 self.applied_dirty = 1
1148 1148 end = len(self.applied)
1149 1149 rev = self.applied[start].node
1150 1150 if update:
1151 1151 top = self.check_toppatch(repo)[0]
1152 1152
1153 1153 try:
1154 1154 heads = repo.changelog.heads(rev)
1155 1155 except error.LookupError:
1156 1156 node = short(rev)
1157 1157 raise util.Abort(_('trying to pop unknown node %s') % node)
1158 1158
1159 1159 if heads != [self.applied[-1].node]:
1160 1160 raise util.Abort(_("popping would remove a revision not "
1161 1161 "managed by this patch queue"))
1162 1162
1163 1163 # we know there are no local changes, so we can make a simplified
1164 1164 # form of hg.update.
1165 1165 if update:
1166 1166 qp = self.qparents(repo, rev)
1167 1167 ctx = repo[qp]
1168 1168 m, a, r, d = repo.status(qp, top)[:4]
1169 1169 if d:
1170 1170 raise util.Abort(_("deletions found between repo revs"))
1171 1171 for f in a:
1172 1172 try:
1173 1173 util.unlink(repo.wjoin(f))
1174 1174 except OSError, e:
1175 1175 if e.errno != errno.ENOENT:
1176 1176 raise
1177 1177 repo.dirstate.forget(f)
1178 1178 for f in m + r:
1179 1179 fctx = ctx[f]
1180 1180 repo.wwrite(f, fctx.data(), fctx.flags())
1181 1181 repo.dirstate.normal(f)
1182 1182 repo.dirstate.setparents(qp, nullid)
1183 1183 for patch in reversed(self.applied[start:end]):
1184 1184 self.ui.status(_("popping %s\n") % patch.name)
1185 1185 del self.applied[start:end]
1186 1186 self.strip(repo, rev, update=False, backup='strip')
1187 1187 if self.applied:
1188 1188 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1189 1189 else:
1190 1190 self.ui.write(_("patch queue now empty\n"))
1191 1191 finally:
1192 1192 wlock.release()
1193 1193
1194 1194 def diff(self, repo, pats, opts):
1195 1195 top, patch = self.check_toppatch(repo)
1196 1196 if not top:
1197 1197 self.ui.write(_("no patches applied\n"))
1198 1198 return
1199 1199 qp = self.qparents(repo, top)
1200 1200 if opts.get('reverse'):
1201 1201 node1, node2 = None, qp
1202 1202 else:
1203 1203 node1, node2 = qp, None
1204 1204 diffopts = self.diffopts(opts, patch)
1205 1205 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1206 1206
1207 1207 def refresh(self, repo, pats=None, **opts):
1208 1208 if not self.applied:
1209 1209 self.ui.write(_("no patches applied\n"))
1210 1210 return 1
1211 1211 msg = opts.get('msg', '').rstrip()
1212 1212 newuser = opts.get('user')
1213 1213 newdate = opts.get('date')
1214 1214 if newdate:
1215 1215 newdate = '%d %d' % util.parsedate(newdate)
1216 1216 wlock = repo.wlock()
1217 1217
1218 1218 try:
1219 1219 self.check_toppatch(repo)
1220 1220 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1221 1221 if repo.changelog.heads(top) != [top]:
1222 1222 raise util.Abort(_("cannot refresh a revision with children"))
1223 1223
1224 1224 cparents = repo.changelog.parents(top)
1225 1225 patchparent = self.qparents(repo, top)
1226 1226 ph = patchheader(self.join(patchfn), self.plainmode)
1227 1227 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1228 1228 if msg:
1229 1229 ph.setmessage(msg)
1230 1230 if newuser:
1231 1231 ph.setuser(newuser)
1232 1232 if newdate:
1233 1233 ph.setdate(newdate)
1234 1234 ph.setparent(hex(patchparent))
1235 1235
1236 1236 # only commit new patch when write is complete
1237 1237 patchf = self.opener(patchfn, 'w', atomictemp=True)
1238 1238
1239 1239 comments = str(ph)
1240 1240 if comments:
1241 1241 patchf.write(comments)
1242 1242
1243 1243 # update the dirstate in place, strip off the qtip commit
1244 1244 # and then commit.
1245 1245 #
1246 1246 # this should really read:
1247 1247 # mm, dd, aa, aa2 = repo.status(tip, patchparent)[:4]
1248 1248 # but we do it backwards to take advantage of manifest/chlog
1249 1249 # caching against the next repo.status call
1250 1250 mm, aa, dd, aa2 = repo.status(patchparent, top)[:4]
1251 1251 changes = repo.changelog.read(top)
1252 1252 man = repo.manifest.read(changes[0])
1253 1253 aaa = aa[:]
1254 1254 matchfn = cmdutil.match(repo, pats, opts)
1255 1255 # in short mode, we only diff the files included in the
1256 1256 # patch already plus specified files
1257 1257 if opts.get('short'):
1258 1258 # if amending a patch, we start with existing
1259 1259 # files plus specified files - unfiltered
1260 1260 match = cmdutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1261 1261 # filter with inc/exl options
1262 1262 matchfn = cmdutil.match(repo, opts=opts)
1263 1263 else:
1264 1264 match = cmdutil.matchall(repo)
1265 1265 m, a, r, d = repo.status(match=match)[:4]
1266 1266
1267 1267 # we might end up with files that were added between
1268 1268 # qtip and the dirstate parent, but then changed in the
1269 1269 # local dirstate. in this case, we want them to only
1270 1270 # show up in the added section
1271 1271 for x in m:
1272 1272 if x not in aa:
1273 1273 mm.append(x)
1274 1274 # we might end up with files added by the local dirstate that
1275 1275 # were deleted by the patch. In this case, they should only
1276 1276 # show up in the changed section.
1277 1277 for x in a:
1278 1278 if x in dd:
1279 1279 del dd[dd.index(x)]
1280 1280 mm.append(x)
1281 1281 else:
1282 1282 aa.append(x)
1283 1283 # make sure any files deleted in the local dirstate
1284 1284 # are not in the add or change column of the patch
1285 1285 forget = []
1286 1286 for x in d + r:
1287 1287 if x in aa:
1288 1288 del aa[aa.index(x)]
1289 1289 forget.append(x)
1290 1290 continue
1291 1291 elif x in mm:
1292 1292 del mm[mm.index(x)]
1293 1293 dd.append(x)
1294 1294
1295 1295 m = list(set(mm))
1296 1296 r = list(set(dd))
1297 1297 a = list(set(aa))
1298 1298 c = [filter(matchfn, l) for l in (m, a, r)]
1299 1299 match = cmdutil.matchfiles(repo, set(c[0] + c[1] + c[2]))
1300 1300 chunks = patch.diff(repo, patchparent, match=match,
1301 1301 changes=c, opts=diffopts)
1302 1302 for chunk in chunks:
1303 1303 patchf.write(chunk)
1304 1304
1305 1305 try:
1306 1306 if diffopts.git or diffopts.upgrade:
1307 1307 copies = {}
1308 1308 for dst in a:
1309 1309 src = repo.dirstate.copied(dst)
1310 1310 # during qfold, the source file for copies may
1311 1311 # be removed. Treat this as a simple add.
1312 1312 if src is not None and src in repo.dirstate:
1313 1313 copies.setdefault(src, []).append(dst)
1314 1314 repo.dirstate.add(dst)
1315 1315 # remember the copies between patchparent and qtip
1316 1316 for dst in aaa:
1317 1317 f = repo.file(dst)
1318 1318 src = f.renamed(man[dst])
1319 1319 if src:
1320 1320 copies.setdefault(src[0], []).extend(
1321 1321 copies.get(dst, []))
1322 1322 if dst in a:
1323 1323 copies[src[0]].append(dst)
1324 1324 # we can't copy a file created by the patch itself
1325 1325 if dst in copies:
1326 1326 del copies[dst]
1327 1327 for src, dsts in copies.iteritems():
1328 1328 for dst in dsts:
1329 1329 repo.dirstate.copy(src, dst)
1330 1330 else:
1331 1331 for dst in a:
1332 1332 repo.dirstate.add(dst)
1333 1333 # Drop useless copy information
1334 1334 for f in list(repo.dirstate.copies()):
1335 1335 repo.dirstate.copy(None, f)
1336 1336 for f in r:
1337 1337 repo.dirstate.remove(f)
1338 1338 # if the patch excludes a modified file, mark that
1339 1339 # file with mtime=0 so status can see it.
1340 1340 mm = []
1341 1341 for i in xrange(len(m)-1, -1, -1):
1342 1342 if not matchfn(m[i]):
1343 1343 mm.append(m[i])
1344 1344 del m[i]
1345 1345 for f in m:
1346 1346 repo.dirstate.normal(f)
1347 1347 for f in mm:
1348 1348 repo.dirstate.normallookup(f)
1349 1349 for f in forget:
1350 1350 repo.dirstate.forget(f)
1351 1351
1352 1352 if not msg:
1353 1353 if not ph.message:
1354 1354 message = "[mq]: %s\n" % patchfn
1355 1355 else:
1356 1356 message = "\n".join(ph.message)
1357 1357 else:
1358 1358 message = msg
1359 1359
1360 1360 user = ph.user or changes[1]
1361 1361
1362 1362 # assumes strip can roll itself back if interrupted
1363 1363 repo.dirstate.setparents(*cparents)
1364 1364 self.applied.pop()
1365 1365 self.applied_dirty = 1
1366 1366 self.strip(repo, top, update=False,
1367 1367 backup='strip')
1368 1368 except:
1369 1369 repo.dirstate.invalidate()
1370 1370 raise
1371 1371
1372 1372 try:
1373 1373 # might be nice to attempt to roll back strip after this
1374 1374 patchf.rename()
1375 1375 n = repo.commit(message, user, ph.date, match=match,
1376 1376 force=True)
1377 1377 self.applied.append(statusentry(n, patchfn))
1378 1378 except:
1379 1379 ctx = repo[cparents[0]]
1380 1380 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1381 1381 self.save_dirty()
1382 1382 self.ui.warn(_('refresh interrupted while patch was popped! '
1383 1383 '(revert --all, qpush to recover)\n'))
1384 1384 raise
1385 1385 finally:
1386 1386 wlock.release()
1387 1387 self.removeundo(repo)
1388 1388
1389 1389 def init(self, repo, create=False):
1390 1390 if not create and os.path.isdir(self.path):
1391 1391 raise util.Abort(_("patch queue directory already exists"))
1392 1392 try:
1393 1393 os.mkdir(self.path)
1394 1394 except OSError, inst:
1395 1395 if inst.errno != errno.EEXIST or not create:
1396 1396 raise
1397 1397 if create:
1398 1398 return self.qrepo(create=True)
1399 1399
1400 1400 def unapplied(self, repo, patch=None):
1401 1401 if patch and patch not in self.series:
1402 1402 raise util.Abort(_("patch %s is not in series file") % patch)
1403 1403 if not patch:
1404 1404 start = self.series_end()
1405 1405 else:
1406 1406 start = self.series.index(patch) + 1
1407 1407 unapplied = []
1408 1408 for i in xrange(start, len(self.series)):
1409 1409 pushable, reason = self.pushable(i)
1410 1410 if pushable:
1411 1411 unapplied.append((i, self.series[i]))
1412 1412 self.explain_pushable(i)
1413 1413 return unapplied
1414 1414
1415 1415 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1416 1416 summary=False):
1417 1417 def displayname(pfx, patchname, state):
1418 1418 if pfx:
1419 1419 self.ui.write(pfx)
1420 1420 if summary:
1421 1421 ph = patchheader(self.join(patchname), self.plainmode)
1422 1422 msg = ph.message and ph.message[0] or ''
1423 1423 if not self.ui.plain():
1424 1424 width = util.termwidth() - len(pfx) - len(patchname) - 2
1425 1425 if width > 0:
1426 1426 msg = util.ellipsis(msg, width)
1427 1427 else:
1428 1428 msg = ''
1429 1429 self.ui.write(patchname, label='qseries.' + state)
1430 1430 self.ui.write(': ')
1431 1431 self.ui.write(msg, label='qseries.message.' + state)
1432 1432 else:
1433 1433 self.ui.write(patchname, label='qseries.' + state)
1434 1434 self.ui.write('\n')
1435 1435
1436 1436 applied = set([p.name for p in self.applied])
1437 1437 if length is None:
1438 1438 length = len(self.series) - start
1439 1439 if not missing:
1440 1440 if self.ui.verbose:
1441 1441 idxwidth = len(str(start + length - 1))
1442 1442 for i in xrange(start, start + length):
1443 1443 patch = self.series[i]
1444 1444 if patch in applied:
1445 1445 char, state = 'A', 'applied'
1446 1446 elif self.pushable(i)[0]:
1447 1447 char, state = 'U', 'unapplied'
1448 1448 else:
1449 1449 char, state = 'G', 'guarded'
1450 1450 pfx = ''
1451 1451 if self.ui.verbose:
1452 1452 pfx = '%*d %s ' % (idxwidth, i, char)
1453 1453 elif status and status != char:
1454 1454 continue
1455 1455 displayname(pfx, patch, state)
1456 1456 else:
1457 1457 msng_list = []
1458 1458 for root, dirs, files in os.walk(self.path):
1459 1459 d = root[len(self.path) + 1:]
1460 1460 for f in files:
1461 1461 fl = os.path.join(d, f)
1462 1462 if (fl not in self.series and
1463 1463 fl not in (self.status_path, self.series_path,
1464 1464 self.guards_path)
1465 1465 and not fl.startswith('.')):
1466 1466 msng_list.append(fl)
1467 1467 for x in sorted(msng_list):
1468 1468 pfx = self.ui.verbose and ('D ') or ''
1469 1469 displayname(pfx, x, 'missing')
1470 1470
1471 1471 def issaveline(self, l):
1472 1472 if l.name == '.hg.patches.save.line':
1473 1473 return True
1474 1474
1475 1475 def qrepo(self, create=False):
1476 1476 if create or os.path.isdir(self.join(".hg")):
1477 1477 return hg.repository(self.ui, path=self.path, create=create)
1478 1478
1479 1479 def restore(self, repo, rev, delete=None, qupdate=None):
1480 1480 desc = repo[rev].description().strip()
1481 1481 lines = desc.splitlines()
1482 1482 i = 0
1483 1483 datastart = None
1484 1484 series = []
1485 1485 applied = []
1486 1486 qpp = None
1487 1487 for i, line in enumerate(lines):
1488 1488 if line == 'Patch Data:':
1489 1489 datastart = i + 1
1490 1490 elif line.startswith('Dirstate:'):
1491 1491 l = line.rstrip()
1492 1492 l = l[10:].split(' ')
1493 1493 qpp = [bin(x) for x in l]
1494 1494 elif datastart != None:
1495 1495 l = line.rstrip()
1496 1496 n, name = l.split(':', 1)
1497 1497 if n:
1498 1498 applied.append(statusentry(bin(n), name))
1499 1499 else:
1500 1500 series.append(l)
1501 1501 if datastart is None:
1502 1502 self.ui.warn(_("No saved patch data found\n"))
1503 1503 return 1
1504 1504 self.ui.warn(_("restoring status: %s\n") % lines[0])
1505 1505 self.full_series = series
1506 1506 self.applied = applied
1507 1507 self.parse_series()
1508 1508 self.series_dirty = 1
1509 1509 self.applied_dirty = 1
1510 1510 heads = repo.changelog.heads()
1511 1511 if delete:
1512 1512 if rev not in heads:
1513 1513 self.ui.warn(_("save entry has children, leaving it alone\n"))
1514 1514 else:
1515 1515 self.ui.warn(_("removing save entry %s\n") % short(rev))
1516 1516 pp = repo.dirstate.parents()
1517 1517 if rev in pp:
1518 1518 update = True
1519 1519 else:
1520 1520 update = False
1521 1521 self.strip(repo, rev, update=update, backup='strip')
1522 1522 if qpp:
1523 1523 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1524 1524 (short(qpp[0]), short(qpp[1])))
1525 1525 if qupdate:
1526 1526 self.ui.status(_("queue directory updating\n"))
1527 1527 r = self.qrepo()
1528 1528 if not r:
1529 1529 self.ui.warn(_("Unable to load queue repository\n"))
1530 1530 return 1
1531 1531 hg.clean(r, qpp[0])
1532 1532
1533 1533 def save(self, repo, msg=None):
1534 1534 if not self.applied:
1535 1535 self.ui.warn(_("save: no patches applied, exiting\n"))
1536 1536 return 1
1537 1537 if self.issaveline(self.applied[-1]):
1538 1538 self.ui.warn(_("status is already saved\n"))
1539 1539 return 1
1540 1540
1541 1541 if not msg:
1542 1542 msg = _("hg patches saved state")
1543 1543 else:
1544 1544 msg = "hg patches: " + msg.rstrip('\r\n')
1545 1545 r = self.qrepo()
1546 1546 if r:
1547 1547 pp = r.dirstate.parents()
1548 1548 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1549 1549 msg += "\n\nPatch Data:\n"
1550 1550 msg += ''.join('%s\n' % x for x in self.applied)
1551 1551 msg += ''.join(':%s\n' % x for x in self.full_series)
1552 1552 n = repo.commit(msg, force=True)
1553 1553 if not n:
1554 1554 self.ui.warn(_("repo commit failed\n"))
1555 1555 return 1
1556 1556 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1557 1557 self.applied_dirty = 1
1558 1558 self.removeundo(repo)
1559 1559
1560 1560 def full_series_end(self):
1561 1561 if self.applied:
1562 1562 p = self.applied[-1].name
1563 1563 end = self.find_series(p)
1564 1564 if end is None:
1565 1565 return len(self.full_series)
1566 1566 return end + 1
1567 1567 return 0
1568 1568
1569 1569 def series_end(self, all_patches=False):
1570 1570 """If all_patches is False, return the index of the next pushable patch
1571 1571 in the series, or the series length. If all_patches is True, return the
1572 1572 index of the first patch past the last applied one.
1573 1573 """
1574 1574 end = 0
1575 1575 def next(start):
1576 1576 if all_patches or start >= len(self.series):
1577 1577 return start
1578 1578 for i in xrange(start, len(self.series)):
1579 1579 p, reason = self.pushable(i)
1580 1580 if p:
1581 1581 break
1582 1582 self.explain_pushable(i)
1583 1583 return i
1584 1584 if self.applied:
1585 1585 p = self.applied[-1].name
1586 1586 try:
1587 1587 end = self.series.index(p)
1588 1588 except ValueError:
1589 1589 return 0
1590 1590 return next(end + 1)
1591 1591 return next(end)
1592 1592
1593 1593 def appliedname(self, index):
1594 1594 pname = self.applied[index].name
1595 1595 if not self.ui.verbose:
1596 1596 p = pname
1597 1597 else:
1598 1598 p = str(self.series.index(pname)) + " " + pname
1599 1599 return p
1600 1600
1601 1601 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1602 1602 force=None, git=False):
1603 1603 def checkseries(patchname):
1604 1604 if patchname in self.series:
1605 1605 raise util.Abort(_('patch %s is already in the series file')
1606 1606 % patchname)
1607 1607 def checkfile(patchname):
1608 1608 if not force and os.path.exists(self.join(patchname)):
1609 1609 raise util.Abort(_('patch "%s" already exists')
1610 1610 % patchname)
1611 1611
1612 1612 if rev:
1613 1613 if files:
1614 1614 raise util.Abort(_('option "-r" not valid when importing '
1615 1615 'files'))
1616 1616 rev = cmdutil.revrange(repo, rev)
1617 1617 rev.sort(reverse=True)
1618 1618 if (len(files) > 1 or len(rev) > 1) and patchname:
1619 1619 raise util.Abort(_('option "-n" not valid when importing multiple '
1620 1620 'patches'))
1621 1621 added = []
1622 1622 if rev:
1623 1623 # If mq patches are applied, we can only import revisions
1624 1624 # that form a linear path to qbase.
1625 1625 # Otherwise, they should form a linear path to a head.
1626 1626 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1627 1627 if len(heads) > 1:
1628 1628 raise util.Abort(_('revision %d is the root of more than one '
1629 1629 'branch') % rev[-1])
1630 1630 if self.applied:
1631 1631 base = repo.changelog.node(rev[0])
1632 1632 if base in [n.node for n in self.applied]:
1633 1633 raise util.Abort(_('revision %d is already managed')
1634 1634 % rev[0])
1635 1635 if heads != [self.applied[-1].node]:
1636 1636 raise util.Abort(_('revision %d is not the parent of '
1637 1637 'the queue') % rev[0])
1638 1638 base = repo.changelog.rev(self.applied[0].node)
1639 1639 lastparent = repo.changelog.parentrevs(base)[0]
1640 1640 else:
1641 1641 if heads != [repo.changelog.node(rev[0])]:
1642 1642 raise util.Abort(_('revision %d has unmanaged children')
1643 1643 % rev[0])
1644 1644 lastparent = None
1645 1645
1646 1646 diffopts = self.diffopts({'git': git})
1647 1647 for r in rev:
1648 1648 p1, p2 = repo.changelog.parentrevs(r)
1649 1649 n = repo.changelog.node(r)
1650 1650 if p2 != nullrev:
1651 1651 raise util.Abort(_('cannot import merge revision %d') % r)
1652 1652 if lastparent and lastparent != r:
1653 1653 raise util.Abort(_('revision %d is not the parent of %d')
1654 1654 % (r, lastparent))
1655 1655 lastparent = p1
1656 1656
1657 1657 if not patchname:
1658 1658 patchname = normname('%d.diff' % r)
1659 1659 self.check_reserved_name(patchname)
1660 1660 checkseries(patchname)
1661 1661 checkfile(patchname)
1662 1662 self.full_series.insert(0, patchname)
1663 1663
1664 1664 patchf = self.opener(patchname, "w")
1665 1665 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1666 1666 patchf.close()
1667 1667
1668 1668 se = statusentry(n, patchname)
1669 1669 self.applied.insert(0, se)
1670 1670
1671 1671 added.append(patchname)
1672 1672 patchname = None
1673 1673 self.parse_series()
1674 1674 self.applied_dirty = 1
1675 1675
1676 1676 for i, filename in enumerate(files):
1677 1677 if existing:
1678 1678 if filename == '-':
1679 1679 raise util.Abort(_('-e is incompatible with import from -'))
1680 1680 if not patchname:
1681 1681 patchname = normname(filename)
1682 1682 self.check_reserved_name(patchname)
1683 1683 if not os.path.isfile(self.join(patchname)):
1684 1684 raise util.Abort(_("patch %s does not exist") % patchname)
1685 1685 else:
1686 1686 try:
1687 1687 if filename == '-':
1688 1688 if not patchname:
1689 1689 raise util.Abort(
1690 1690 _('need --name to import a patch from -'))
1691 1691 text = sys.stdin.read()
1692 1692 else:
1693 1693 text = url.open(self.ui, filename).read()
1694 1694 except (OSError, IOError):
1695 1695 raise util.Abort(_("unable to read %s") % filename)
1696 1696 if not patchname:
1697 1697 patchname = normname(os.path.basename(filename))
1698 1698 self.check_reserved_name(patchname)
1699 1699 checkfile(patchname)
1700 1700 patchf = self.opener(patchname, "w")
1701 1701 patchf.write(text)
1702 1702 if not force:
1703 1703 checkseries(patchname)
1704 1704 if patchname not in self.series:
1705 1705 index = self.full_series_end() + i
1706 1706 self.full_series[index:index] = [patchname]
1707 1707 self.parse_series()
1708 1708 self.ui.warn(_("adding %s to series file\n") % patchname)
1709 1709 added.append(patchname)
1710 1710 patchname = None
1711 1711 self.series_dirty = 1
1712 1712 qrepo = self.qrepo()
1713 1713 if qrepo:
1714 1714 qrepo.add(added)
1715 1715
1716 1716 def delete(ui, repo, *patches, **opts):
1717 1717 """remove patches from queue
1718 1718
1719 1719 The patches must not be applied, and at least one patch is required. With
1720 1720 -k/--keep, the patch files are preserved in the patch directory.
1721 1721
1722 1722 To stop managing a patch and move it into permanent history,
1723 1723 use the qfinish command."""
1724 1724 q = repo.mq
1725 1725 q.delete(repo, patches, opts)
1726 1726 q.save_dirty()
1727 1727 return 0
1728 1728
1729 1729 def applied(ui, repo, patch=None, **opts):
1730 1730 """print the patches already applied"""
1731 1731
1732 1732 q = repo.mq
1733 1733 l = len(q.applied)
1734 1734
1735 1735 if patch:
1736 1736 if patch not in q.series:
1737 1737 raise util.Abort(_("patch %s is not in series file") % patch)
1738 1738 end = q.series.index(patch) + 1
1739 1739 else:
1740 1740 end = q.series_end(True)
1741 1741
1742 1742 if opts.get('last') and not end:
1743 1743 ui.write(_("no patches applied\n"))
1744 1744 return 1
1745 1745 elif opts.get('last') and end == 1:
1746 1746 ui.write(_("only one patch applied\n"))
1747 1747 return 1
1748 1748 elif opts.get('last'):
1749 1749 start = end - 2
1750 1750 end = 1
1751 1751 else:
1752 1752 start = 0
1753 1753
1754 1754 return q.qseries(repo, length=end, start=start, status='A',
1755 1755 summary=opts.get('summary'))
1756 1756
1757 1757 def unapplied(ui, repo, patch=None, **opts):
1758 1758 """print the patches not yet applied"""
1759 1759
1760 1760 q = repo.mq
1761 1761 if patch:
1762 1762 if patch not in q.series:
1763 1763 raise util.Abort(_("patch %s is not in series file") % patch)
1764 1764 start = q.series.index(patch) + 1
1765 1765 else:
1766 1766 start = q.series_end(True)
1767 1767
1768 1768 if start == len(q.series) and opts.get('first'):
1769 1769 ui.write(_("all patches applied\n"))
1770 1770 return 1
1771 1771
1772 1772 length = opts.get('first') and 1 or None
1773 1773 return q.qseries(repo, start=start, length=length, status='U',
1774 1774 summary=opts.get('summary'))
1775 1775
1776 1776 def qimport(ui, repo, *filename, **opts):
1777 1777 """import a patch
1778 1778
1779 1779 The patch is inserted into the series after the last applied
1780 1780 patch. If no patches have been applied, qimport prepends the patch
1781 1781 to the series.
1782 1782
1783 1783 The patch will have the same name as its source file unless you
1784 1784 give it a new one with -n/--name.
1785 1785
1786 1786 You can register an existing patch inside the patch directory with
1787 1787 the -e/--existing flag.
1788 1788
1789 1789 With -f/--force, an existing patch of the same name will be
1790 1790 overwritten.
1791 1791
1792 1792 An existing changeset may be placed under mq control with -r/--rev
1793 1793 (e.g. qimport --rev tip -n patch will place tip under mq control).
1794 1794 With -g/--git, patches imported with --rev will use the git diff
1795 1795 format. See the diffs help topic for information on why this is
1796 1796 important for preserving rename/copy information and permission
1797 1797 changes.
1798 1798
1799 1799 To import a patch from standard input, pass - as the patch file.
1800 1800 When importing from standard input, a patch name must be specified
1801 1801 using the --name flag.
1802 1802 """
1803 1803 q = repo.mq
1804 1804 q.qimport(repo, filename, patchname=opts['name'],
1805 1805 existing=opts['existing'], force=opts['force'], rev=opts['rev'],
1806 1806 git=opts['git'])
1807 1807 q.save_dirty()
1808 1808
1809 1809 if opts.get('push') and not opts.get('rev'):
1810 1810 return q.push(repo, None)
1811 1811 return 0
1812 1812
1813 1813 def qinit(ui, repo, create):
1814 1814 """initialize a new queue repository
1815 1815
1816 1816 This command also creates a series file for ordering patches, and
1817 1817 an mq-specific .hgignore file in the queue repository, to exclude
1818 1818 the status and guards files (these contain mostly transient state)."""
1819 1819 q = repo.mq
1820 1820 r = q.init(repo, create)
1821 1821 q.save_dirty()
1822 1822 if r:
1823 1823 if not os.path.exists(r.wjoin('.hgignore')):
1824 1824 fp = r.wopener('.hgignore', 'w')
1825 1825 fp.write('^\\.hg\n')
1826 1826 fp.write('^\\.mq\n')
1827 1827 fp.write('syntax: glob\n')
1828 1828 fp.write('status\n')
1829 1829 fp.write('guards\n')
1830 1830 fp.close()
1831 1831 if not os.path.exists(r.wjoin('series')):
1832 1832 r.wopener('series', 'w').close()
1833 1833 r.add(['.hgignore', 'series'])
1834 1834 commands.add(ui, r)
1835 1835 return 0
1836 1836
1837 1837 def init(ui, repo, **opts):
1838 1838 """init a new queue repository (DEPRECATED)
1839 1839
1840 1840 The queue repository is unversioned by default. If
1841 1841 -c/--create-repo is specified, qinit will create a separate nested
1842 1842 repository for patches (qinit -c may also be run later to convert
1843 1843 an unversioned patch repository into a versioned one). You can use
1844 1844 qcommit to commit changes to this queue repository.
1845 1845
1846 1846 This command is deprecated. Without -c, it's implied by other relevant
1847 1847 commands. With -c, use hg init --mq instead."""
1848 1848 return qinit(ui, repo, create=opts['create_repo'])
1849 1849
1850 1850 def clone(ui, source, dest=None, **opts):
1851 1851 '''clone main and patch repository at same time
1852 1852
1853 1853 If source is local, destination will have no patches applied. If
1854 1854 source is remote, this command can not check if patches are
1855 1855 applied in source, so cannot guarantee that patches are not
1856 1856 applied in destination. If you clone remote repository, be sure
1857 1857 before that it has no patches applied.
1858 1858
1859 1859 Source patch repository is looked for in <src>/.hg/patches by
1860 1860 default. Use -p <url> to change.
1861 1861
1862 1862 The patch directory must be a nested Mercurial repository, as
1863 1863 would be created by init --mq.
1864 1864 '''
1865 1865 def patchdir(repo):
1866 1866 url = repo.url()
1867 1867 if url.endswith('/'):
1868 1868 url = url[:-1]
1869 1869 return url + '/.hg/patches'
1870 1870 if dest is None:
1871 1871 dest = hg.defaultdest(source)
1872 1872 sr = hg.repository(cmdutil.remoteui(ui, opts), ui.expandpath(source))
1873 1873 if opts['patches']:
1874 1874 patchespath = ui.expandpath(opts['patches'])
1875 1875 else:
1876 1876 patchespath = patchdir(sr)
1877 1877 try:
1878 1878 hg.repository(ui, patchespath)
1879 1879 except error.RepoError:
1880 1880 raise util.Abort(_('versioned patch repository not found'
1881 1881 ' (see init --mq)'))
1882 1882 qbase, destrev = None, None
1883 1883 if sr.local():
1884 1884 if sr.mq.applied:
1885 1885 qbase = sr.mq.applied[0].node
1886 1886 if not hg.islocal(dest):
1887 1887 heads = set(sr.heads())
1888 1888 destrev = list(heads.difference(sr.heads(qbase)))
1889 1889 destrev.append(sr.changelog.parents(qbase)[0])
1890 1890 elif sr.capable('lookup'):
1891 1891 try:
1892 1892 qbase = sr.lookup('qbase')
1893 1893 except error.RepoError:
1894 1894 pass
1895 1895 ui.note(_('cloning main repository\n'))
1896 1896 sr, dr = hg.clone(ui, sr.url(), dest,
1897 1897 pull=opts['pull'],
1898 1898 rev=destrev,
1899 1899 update=False,
1900 1900 stream=opts['uncompressed'])
1901 1901 ui.note(_('cloning patch repository\n'))
1902 1902 hg.clone(ui, opts['patches'] or patchdir(sr), patchdir(dr),
1903 1903 pull=opts['pull'], update=not opts['noupdate'],
1904 1904 stream=opts['uncompressed'])
1905 1905 if dr.local():
1906 1906 if qbase:
1907 1907 ui.note(_('stripping applied patches from destination '
1908 1908 'repository\n'))
1909 1909 dr.mq.strip(dr, qbase, update=False, backup=None)
1910 1910 if not opts['noupdate']:
1911 1911 ui.note(_('updating destination repository\n'))
1912 1912 hg.update(dr, dr.changelog.tip())
1913 1913
1914 1914 def commit(ui, repo, *pats, **opts):
1915 1915 """commit changes in the queue repository (DEPRECATED)
1916 1916
1917 1917 This command is deprecated; use hg commit --mq instead."""
1918 1918 q = repo.mq
1919 1919 r = q.qrepo()
1920 1920 if not r:
1921 1921 raise util.Abort('no queue repository')
1922 1922 commands.commit(r.ui, r, *pats, **opts)
1923 1923
1924 1924 def series(ui, repo, **opts):
1925 1925 """print the entire series file"""
1926 1926 repo.mq.qseries(repo, missing=opts['missing'], summary=opts['summary'])
1927 1927 return 0
1928 1928
1929 1929 def top(ui, repo, **opts):
1930 1930 """print the name of the current patch"""
1931 1931 q = repo.mq
1932 1932 t = q.applied and q.series_end(True) or 0
1933 1933 if t:
1934 1934 return q.qseries(repo, start=t - 1, length=1, status='A',
1935 1935 summary=opts.get('summary'))
1936 1936 else:
1937 1937 ui.write(_("no patches applied\n"))
1938 1938 return 1
1939 1939
1940 1940 def next(ui, repo, **opts):
1941 1941 """print the name of the next patch"""
1942 1942 q = repo.mq
1943 1943 end = q.series_end()
1944 1944 if end == len(q.series):
1945 1945 ui.write(_("all patches applied\n"))
1946 1946 return 1
1947 1947 return q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
1948 1948
1949 1949 def prev(ui, repo, **opts):
1950 1950 """print the name of the previous patch"""
1951 1951 q = repo.mq
1952 1952 l = len(q.applied)
1953 1953 if l == 1:
1954 1954 ui.write(_("only one patch applied\n"))
1955 1955 return 1
1956 1956 if not l:
1957 1957 ui.write(_("no patches applied\n"))
1958 1958 return 1
1959 1959 return q.qseries(repo, start=l - 2, length=1, status='A',
1960 1960 summary=opts.get('summary'))
1961 1961
1962 1962 def setupheaderopts(ui, opts):
1963 1963 if not opts.get('user') and opts.get('currentuser'):
1964 1964 opts['user'] = ui.username()
1965 1965 if not opts.get('date') and opts.get('currentdate'):
1966 1966 opts['date'] = "%d %d" % util.makedate()
1967 1967
1968 1968 def new(ui, repo, patch, *args, **opts):
1969 1969 """create a new patch
1970 1970
1971 1971 qnew creates a new patch on top of the currently-applied patch (if
1972 1972 any). The patch will be initialized with any outstanding changes
1973 1973 in the working directory. You may also use -I/--include,
1974 1974 -X/--exclude, and/or a list of files after the patch name to add
1975 1975 only changes to matching files to the new patch, leaving the rest
1976 1976 as uncommitted modifications.
1977 1977
1978 1978 -u/--user and -d/--date can be used to set the (given) user and
1979 1979 date, respectively. -U/--currentuser and -D/--currentdate set user
1980 1980 to current user and date to current date.
1981 1981
1982 1982 -e/--edit, -m/--message or -l/--logfile set the patch header as
1983 1983 well as the commit message. If none is specified, the header is
1984 1984 empty and the commit message is '[mq]: PATCH'.
1985 1985
1986 1986 Use the -g/--git option to keep the patch in the git extended diff
1987 1987 format. Read the diffs help topic for more information on why this
1988 1988 is important for preserving permission changes and copy/rename
1989 1989 information.
1990 1990 """
1991 1991 msg = cmdutil.logmessage(opts)
1992 1992 def getmsg():
1993 1993 return ui.edit(msg, ui.username())
1994 1994 q = repo.mq
1995 1995 opts['msg'] = msg
1996 1996 if opts.get('edit'):
1997 1997 opts['msg'] = getmsg
1998 1998 else:
1999 1999 opts['msg'] = msg
2000 2000 setupheaderopts(ui, opts)
2001 2001 q.new(repo, patch, *args, **opts)
2002 2002 q.save_dirty()
2003 2003 return 0
2004 2004
2005 2005 def refresh(ui, repo, *pats, **opts):
2006 2006 """update the current patch
2007 2007
2008 2008 If any file patterns are provided, the refreshed patch will
2009 2009 contain only the modifications that match those patterns; the
2010 2010 remaining modifications will remain in the working directory.
2011 2011
2012 2012 If -s/--short is specified, files currently included in the patch
2013 2013 will be refreshed just like matched files and remain in the patch.
2014 2014
2015 2015 hg add/remove/copy/rename work as usual, though you might want to
2016 2016 use git-style patches (-g/--git or [diff] git=1) to track copies
2017 2017 and renames. See the diffs help topic for more information on the
2018 2018 git diff format.
2019 2019 """
2020 2020 q = repo.mq
2021 2021 message = cmdutil.logmessage(opts)
2022 2022 if opts['edit']:
2023 2023 if not q.applied:
2024 2024 ui.write(_("no patches applied\n"))
2025 2025 return 1
2026 2026 if message:
2027 2027 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2028 2028 patch = q.applied[-1].name
2029 2029 ph = patchheader(q.join(patch), q.plainmode)
2030 2030 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2031 2031 setupheaderopts(ui, opts)
2032 2032 ret = q.refresh(repo, pats, msg=message, **opts)
2033 2033 q.save_dirty()
2034 2034 return ret
2035 2035
2036 2036 def diff(ui, repo, *pats, **opts):
2037 2037 """diff of the current patch and subsequent modifications
2038 2038
2039 2039 Shows a diff which includes the current patch as well as any
2040 2040 changes which have been made in the working directory since the
2041 2041 last refresh (thus showing what the current patch would become
2042 2042 after a qrefresh).
2043 2043
2044 Use 'hg diff' if you only want to see the changes made since the
2045 last qrefresh, or 'hg export qtip' if you want to see changes made
2046 by the current patch without including changes made since the
2044 Use :hg:`diff` if you only want to see the changes made since the
2045 last qrefresh, or :hg:`export qtip` if you want to see changes
2046 made by the current patch without including changes made since the
2047 2047 qrefresh.
2048 2048 """
2049 2049 repo.mq.diff(repo, pats, opts)
2050 2050 return 0
2051 2051
2052 2052 def fold(ui, repo, *files, **opts):
2053 2053 """fold the named patches into the current patch
2054 2054
2055 2055 Patches must not yet be applied. Each patch will be successively
2056 2056 applied to the current patch in the order given. If all the
2057 2057 patches apply successfully, the current patch will be refreshed
2058 2058 with the new cumulative patch, and the folded patches will be
2059 2059 deleted. With -k/--keep, the folded patch files will not be
2060 2060 removed afterwards.
2061 2061
2062 2062 The header for each folded patch will be concatenated with the
2063 2063 current patch header, separated by a line of '* * *'."""
2064 2064
2065 2065 q = repo.mq
2066 2066
2067 2067 if not files:
2068 2068 raise util.Abort(_('qfold requires at least one patch name'))
2069 2069 if not q.check_toppatch(repo)[0]:
2070 2070 raise util.Abort(_('No patches applied'))
2071 2071 q.check_localchanges(repo)
2072 2072
2073 2073 message = cmdutil.logmessage(opts)
2074 2074 if opts['edit']:
2075 2075 if message:
2076 2076 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2077 2077
2078 2078 parent = q.lookup('qtip')
2079 2079 patches = []
2080 2080 messages = []
2081 2081 for f in files:
2082 2082 p = q.lookup(f)
2083 2083 if p in patches or p == parent:
2084 2084 ui.warn(_('Skipping already folded patch %s') % p)
2085 2085 if q.isapplied(p):
2086 2086 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2087 2087 patches.append(p)
2088 2088
2089 2089 for p in patches:
2090 2090 if not message:
2091 2091 ph = patchheader(q.join(p), q.plainmode)
2092 2092 if ph.message:
2093 2093 messages.append(ph.message)
2094 2094 pf = q.join(p)
2095 2095 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2096 2096 if not patchsuccess:
2097 2097 raise util.Abort(_('Error folding patch %s') % p)
2098 2098 patch.updatedir(ui, repo, files)
2099 2099
2100 2100 if not message:
2101 2101 ph = patchheader(q.join(parent), q.plainmode)
2102 2102 message, user = ph.message, ph.user
2103 2103 for msg in messages:
2104 2104 message.append('* * *')
2105 2105 message.extend(msg)
2106 2106 message = '\n'.join(message)
2107 2107
2108 2108 if opts['edit']:
2109 2109 message = ui.edit(message, user or ui.username())
2110 2110
2111 2111 diffopts = q.patchopts(q.diffopts(), *patches)
2112 2112 q.refresh(repo, msg=message, git=diffopts.git)
2113 2113 q.delete(repo, patches, opts)
2114 2114 q.save_dirty()
2115 2115
2116 2116 def goto(ui, repo, patch, **opts):
2117 2117 '''push or pop patches until named patch is at top of stack'''
2118 2118 q = repo.mq
2119 2119 patch = q.lookup(patch)
2120 2120 if q.isapplied(patch):
2121 2121 ret = q.pop(repo, patch, force=opts['force'])
2122 2122 else:
2123 2123 ret = q.push(repo, patch, force=opts['force'])
2124 2124 q.save_dirty()
2125 2125 return ret
2126 2126
2127 2127 def guard(ui, repo, *args, **opts):
2128 2128 '''set or print guards for a patch
2129 2129
2130 2130 Guards control whether a patch can be pushed. A patch with no
2131 2131 guards is always pushed. A patch with a positive guard ("+foo") is
2132 2132 pushed only if the qselect command has activated it. A patch with
2133 2133 a negative guard ("-foo") is never pushed if the qselect command
2134 2134 has activated it.
2135 2135
2136 2136 With no arguments, print the currently active guards.
2137 2137 With arguments, set guards for the named patch.
2138 2138 NOTE: Specifying negative guards now requires '--'.
2139 2139
2140 2140 To set guards on another patch::
2141 2141
2142 2142 hg qguard other.patch -- +2.6.17 -stable
2143 2143 '''
2144 2144 def status(idx):
2145 2145 guards = q.series_guards[idx] or ['unguarded']
2146 2146 ui.write('%s: ' % ui.label(q.series[idx], 'qguard.patch'))
2147 2147 for i, guard in enumerate(guards):
2148 2148 if guard.startswith('+'):
2149 2149 ui.write(guard, label='qguard.positive')
2150 2150 elif guard.startswith('-'):
2151 2151 ui.write(guard, label='qguard.negative')
2152 2152 else:
2153 2153 ui.write(guard, label='qguard.unguarded')
2154 2154 if i != len(guards) - 1:
2155 2155 ui.write(' ')
2156 2156 ui.write('\n')
2157 2157 q = repo.mq
2158 2158 patch = None
2159 2159 args = list(args)
2160 2160 if opts['list']:
2161 2161 if args or opts['none']:
2162 2162 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2163 2163 for i in xrange(len(q.series)):
2164 2164 status(i)
2165 2165 return
2166 2166 if not args or args[0][0:1] in '-+':
2167 2167 if not q.applied:
2168 2168 raise util.Abort(_('no patches applied'))
2169 2169 patch = q.applied[-1].name
2170 2170 if patch is None and args[0][0:1] not in '-+':
2171 2171 patch = args.pop(0)
2172 2172 if patch is None:
2173 2173 raise util.Abort(_('no patch to work with'))
2174 2174 if args or opts['none']:
2175 2175 idx = q.find_series(patch)
2176 2176 if idx is None:
2177 2177 raise util.Abort(_('no patch named %s') % patch)
2178 2178 q.set_guards(idx, args)
2179 2179 q.save_dirty()
2180 2180 else:
2181 2181 status(q.series.index(q.lookup(patch)))
2182 2182
2183 2183 def header(ui, repo, patch=None):
2184 2184 """print the header of the topmost or specified patch"""
2185 2185 q = repo.mq
2186 2186
2187 2187 if patch:
2188 2188 patch = q.lookup(patch)
2189 2189 else:
2190 2190 if not q.applied:
2191 2191 ui.write(_('no patches applied\n'))
2192 2192 return 1
2193 2193 patch = q.lookup('qtip')
2194 2194 ph = patchheader(q.join(patch), q.plainmode)
2195 2195
2196 2196 ui.write('\n'.join(ph.message) + '\n')
2197 2197
2198 2198 def lastsavename(path):
2199 2199 (directory, base) = os.path.split(path)
2200 2200 names = os.listdir(directory)
2201 2201 namere = re.compile("%s.([0-9]+)" % base)
2202 2202 maxindex = None
2203 2203 maxname = None
2204 2204 for f in names:
2205 2205 m = namere.match(f)
2206 2206 if m:
2207 2207 index = int(m.group(1))
2208 2208 if maxindex is None or index > maxindex:
2209 2209 maxindex = index
2210 2210 maxname = f
2211 2211 if maxname:
2212 2212 return (os.path.join(directory, maxname), maxindex)
2213 2213 return (None, None)
2214 2214
2215 2215 def savename(path):
2216 2216 (last, index) = lastsavename(path)
2217 2217 if last is None:
2218 2218 index = 0
2219 2219 newpath = path + ".%d" % (index + 1)
2220 2220 return newpath
2221 2221
2222 2222 def push(ui, repo, patch=None, **opts):
2223 2223 """push the next patch onto the stack
2224 2224
2225 2225 When -f/--force is applied, all local changes in patched files
2226 2226 will be lost.
2227 2227 """
2228 2228 q = repo.mq
2229 2229 mergeq = None
2230 2230
2231 2231 if opts['merge']:
2232 2232 if opts['name']:
2233 2233 newpath = repo.join(opts['name'])
2234 2234 else:
2235 2235 newpath, i = lastsavename(q.path)
2236 2236 if not newpath:
2237 2237 ui.warn(_("no saved queues found, please use -n\n"))
2238 2238 return 1
2239 2239 mergeq = queue(ui, repo.join(""), newpath)
2240 2240 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2241 2241 ret = q.push(repo, patch, force=opts['force'], list=opts['list'],
2242 2242 mergeq=mergeq, all=opts.get('all'))
2243 2243 return ret
2244 2244
2245 2245 def pop(ui, repo, patch=None, **opts):
2246 2246 """pop the current patch off the stack
2247 2247
2248 2248 By default, pops off the top of the patch stack. If given a patch
2249 2249 name, keeps popping off patches until the named patch is at the
2250 2250 top of the stack.
2251 2251 """
2252 2252 localupdate = True
2253 2253 if opts['name']:
2254 2254 q = queue(ui, repo.join(""), repo.join(opts['name']))
2255 2255 ui.warn(_('using patch queue: %s\n') % q.path)
2256 2256 localupdate = False
2257 2257 else:
2258 2258 q = repo.mq
2259 2259 ret = q.pop(repo, patch, force=opts['force'], update=localupdate,
2260 2260 all=opts['all'])
2261 2261 q.save_dirty()
2262 2262 return ret
2263 2263
2264 2264 def rename(ui, repo, patch, name=None, **opts):
2265 2265 """rename a patch
2266 2266
2267 2267 With one argument, renames the current patch to PATCH1.
2268 2268 With two arguments, renames PATCH1 to PATCH2."""
2269 2269
2270 2270 q = repo.mq
2271 2271
2272 2272 if not name:
2273 2273 name = patch
2274 2274 patch = None
2275 2275
2276 2276 if patch:
2277 2277 patch = q.lookup(patch)
2278 2278 else:
2279 2279 if not q.applied:
2280 2280 ui.write(_('no patches applied\n'))
2281 2281 return
2282 2282 patch = q.lookup('qtip')
2283 2283 absdest = q.join(name)
2284 2284 if os.path.isdir(absdest):
2285 2285 name = normname(os.path.join(name, os.path.basename(patch)))
2286 2286 absdest = q.join(name)
2287 2287 if os.path.exists(absdest):
2288 2288 raise util.Abort(_('%s already exists') % absdest)
2289 2289
2290 2290 if name in q.series:
2291 2291 raise util.Abort(
2292 2292 _('A patch named %s already exists in the series file') % name)
2293 2293
2294 2294 ui.note(_('renaming %s to %s\n') % (patch, name))
2295 2295 i = q.find_series(patch)
2296 2296 guards = q.guard_re.findall(q.full_series[i])
2297 2297 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2298 2298 q.parse_series()
2299 2299 q.series_dirty = 1
2300 2300
2301 2301 info = q.isapplied(patch)
2302 2302 if info:
2303 2303 q.applied[info[0]] = statusentry(info[1], name)
2304 2304 q.applied_dirty = 1
2305 2305
2306 2306 util.rename(q.join(patch), absdest)
2307 2307 r = q.qrepo()
2308 2308 if r:
2309 2309 wlock = r.wlock()
2310 2310 try:
2311 2311 if r.dirstate[patch] == 'a':
2312 2312 r.dirstate.forget(patch)
2313 2313 r.dirstate.add(name)
2314 2314 else:
2315 2315 if r.dirstate[name] == 'r':
2316 2316 r.undelete([name])
2317 2317 r.copy(patch, name)
2318 2318 r.remove([patch], False)
2319 2319 finally:
2320 2320 wlock.release()
2321 2321
2322 2322 q.save_dirty()
2323 2323
2324 2324 def restore(ui, repo, rev, **opts):
2325 2325 """restore the queue state saved by a revision (DEPRECATED)
2326 2326
2327 2327 This command is deprecated, use rebase --mq instead."""
2328 2328 rev = repo.lookup(rev)
2329 2329 q = repo.mq
2330 2330 q.restore(repo, rev, delete=opts['delete'],
2331 2331 qupdate=opts['update'])
2332 2332 q.save_dirty()
2333 2333 return 0
2334 2334
2335 2335 def save(ui, repo, **opts):
2336 2336 """save current queue state (DEPRECATED)
2337 2337
2338 2338 This command is deprecated, use rebase --mq instead."""
2339 2339 q = repo.mq
2340 2340 message = cmdutil.logmessage(opts)
2341 2341 ret = q.save(repo, msg=message)
2342 2342 if ret:
2343 2343 return ret
2344 2344 q.save_dirty()
2345 2345 if opts['copy']:
2346 2346 path = q.path
2347 2347 if opts['name']:
2348 2348 newpath = os.path.join(q.basepath, opts['name'])
2349 2349 if os.path.exists(newpath):
2350 2350 if not os.path.isdir(newpath):
2351 2351 raise util.Abort(_('destination %s exists and is not '
2352 2352 'a directory') % newpath)
2353 2353 if not opts['force']:
2354 2354 raise util.Abort(_('destination %s exists, '
2355 2355 'use -f to force') % newpath)
2356 2356 else:
2357 2357 newpath = savename(path)
2358 2358 ui.warn(_("copy %s to %s\n") % (path, newpath))
2359 2359 util.copyfiles(path, newpath)
2360 2360 if opts['empty']:
2361 2361 try:
2362 2362 os.unlink(q.join(q.status_path))
2363 2363 except:
2364 2364 pass
2365 2365 return 0
2366 2366
2367 2367 def strip(ui, repo, rev, **opts):
2368 2368 """strip a revision and all its descendants from the repository
2369 2369
2370 2370 If one of the working directory's parent revisions is stripped, the
2371 2371 working directory will be updated to the parent of the stripped
2372 2372 revision.
2373 2373 """
2374 2374 backup = 'all'
2375 2375 if opts['backup']:
2376 2376 backup = 'strip'
2377 2377 elif opts['nobackup']:
2378 2378 backup = 'none'
2379 2379
2380 2380 rev = repo.lookup(rev)
2381 2381 p = repo.dirstate.parents()
2382 2382 cl = repo.changelog
2383 2383 update = True
2384 2384 if p[0] == nullid:
2385 2385 update = False
2386 2386 elif p[1] == nullid and rev != cl.ancestor(p[0], rev):
2387 2387 update = False
2388 2388 elif rev not in (cl.ancestor(p[0], rev), cl.ancestor(p[1], rev)):
2389 2389 update = False
2390 2390
2391 2391 repo.mq.strip(repo, rev, backup=backup, update=update, force=opts['force'])
2392 2392 return 0
2393 2393
2394 2394 def select(ui, repo, *args, **opts):
2395 2395 '''set or print guarded patches to push
2396 2396
2397 2397 Use the qguard command to set or print guards on patch, then use
2398 2398 qselect to tell mq which guards to use. A patch will be pushed if
2399 2399 it has no guards or any positive guards match the currently
2400 2400 selected guard, but will not be pushed if any negative guards
2401 2401 match the current guard. For example::
2402 2402
2403 2403 qguard foo.patch -stable (negative guard)
2404 2404 qguard bar.patch +stable (positive guard)
2405 2405 qselect stable
2406 2406
2407 2407 This activates the "stable" guard. mq will skip foo.patch (because
2408 2408 it has a negative match) but push bar.patch (because it has a
2409 2409 positive match).
2410 2410
2411 2411 With no arguments, prints the currently active guards.
2412 2412 With one argument, sets the active guard.
2413 2413
2414 2414 Use -n/--none to deactivate guards (no other arguments needed).
2415 2415 When no guards are active, patches with positive guards are
2416 2416 skipped and patches with negative guards are pushed.
2417 2417
2418 2418 qselect can change the guards on applied patches. It does not pop
2419 2419 guarded patches by default. Use --pop to pop back to the last
2420 2420 applied patch that is not guarded. Use --reapply (which implies
2421 2421 --pop) to push back to the current patch afterwards, but skip
2422 2422 guarded patches.
2423 2423
2424 2424 Use -s/--series to print a list of all guards in the series file
2425 2425 (no other arguments needed). Use -v for more information.'''
2426 2426
2427 2427 q = repo.mq
2428 2428 guards = q.active()
2429 2429 if args or opts['none']:
2430 2430 old_unapplied = q.unapplied(repo)
2431 2431 old_guarded = [i for i in xrange(len(q.applied)) if
2432 2432 not q.pushable(i)[0]]
2433 2433 q.set_active(args)
2434 2434 q.save_dirty()
2435 2435 if not args:
2436 2436 ui.status(_('guards deactivated\n'))
2437 2437 if not opts['pop'] and not opts['reapply']:
2438 2438 unapplied = q.unapplied(repo)
2439 2439 guarded = [i for i in xrange(len(q.applied))
2440 2440 if not q.pushable(i)[0]]
2441 2441 if len(unapplied) != len(old_unapplied):
2442 2442 ui.status(_('number of unguarded, unapplied patches has '
2443 2443 'changed from %d to %d\n') %
2444 2444 (len(old_unapplied), len(unapplied)))
2445 2445 if len(guarded) != len(old_guarded):
2446 2446 ui.status(_('number of guarded, applied patches has changed '
2447 2447 'from %d to %d\n') %
2448 2448 (len(old_guarded), len(guarded)))
2449 2449 elif opts['series']:
2450 2450 guards = {}
2451 2451 noguards = 0
2452 2452 for gs in q.series_guards:
2453 2453 if not gs:
2454 2454 noguards += 1
2455 2455 for g in gs:
2456 2456 guards.setdefault(g, 0)
2457 2457 guards[g] += 1
2458 2458 if ui.verbose:
2459 2459 guards['NONE'] = noguards
2460 2460 guards = guards.items()
2461 2461 guards.sort(key=lambda x: x[0][1:])
2462 2462 if guards:
2463 2463 ui.note(_('guards in series file:\n'))
2464 2464 for guard, count in guards:
2465 2465 ui.note('%2d ' % count)
2466 2466 ui.write(guard, '\n')
2467 2467 else:
2468 2468 ui.note(_('no guards in series file\n'))
2469 2469 else:
2470 2470 if guards:
2471 2471 ui.note(_('active guards:\n'))
2472 2472 for g in guards:
2473 2473 ui.write(g, '\n')
2474 2474 else:
2475 2475 ui.write(_('no active guards\n'))
2476 2476 reapply = opts['reapply'] and q.applied and q.appliedname(-1)
2477 2477 popped = False
2478 2478 if opts['pop'] or opts['reapply']:
2479 2479 for i in xrange(len(q.applied)):
2480 2480 pushable, reason = q.pushable(i)
2481 2481 if not pushable:
2482 2482 ui.status(_('popping guarded patches\n'))
2483 2483 popped = True
2484 2484 if i == 0:
2485 2485 q.pop(repo, all=True)
2486 2486 else:
2487 2487 q.pop(repo, i - 1)
2488 2488 break
2489 2489 if popped:
2490 2490 try:
2491 2491 if reapply:
2492 2492 ui.status(_('reapplying unguarded patches\n'))
2493 2493 q.push(repo, reapply)
2494 2494 finally:
2495 2495 q.save_dirty()
2496 2496
2497 2497 def finish(ui, repo, *revrange, **opts):
2498 2498 """move applied patches into repository history
2499 2499
2500 2500 Finishes the specified revisions (corresponding to applied
2501 2501 patches) by moving them out of mq control into regular repository
2502 2502 history.
2503 2503
2504 2504 Accepts a revision range or the -a/--applied option. If --applied
2505 2505 is specified, all applied mq revisions are removed from mq
2506 2506 control. Otherwise, the given revisions must be at the base of the
2507 2507 stack of applied patches.
2508 2508
2509 2509 This can be especially useful if your changes have been applied to
2510 2510 an upstream repository, or if you are about to push your changes
2511 2511 to upstream.
2512 2512 """
2513 2513 if not opts['applied'] and not revrange:
2514 2514 raise util.Abort(_('no revisions specified'))
2515 2515 elif opts['applied']:
2516 2516 revrange = ('qbase:qtip',) + revrange
2517 2517
2518 2518 q = repo.mq
2519 2519 if not q.applied:
2520 2520 ui.status(_('no patches applied\n'))
2521 2521 return 0
2522 2522
2523 2523 revs = cmdutil.revrange(repo, revrange)
2524 2524 q.finish(repo, revs)
2525 2525 q.save_dirty()
2526 2526 return 0
2527 2527
2528 2528 def reposetup(ui, repo):
2529 2529 class mqrepo(repo.__class__):
2530 2530 @util.propertycache
2531 2531 def mq(self):
2532 2532 return queue(self.ui, self.join(""))
2533 2533
2534 2534 def abort_if_wdir_patched(self, errmsg, force=False):
2535 2535 if self.mq.applied and not force:
2536 2536 parent = self.dirstate.parents()[0]
2537 2537 if parent in [s.node for s in self.mq.applied]:
2538 2538 raise util.Abort(errmsg)
2539 2539
2540 2540 def commit(self, text="", user=None, date=None, match=None,
2541 2541 force=False, editor=False, extra={}):
2542 2542 self.abort_if_wdir_patched(
2543 2543 _('cannot commit over an applied mq patch'),
2544 2544 force)
2545 2545
2546 2546 return super(mqrepo, self).commit(text, user, date, match, force,
2547 2547 editor, extra)
2548 2548
2549 2549 def push(self, remote, force=False, revs=None):
2550 2550 if self.mq.applied and not force and not revs:
2551 2551 raise util.Abort(_('source has mq patches applied'))
2552 2552 return super(mqrepo, self).push(remote, force, revs)
2553 2553
2554 2554 def _findtags(self):
2555 2555 '''augment tags from base class with patch tags'''
2556 2556 result = super(mqrepo, self)._findtags()
2557 2557
2558 2558 q = self.mq
2559 2559 if not q.applied:
2560 2560 return result
2561 2561
2562 2562 mqtags = [(patch.node, patch.name) for patch in q.applied]
2563 2563
2564 2564 if mqtags[-1][0] not in self.changelog.nodemap:
2565 2565 self.ui.warn(_('mq status file refers to unknown node %s\n')
2566 2566 % short(mqtags[-1][0]))
2567 2567 return result
2568 2568
2569 2569 mqtags.append((mqtags[-1][0], 'qtip'))
2570 2570 mqtags.append((mqtags[0][0], 'qbase'))
2571 2571 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
2572 2572 tags = result[0]
2573 2573 for patch in mqtags:
2574 2574 if patch[1] in tags:
2575 2575 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
2576 2576 % patch[1])
2577 2577 else:
2578 2578 tags[patch[1]] = patch[0]
2579 2579
2580 2580 return result
2581 2581
2582 2582 def _branchtags(self, partial, lrev):
2583 2583 q = self.mq
2584 2584 if not q.applied:
2585 2585 return super(mqrepo, self)._branchtags(partial, lrev)
2586 2586
2587 2587 cl = self.changelog
2588 2588 qbasenode = q.applied[0].node
2589 2589 if qbasenode not in cl.nodemap:
2590 2590 self.ui.warn(_('mq status file refers to unknown node %s\n')
2591 2591 % short(qbasenode))
2592 2592 return super(mqrepo, self)._branchtags(partial, lrev)
2593 2593
2594 2594 qbase = cl.rev(qbasenode)
2595 2595 start = lrev + 1
2596 2596 if start < qbase:
2597 2597 # update the cache (excluding the patches) and save it
2598 2598 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
2599 2599 self._updatebranchcache(partial, ctxgen)
2600 2600 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
2601 2601 start = qbase
2602 2602 # if start = qbase, the cache is as updated as it should be.
2603 2603 # if start > qbase, the cache includes (part of) the patches.
2604 2604 # we might as well use it, but we won't save it.
2605 2605
2606 2606 # update the cache up to the tip
2607 2607 ctxgen = (self[r] for r in xrange(start, len(cl)))
2608 2608 self._updatebranchcache(partial, ctxgen)
2609 2609
2610 2610 return partial
2611 2611
2612 2612 if repo.local():
2613 2613 repo.__class__ = mqrepo
2614 2614
2615 2615 def mqimport(orig, ui, repo, *args, **kwargs):
2616 2616 if (hasattr(repo, 'abort_if_wdir_patched')
2617 2617 and not kwargs.get('no_commit', False)):
2618 2618 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
2619 2619 kwargs.get('force'))
2620 2620 return orig(ui, repo, *args, **kwargs)
2621 2621
2622 2622 def mqinit(orig, ui, *args, **kwargs):
2623 2623 mq = kwargs.pop('mq', None)
2624 2624
2625 2625 if not mq:
2626 2626 return orig(ui, *args, **kwargs)
2627 2627
2628 2628 if args:
2629 2629 repopath = args[0]
2630 2630 if not hg.islocal(repopath):
2631 2631 raise util.Abort(_('only a local queue repository '
2632 2632 'may be initialized'))
2633 2633 else:
2634 2634 repopath = cmdutil.findrepo(os.getcwd())
2635 2635 if not repopath:
2636 2636 raise util.Abort(_('There is no Mercurial repository here '
2637 2637 '(.hg not found)'))
2638 2638 repo = hg.repository(ui, repopath)
2639 2639 return qinit(ui, repo, True)
2640 2640
2641 2641 def mqcommand(orig, ui, repo, *args, **kwargs):
2642 2642 """Add --mq option to operate on patch repository instead of main"""
2643 2643
2644 2644 # some commands do not like getting unknown options
2645 2645 mq = kwargs.pop('mq', None)
2646 2646
2647 2647 if not mq:
2648 2648 return orig(ui, repo, *args, **kwargs)
2649 2649
2650 2650 q = repo.mq
2651 2651 r = q.qrepo()
2652 2652 if not r:
2653 2653 raise util.Abort('no queue repository')
2654 2654 return orig(r.ui, r, *args, **kwargs)
2655 2655
2656 2656 def uisetup(ui):
2657 2657 mqopt = [('', 'mq', None, _("operate on patch repository"))]
2658 2658
2659 2659 extensions.wrapcommand(commands.table, 'import', mqimport)
2660 2660
2661 2661 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
2662 2662 entry[1].extend(mqopt)
2663 2663
2664 2664 norepo = commands.norepo.split(" ")
2665 2665 for cmd in commands.table.keys():
2666 2666 cmd = cmdutil.parsealiases(cmd)[0]
2667 2667 if cmd in norepo:
2668 2668 continue
2669 2669 entry = extensions.wrapcommand(commands.table, cmd, mqcommand)
2670 2670 entry[1].extend(mqopt)
2671 2671
2672 2672 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
2673 2673
2674 2674 cmdtable = {
2675 2675 "qapplied":
2676 2676 (applied,
2677 2677 [('1', 'last', None, _('show only the last patch'))] + seriesopts,
2678 2678 _('hg qapplied [-1] [-s] [PATCH]')),
2679 2679 "qclone":
2680 2680 (clone,
2681 2681 [('', 'pull', None, _('use pull protocol to copy metadata')),
2682 2682 ('U', 'noupdate', None, _('do not update the new working directories')),
2683 2683 ('', 'uncompressed', None,
2684 2684 _('use uncompressed transfer (fast over LAN)')),
2685 2685 ('p', 'patches', '', _('location of source patch repository')),
2686 2686 ] + commands.remoteopts,
2687 2687 _('hg qclone [OPTION]... SOURCE [DEST]')),
2688 2688 "qcommit|qci":
2689 2689 (commit,
2690 2690 commands.table["^commit|ci"][1],
2691 2691 _('hg qcommit [OPTION]... [FILE]...')),
2692 2692 "^qdiff":
2693 2693 (diff,
2694 2694 commands.diffopts + commands.diffopts2 + commands.walkopts,
2695 2695 _('hg qdiff [OPTION]... [FILE]...')),
2696 2696 "qdelete|qremove|qrm":
2697 2697 (delete,
2698 2698 [('k', 'keep', None, _('keep patch file')),
2699 2699 ('r', 'rev', [], _('stop managing a revision (DEPRECATED)'))],
2700 2700 _('hg qdelete [-k] [-r REV]... [PATCH]...')),
2701 2701 'qfold':
2702 2702 (fold,
2703 2703 [('e', 'edit', None, _('edit patch header')),
2704 2704 ('k', 'keep', None, _('keep folded patch files')),
2705 2705 ] + commands.commitopts,
2706 2706 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...')),
2707 2707 'qgoto':
2708 2708 (goto,
2709 2709 [('f', 'force', None, _('overwrite any local changes'))],
2710 2710 _('hg qgoto [OPTION]... PATCH')),
2711 2711 'qguard':
2712 2712 (guard,
2713 2713 [('l', 'list', None, _('list all patches and guards')),
2714 2714 ('n', 'none', None, _('drop all guards'))],
2715 2715 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]')),
2716 2716 'qheader': (header, [], _('hg qheader [PATCH]')),
2717 2717 "qimport":
2718 2718 (qimport,
2719 2719 [('e', 'existing', None, _('import file in patch directory')),
2720 2720 ('n', 'name', '', _('name of patch file')),
2721 2721 ('f', 'force', None, _('overwrite existing files')),
2722 2722 ('r', 'rev', [], _('place existing revisions under mq control')),
2723 2723 ('g', 'git', None, _('use git extended diff format')),
2724 2724 ('P', 'push', None, _('qpush after importing'))],
2725 2725 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...')),
2726 2726 "^qinit":
2727 2727 (init,
2728 2728 [('c', 'create-repo', None, _('create queue repository'))],
2729 2729 _('hg qinit [-c]')),
2730 2730 "^qnew":
2731 2731 (new,
2732 2732 [('e', 'edit', None, _('edit commit message')),
2733 2733 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2734 2734 ('g', 'git', None, _('use git extended diff format')),
2735 2735 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2736 2736 ('u', 'user', '', _('add "From: <given user>" to patch')),
2737 2737 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2738 2738 ('d', 'date', '', _('add "Date: <given date>" to patch'))
2739 2739 ] + commands.walkopts + commands.commitopts,
2740 2740 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...')),
2741 2741 "qnext": (next, [] + seriesopts, _('hg qnext [-s]')),
2742 2742 "qprev": (prev, [] + seriesopts, _('hg qprev [-s]')),
2743 2743 "^qpop":
2744 2744 (pop,
2745 2745 [('a', 'all', None, _('pop all patches')),
2746 2746 ('n', 'name', '', _('queue name to pop (DEPRECATED)')),
2747 2747 ('f', 'force', None, _('forget any local changes to patched files'))],
2748 2748 _('hg qpop [-a] [-n NAME] [-f] [PATCH | INDEX]')),
2749 2749 "^qpush":
2750 2750 (push,
2751 2751 [('f', 'force', None, _('apply if the patch has rejects')),
2752 2752 ('l', 'list', None, _('list patch name in commit text')),
2753 2753 ('a', 'all', None, _('apply all patches')),
2754 2754 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2755 2755 ('n', 'name', '', _('merge queue name (DEPRECATED)'))],
2756 2756 _('hg qpush [-f] [-l] [-a] [-m] [-n NAME] [PATCH | INDEX]')),
2757 2757 "^qrefresh":
2758 2758 (refresh,
2759 2759 [('e', 'edit', None, _('edit commit message')),
2760 2760 ('g', 'git', None, _('use git extended diff format')),
2761 2761 ('s', 'short', None,
2762 2762 _('refresh only files already in the patch and specified files')),
2763 2763 ('U', 'currentuser', None,
2764 2764 _('add/update author field in patch with current user')),
2765 2765 ('u', 'user', '',
2766 2766 _('add/update author field in patch with given user')),
2767 2767 ('D', 'currentdate', None,
2768 2768 _('add/update date field in patch with current date')),
2769 2769 ('d', 'date', '',
2770 2770 _('add/update date field in patch with given date'))
2771 2771 ] + commands.walkopts + commands.commitopts,
2772 2772 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...')),
2773 2773 'qrename|qmv':
2774 2774 (rename, [], _('hg qrename PATCH1 [PATCH2]')),
2775 2775 "qrestore":
2776 2776 (restore,
2777 2777 [('d', 'delete', None, _('delete save entry')),
2778 2778 ('u', 'update', None, _('update queue working directory'))],
2779 2779 _('hg qrestore [-d] [-u] REV')),
2780 2780 "qsave":
2781 2781 (save,
2782 2782 [('c', 'copy', None, _('copy patch directory')),
2783 2783 ('n', 'name', '', _('copy directory name')),
2784 2784 ('e', 'empty', None, _('clear queue status file')),
2785 2785 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2786 2786 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]')),
2787 2787 "qselect":
2788 2788 (select,
2789 2789 [('n', 'none', None, _('disable all guards')),
2790 2790 ('s', 'series', None, _('list all guards in series file')),
2791 2791 ('', 'pop', None, _('pop to before first guarded applied patch')),
2792 2792 ('', 'reapply', None, _('pop, then reapply patches'))],
2793 2793 _('hg qselect [OPTION]... [GUARD]...')),
2794 2794 "qseries":
2795 2795 (series,
2796 2796 [('m', 'missing', None, _('print patches not in series')),
2797 2797 ] + seriesopts,
2798 2798 _('hg qseries [-ms]')),
2799 2799 "strip":
2800 2800 (strip,
2801 2801 [('f', 'force', None, _('force removal with local changes')),
2802 2802 ('b', 'backup', None, _('bundle unrelated changesets')),
2803 2803 ('n', 'nobackup', None, _('no backups'))],
2804 2804 _('hg strip [-f] [-b] [-n] REV')),
2805 2805 "qtop": (top, [] + seriesopts, _('hg qtop [-s]')),
2806 2806 "qunapplied":
2807 2807 (unapplied,
2808 2808 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
2809 2809 _('hg qunapplied [-1] [-s] [PATCH]')),
2810 2810 "qfinish":
2811 2811 (finish,
2812 2812 [('a', 'applied', None, _('finish all applied changesets'))],
2813 2813 _('hg qfinish [-a] [REV]...')),
2814 2814 }
2815 2815
2816 2816 colortable = {'qguard.negative': 'red',
2817 2817 'qguard.positive': 'yellow',
2818 2818 'qguard.unguarded': 'green',
2819 2819 'qseries.applied': 'blue bold underline',
2820 2820 'qseries.guarded': 'black bold',
2821 2821 'qseries.missing': 'red bold',
2822 2822 'qseries.unapplied': 'black bold'}
@@ -1,70 +1,70
1 1 # pager.py - display output using a pager
2 2 #
3 3 # Copyright 2008 David Soria Parra <dsp@php.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 # To load the extension, add it to your .hgrc file:
9 9 #
10 10 # [extension]
11 11 # pager =
12 12 #
13 13 # Run "hg help pager" to get info on configuration.
14 14
15 15 '''browse command output with an external pager
16 16
17 17 To set the pager that should be used, set the application variable::
18 18
19 19 [pager]
20 20 pager = LESS='FSRX' less
21 21
22 22 If no pager is set, the pager extensions uses the environment variable
23 23 $PAGER. If neither pager.pager, nor $PAGER is set, no pager is used.
24 24
25 25 If you notice "BROKEN PIPE" error messages, you can disable them by
26 26 setting::
27 27
28 28 [pager]
29 29 quiet = True
30 30
31 31 You can disable the pager for certain commands by adding them to the
32 32 pager.ignore list::
33 33
34 34 [pager]
35 35 ignore = version, help, update
36 36
37 37 You can also enable the pager only for certain commands using
38 38 pager.attend. Below is the default list of commands to be paged::
39 39
40 40 [pager]
41 41 attend = annotate, cat, diff, export, glog, log, qdiff
42 42
43 43 Setting pager.attend to an empty value will cause all commands to be
44 44 paged.
45 45
46 46 If pager.attend is present, pager.ignore will be ignored.
47 47
48 To ignore global commands like "hg version" or "hg help", you have to
49 specify them in the global .hgrc
48 To ignore global commands like :hg:`version` or :hg:`help`, you have
49 to specify them in the global .hgrc
50 50 '''
51 51
52 52 import sys, os, signal
53 53 from mercurial import dispatch, util, extensions
54 54
55 55 def uisetup(ui):
56 56 def pagecmd(orig, ui, options, cmd, cmdfunc):
57 57 p = ui.config("pager", "pager", os.environ.get("PAGER"))
58 58 if p and sys.stdout.isatty() and '--debugger' not in sys.argv:
59 59 attend = ui.configlist('pager', 'attend', attended)
60 60 if (cmd in attend or
61 61 (cmd not in ui.configlist('pager', 'ignore') and not attend)):
62 62 ui.setconfig('ui', 'interactive', False)
63 63 sys.stderr = sys.stdout = util.popen(p, "wb")
64 64 if ui.configbool('pager', 'quiet'):
65 65 signal.signal(signal.SIGPIPE, signal.SIG_DFL)
66 66 return orig(ui, options, cmd, cmdfunc)
67 67
68 68 extensions.wrapfunction(dispatch, '_runcommand', pagecmd)
69 69
70 70 attended = ['annotate', 'cat', 'diff', 'export', 'glog', 'log', 'qdiff']
@@ -1,527 +1,527
1 1 # patchbomb.py - sending Mercurial changesets as patch emails
2 2 #
3 3 # Copyright 2005-2009 Matt Mackall <mpm@selenic.com> and others
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 '''command to send changesets as (a series of) patch emails
9 9
10 10 The series is started off with a "[PATCH 0 of N]" introduction, which
11 11 describes the series as a whole.
12 12
13 13 Each patch email has a Subject line of "[PATCH M of N] ...", using the
14 14 first line of the changeset description as the subject text. The
15 15 message contains two or three body parts:
16 16
17 17 - The changeset description.
18 18 - [Optional] The result of running diffstat on the patch.
19 - The patch itself, as generated by "hg export".
19 - The patch itself, as generated by :hg:`export`.
20 20
21 21 Each message refers to the first in the series using the In-Reply-To
22 22 and References headers, so they will show up as a sequence in threaded
23 23 mail and news readers, and in mail archives.
24 24
25 25 With the -d/--diffstat option, you will be prompted for each changeset
26 26 with a diffstat summary and the changeset summary, so you can be sure
27 27 you are sending the right changes.
28 28
29 29 To configure other defaults, add a section like this to your hgrc
30 30 file::
31 31
32 32 [email]
33 33 from = My Name <my@email>
34 34 to = recipient1, recipient2, ...
35 35 cc = cc1, cc2, ...
36 36 bcc = bcc1, bcc2, ...
37 37
38 38 Use ``[patchbomb]`` as configuration section name if you need to
39 39 override global ``[email]`` address settings.
40 40
41 Then you can use the "hg email" command to mail a series of changesets
42 as a patchbomb.
41 Then you can use the :hg:`email` command to mail a series of
42 changesets as a patchbomb.
43 43
44 44 To avoid sending patches prematurely, it is a good idea to first run
45 the "email" command with the "-n" option (test only). You will be
45 the :hg:`email` command with the "-n" option (test only). You will be
46 46 prompted for an email recipient address, a subject and an introductory
47 47 message describing the patches of your patchbomb. Then when all is
48 48 done, patchbomb messages are displayed. If the PAGER environment
49 49 variable is set, your pager will be fired up once for each patchbomb
50 50 message, so you can verify everything is alright.
51 51
52 52 The -m/--mbox option is also very useful. Instead of previewing each
53 53 patchbomb message in a pager or sending the messages directly, it will
54 54 create a UNIX mailbox file with the patch emails. This mailbox file
55 55 can be previewed with any mail user agent which supports UNIX mbox
56 56 files, e.g. with mutt::
57 57
58 58 % mutt -R -f mbox
59 59
60 60 When you are previewing the patchbomb messages, you can use ``formail``
61 61 (a utility that is commonly installed as part of the procmail
62 62 package), to send each message out::
63 63
64 64 % formail -s sendmail -bm -t < mbox
65 65
66 66 That should be all. Now your patchbomb is on its way out.
67 67
68 68 You can also either configure the method option in the email section
69 69 to be a sendmail compatible mailer or fill out the [smtp] section so
70 70 that the patchbomb extension can automatically send patchbombs
71 71 directly from the commandline. See the [email] and [smtp] sections in
72 72 hgrc(5) for details.
73 73 '''
74 74
75 75 import os, errno, socket, tempfile, cStringIO, time
76 76 import email.MIMEMultipart, email.MIMEBase
77 77 import email.Utils, email.Encoders, email.Generator
78 78 from mercurial import cmdutil, commands, hg, mail, patch, util
79 79 from mercurial.i18n import _
80 80 from mercurial.node import bin
81 81
82 82 def prompt(ui, prompt, default=None, rest=':'):
83 83 if not ui.interactive():
84 84 if default is not None:
85 85 return default
86 86 raise util.Abort(_("%s Please enter a valid value" % (prompt + rest)))
87 87 if default:
88 88 prompt += ' [%s]' % default
89 89 prompt += rest
90 90 while True:
91 91 r = ui.prompt(prompt, default=default)
92 92 if r:
93 93 return r
94 94 if default is not None:
95 95 return default
96 96 ui.warn(_('Please enter a valid value.\n'))
97 97
98 98 def cdiffstat(ui, summary, patchlines):
99 99 s = patch.diffstat(patchlines)
100 100 if summary:
101 101 ui.write(summary, '\n')
102 102 ui.write(s, '\n')
103 103 ans = prompt(ui, _('does the diffstat above look okay?'), 'y')
104 104 if not ans.lower().startswith('y'):
105 105 raise util.Abort(_('diffstat rejected'))
106 106 return s
107 107
108 108 def introneeded(opts, number):
109 109 '''is an introductory message required?'''
110 110 return number > 1 or opts.get('intro') or opts.get('desc')
111 111
112 112 def makepatch(ui, repo, patch, opts, _charsets, idx, total, patchname=None):
113 113
114 114 desc = []
115 115 node = None
116 116 body = ''
117 117
118 118 for line in patch:
119 119 if line.startswith('#'):
120 120 if line.startswith('# Node ID'):
121 121 node = line.split()[-1]
122 122 continue
123 123 if line.startswith('diff -r') or line.startswith('diff --git'):
124 124 break
125 125 desc.append(line)
126 126
127 127 if not patchname and not node:
128 128 raise ValueError
129 129
130 130 if opts.get('attach'):
131 131 body = ('\n'.join(desc[1:]).strip() or
132 132 'Patch subject is complete summary.')
133 133 body += '\n\n\n'
134 134
135 135 if opts.get('plain'):
136 136 while patch and patch[0].startswith('# '):
137 137 patch.pop(0)
138 138 if patch:
139 139 patch.pop(0)
140 140 while patch and not patch[0].strip():
141 141 patch.pop(0)
142 142
143 143 if opts.get('diffstat'):
144 144 body += cdiffstat(ui, '\n'.join(desc), patch) + '\n\n'
145 145
146 146 if opts.get('attach') or opts.get('inline'):
147 147 msg = email.MIMEMultipart.MIMEMultipart()
148 148 if body:
149 149 msg.attach(mail.mimeencode(ui, body, _charsets, opts.get('test')))
150 150 p = mail.mimetextpatch('\n'.join(patch), 'x-patch', opts.get('test'))
151 151 binnode = bin(node)
152 152 # if node is mq patch, it will have the patch file's name as a tag
153 153 if not patchname:
154 154 patchtags = [t for t in repo.nodetags(binnode)
155 155 if t.endswith('.patch') or t.endswith('.diff')]
156 156 if patchtags:
157 157 patchname = patchtags[0]
158 158 elif total > 1:
159 159 patchname = cmdutil.make_filename(repo, '%b-%n.patch',
160 160 binnode, seqno=idx, total=total)
161 161 else:
162 162 patchname = cmdutil.make_filename(repo, '%b.patch', binnode)
163 163 disposition = 'inline'
164 164 if opts.get('attach'):
165 165 disposition = 'attachment'
166 166 p['Content-Disposition'] = disposition + '; filename=' + patchname
167 167 msg.attach(p)
168 168 else:
169 169 body += '\n'.join(patch)
170 170 msg = mail.mimetextpatch(body, display=opts.get('test'))
171 171
172 172 flag = ' '.join(opts.get('flag'))
173 173 if flag:
174 174 flag = ' ' + flag
175 175
176 176 subj = desc[0].strip().rstrip('. ')
177 177 if not introneeded(opts, total):
178 178 subj = '[PATCH%s] %s' % (flag, opts.get('subject') or subj)
179 179 else:
180 180 tlen = len(str(total))
181 181 subj = '[PATCH %0*d of %d%s] %s' % (tlen, idx, total, flag, subj)
182 182 msg['Subject'] = mail.headencode(ui, subj, _charsets, opts.get('test'))
183 183 msg['X-Mercurial-Node'] = node
184 184 return msg, subj
185 185
186 186 def patchbomb(ui, repo, *revs, **opts):
187 187 '''send changesets by email
188 188
189 189 By default, diffs are sent in the format generated by hg export,
190 190 one per message. The series starts with a "[PATCH 0 of N]"
191 191 introduction, which describes the series as a whole.
192 192
193 193 Each patch email has a Subject line of "[PATCH M of N] ...", using
194 194 the first line of the changeset description as the subject text.
195 195 The message contains two or three parts. First, the changeset
196 196 description. Next, (optionally) if the diffstat program is
197 197 installed and -d/--diffstat is used, the result of running
198 198 diffstat on the patch. Finally, the patch itself, as generated by
199 "hg export".
199 :hg:`export`.
200 200
201 201 By default the patch is included as text in the email body for
202 202 easy reviewing. Using the -a/--attach option will instead create
203 203 an attachment for the patch. With -i/--inline an inline attachment
204 204 will be created.
205 205
206 206 With -o/--outgoing, emails will be generated for patches not found
207 207 in the destination repository (or only those which are ancestors
208 208 of the specified revisions if any are provided)
209 209
210 210 With -b/--bundle, changesets are selected as for --outgoing, but a
211 211 single email containing a binary Mercurial bundle as an attachment
212 212 will be sent.
213 213
214 214 Examples::
215 215
216 216 hg email -r 3000 # send patch 3000 only
217 217 hg email -r 3000 -r 3001 # send patches 3000 and 3001
218 218 hg email -r 3000:3005 # send patches 3000 through 3005
219 219 hg email 3000 # send patch 3000 (deprecated)
220 220
221 221 hg email -o # send all patches not in default
222 222 hg email -o DEST # send all patches not in DEST
223 223 hg email -o -r 3000 # send all ancestors of 3000 not in default
224 224 hg email -o -r 3000 DEST # send all ancestors of 3000 not in DEST
225 225
226 226 hg email -b # send bundle of all patches not in default
227 227 hg email -b DEST # send bundle of all patches not in DEST
228 228 hg email -b -r 3000 # bundle of all ancestors of 3000 not in default
229 229 hg email -b -r 3000 DEST # bundle of all ancestors of 3000 not in DEST
230 230
231 231 Before using this command, you will need to enable email in your
232 232 hgrc. See the [email] section in hgrc(5) for details.
233 233 '''
234 234
235 235 _charsets = mail._charsets(ui)
236 236
237 237 def outgoing(dest, revs):
238 238 '''Return the revisions present locally but not in dest'''
239 239 dest = ui.expandpath(dest or 'default-push', dest or 'default')
240 240 dest, branches = hg.parseurl(dest)
241 241 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
242 242 if revs:
243 243 revs = [repo.lookup(rev) for rev in revs]
244 244 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
245 245 ui.status(_('comparing with %s\n') % dest)
246 246 o = repo.findoutgoing(other)
247 247 if not o:
248 248 ui.status(_("no changes found\n"))
249 249 return []
250 250 o = repo.changelog.nodesbetween(o, revs)[0]
251 251 return [str(repo.changelog.rev(r)) for r in o]
252 252
253 253 def getpatches(revs):
254 254 for r in cmdutil.revrange(repo, revs):
255 255 output = cStringIO.StringIO()
256 256 cmdutil.export(repo, [r], fp=output,
257 257 opts=patch.diffopts(ui, opts))
258 258 yield output.getvalue().split('\n')
259 259
260 260 def getbundle(dest):
261 261 tmpdir = tempfile.mkdtemp(prefix='hg-email-bundle-')
262 262 tmpfn = os.path.join(tmpdir, 'bundle')
263 263 try:
264 264 commands.bundle(ui, repo, tmpfn, dest, **opts)
265 265 return open(tmpfn, 'rb').read()
266 266 finally:
267 267 try:
268 268 os.unlink(tmpfn)
269 269 except:
270 270 pass
271 271 os.rmdir(tmpdir)
272 272
273 273 if not (opts.get('test') or opts.get('mbox')):
274 274 # really sending
275 275 mail.validateconfig(ui)
276 276
277 277 if not (revs or opts.get('rev')
278 278 or opts.get('outgoing') or opts.get('bundle')
279 279 or opts.get('patches')):
280 280 raise util.Abort(_('specify at least one changeset with -r or -o'))
281 281
282 282 if opts.get('outgoing') and opts.get('bundle'):
283 283 raise util.Abort(_("--outgoing mode always on with --bundle;"
284 284 " do not re-specify --outgoing"))
285 285
286 286 if opts.get('outgoing') or opts.get('bundle'):
287 287 if len(revs) > 1:
288 288 raise util.Abort(_("too many destinations"))
289 289 dest = revs and revs[0] or None
290 290 revs = []
291 291
292 292 if opts.get('rev'):
293 293 if revs:
294 294 raise util.Abort(_('use only one form to specify the revision'))
295 295 revs = opts.get('rev')
296 296
297 297 if opts.get('outgoing'):
298 298 revs = outgoing(dest, opts.get('rev'))
299 299 if opts.get('bundle'):
300 300 opts['revs'] = revs
301 301
302 302 # start
303 303 if opts.get('date'):
304 304 start_time = util.parsedate(opts.get('date'))
305 305 else:
306 306 start_time = util.makedate()
307 307
308 308 def genmsgid(id):
309 309 return '<%s.%s@%s>' % (id[:20], int(start_time[0]), socket.getfqdn())
310 310
311 311 def getdescription(body, sender):
312 312 if opts.get('desc'):
313 313 body = open(opts.get('desc')).read()
314 314 else:
315 315 ui.write(_('\nWrite the introductory message for the '
316 316 'patch series.\n\n'))
317 317 body = ui.edit(body, sender)
318 318 return body
319 319
320 320 def getpatchmsgs(patches, patchnames=None):
321 321 jumbo = []
322 322 msgs = []
323 323
324 324 ui.write(_('This patch series consists of %d patches.\n\n')
325 325 % len(patches))
326 326
327 327 name = None
328 328 for i, p in enumerate(patches):
329 329 jumbo.extend(p)
330 330 if patchnames:
331 331 name = patchnames[i]
332 332 msg = makepatch(ui, repo, p, opts, _charsets, i + 1,
333 333 len(patches), name)
334 334 msgs.append(msg)
335 335
336 336 if introneeded(opts, len(patches)):
337 337 tlen = len(str(len(patches)))
338 338
339 339 flag = ' '.join(opts.get('flag'))
340 340 if flag:
341 341 subj = '[PATCH %0*d of %d %s]' % (tlen, 0, len(patches), flag)
342 342 else:
343 343 subj = '[PATCH %0*d of %d]' % (tlen, 0, len(patches))
344 344 subj += ' ' + (opts.get('subject') or
345 345 prompt(ui, 'Subject: ', rest=subj))
346 346
347 347 body = ''
348 348 if opts.get('diffstat'):
349 349 d = cdiffstat(ui, _('Final summary:\n'), jumbo)
350 350 if d:
351 351 body = '\n' + d
352 352
353 353 body = getdescription(body, sender)
354 354 msg = mail.mimeencode(ui, body, _charsets, opts.get('test'))
355 355 msg['Subject'] = mail.headencode(ui, subj, _charsets,
356 356 opts.get('test'))
357 357
358 358 msgs.insert(0, (msg, subj))
359 359 return msgs
360 360
361 361 def getbundlemsgs(bundle):
362 362 subj = (opts.get('subject')
363 363 or prompt(ui, 'Subject:', 'A bundle for your repository'))
364 364
365 365 body = getdescription('', sender)
366 366 msg = email.MIMEMultipart.MIMEMultipart()
367 367 if body:
368 368 msg.attach(mail.mimeencode(ui, body, _charsets, opts.get('test')))
369 369 datapart = email.MIMEBase.MIMEBase('application', 'x-mercurial-bundle')
370 370 datapart.set_payload(bundle)
371 371 bundlename = '%s.hg' % opts.get('bundlename', 'bundle')
372 372 datapart.add_header('Content-Disposition', 'attachment',
373 373 filename=bundlename)
374 374 email.Encoders.encode_base64(datapart)
375 375 msg.attach(datapart)
376 376 msg['Subject'] = mail.headencode(ui, subj, _charsets, opts.get('test'))
377 377 return [(msg, subj)]
378 378
379 379 sender = (opts.get('from') or ui.config('email', 'from') or
380 380 ui.config('patchbomb', 'from') or
381 381 prompt(ui, 'From', ui.username()))
382 382
383 383 # internal option used by pbranches
384 384 patches = opts.get('patches')
385 385 if patches:
386 386 msgs = getpatchmsgs(patches, opts.get('patchnames'))
387 387 elif opts.get('bundle'):
388 388 msgs = getbundlemsgs(getbundle(dest))
389 389 else:
390 390 msgs = getpatchmsgs(list(getpatches(revs)))
391 391
392 392 def getaddrs(opt, prpt=None, default=None):
393 393 if opts.get(opt):
394 394 return mail.addrlistencode(ui, opts.get(opt), _charsets,
395 395 opts.get('test'))
396 396
397 397 addrs = (ui.config('email', opt) or
398 398 ui.config('patchbomb', opt) or '')
399 399 if not addrs and prpt:
400 400 addrs = prompt(ui, prpt, default)
401 401
402 402 return mail.addrlistencode(ui, [addrs], _charsets, opts.get('test'))
403 403
404 404 to = getaddrs('to', 'To')
405 405 cc = getaddrs('cc', 'Cc', '')
406 406 bcc = getaddrs('bcc')
407 407
408 408 ui.write('\n')
409 409
410 410 parent = opts.get('in_reply_to') or None
411 411 # angle brackets may be omitted, they're not semantically part of the msg-id
412 412 if parent is not None:
413 413 if not parent.startswith('<'):
414 414 parent = '<' + parent
415 415 if not parent.endswith('>'):
416 416 parent += '>'
417 417
418 418 first = True
419 419
420 420 sender_addr = email.Utils.parseaddr(sender)[1]
421 421 sender = mail.addressencode(ui, sender, _charsets, opts.get('test'))
422 422 sendmail = None
423 423 for m, subj in msgs:
424 424 try:
425 425 m['Message-Id'] = genmsgid(m['X-Mercurial-Node'])
426 426 except TypeError:
427 427 m['Message-Id'] = genmsgid('patchbomb')
428 428 if parent:
429 429 m['In-Reply-To'] = parent
430 430 m['References'] = parent
431 431 if first:
432 432 parent = m['Message-Id']
433 433 first = False
434 434
435 435 m['User-Agent'] = 'Mercurial-patchbomb/%s' % util.version()
436 436 m['Date'] = email.Utils.formatdate(start_time[0], localtime=True)
437 437
438 438 start_time = (start_time[0] + 1, start_time[1])
439 439 m['From'] = sender
440 440 m['To'] = ', '.join(to)
441 441 if cc:
442 442 m['Cc'] = ', '.join(cc)
443 443 if bcc:
444 444 m['Bcc'] = ', '.join(bcc)
445 445 if opts.get('test'):
446 446 ui.status(_('Displaying '), subj, ' ...\n')
447 447 ui.flush()
448 448 if 'PAGER' in os.environ:
449 449 fp = util.popen(os.environ['PAGER'], 'w')
450 450 else:
451 451 fp = ui
452 452 generator = email.Generator.Generator(fp, mangle_from_=False)
453 453 try:
454 454 generator.flatten(m, 0)
455 455 fp.write('\n')
456 456 except IOError, inst:
457 457 if inst.errno != errno.EPIPE:
458 458 raise
459 459 if fp is not ui:
460 460 fp.close()
461 461 elif opts.get('mbox'):
462 462 ui.status(_('Writing '), subj, ' ...\n')
463 463 fp = open(opts.get('mbox'), 'In-Reply-To' in m and 'ab+' or 'wb+')
464 464 generator = email.Generator.Generator(fp, mangle_from_=True)
465 465 # Should be time.asctime(), but Windows prints 2-characters day
466 466 # of month instead of one. Make them print the same thing.
467 467 date = time.strftime('%a %b %d %H:%M:%S %Y',
468 468 time.localtime(start_time[0]))
469 469 fp.write('From %s %s\n' % (sender_addr, date))
470 470 generator.flatten(m, 0)
471 471 fp.write('\n\n')
472 472 fp.close()
473 473 else:
474 474 if not sendmail:
475 475 sendmail = mail.connect(ui)
476 476 ui.status(_('Sending '), subj, ' ...\n')
477 477 # Exim does not remove the Bcc field
478 478 del m['Bcc']
479 479 fp = cStringIO.StringIO()
480 480 generator = email.Generator.Generator(fp, mangle_from_=False)
481 481 generator.flatten(m, 0)
482 482 sendmail(sender, to + bcc + cc, fp.getvalue())
483 483
484 484 emailopts = [
485 485 ('a', 'attach', None, _('send patches as attachments')),
486 486 ('i', 'inline', None, _('send patches as inline attachments')),
487 487 ('', 'bcc', [], _('email addresses of blind carbon copy recipients')),
488 488 ('c', 'cc', [], _('email addresses of copy recipients')),
489 489 ('d', 'diffstat', None, _('add diffstat output to messages')),
490 490 ('', 'date', '', _('use the given date as the sending date')),
491 491 ('', 'desc', '', _('use the given file as the series description')),
492 492 ('f', 'from', '', _('email address of sender')),
493 493 ('n', 'test', None, _('print messages that would be sent')),
494 494 ('m', 'mbox', '',
495 495 _('write messages to mbox file instead of sending them')),
496 496 ('s', 'subject', '',
497 497 _('subject of first message (intro or single patch)')),
498 498 ('', 'in-reply-to', '',
499 499 _('message identifier to reply to')),
500 500 ('', 'flag', [], _('flags to add in subject prefixes')),
501 501 ('t', 'to', [], _('email addresses of recipients')),
502 502 ]
503 503
504 504
505 505 cmdtable = {
506 506 "email":
507 507 (patchbomb,
508 508 [('g', 'git', None, _('use git extended diff format')),
509 509 ('', 'plain', None, _('omit hg patch header')),
510 510 ('o', 'outgoing', None,
511 511 _('send changes not found in the target repository')),
512 512 ('b', 'bundle', None,
513 513 _('send changes not in target as a binary bundle')),
514 514 ('', 'bundlename', 'bundle',
515 515 _('name of the bundle attachment file')),
516 516 ('r', 'rev', [], _('a revision to send')),
517 517 ('', 'force', None,
518 518 _('run even when remote repository is unrelated '
519 519 '(with -b/--bundle)')),
520 520 ('', 'base', [],
521 521 _('a base changeset to specify instead of a destination '
522 522 '(with -b/--bundle)')),
523 523 ('', 'intro', None,
524 524 _('send an introduction email for a single patch')),
525 525 ] + emailopts + commands.remoteopts,
526 526 _('hg email [OPTION]... [DEST]...'))
527 527 }
@@ -1,111 +1,111
1 1 # Copyright (C) 2006 - Marco Barisione <marco@barisione.org>
2 2 #
3 3 # This is a small extension for Mercurial (http://mercurial.selenic.com/)
4 4 # that removes files not known to mercurial
5 5 #
6 6 # This program was inspired by the "cvspurge" script contained in CVS
7 7 # utilities (http://www.red-bean.com/cvsutils/).
8 8 #
9 9 # For help on the usage of "hg purge" use:
10 10 # hg help purge
11 11 #
12 12 # This program is free software; you can redistribute it and/or modify
13 13 # it under the terms of the GNU General Public License as published by
14 14 # the Free Software Foundation; either version 2 of the License, or
15 15 # (at your option) any later version.
16 16 #
17 17 # This program is distributed in the hope that it will be useful,
18 18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 20 # GNU General Public License for more details.
21 21 #
22 22 # You should have received a copy of the GNU General Public License
23 23 # along with this program; if not, write to the Free Software
24 24 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 25
26 26 '''command to delete untracked files from the working directory'''
27 27
28 28 from mercurial import util, commands, cmdutil
29 29 from mercurial.i18n import _
30 30 import os, stat
31 31
32 32 def purge(ui, repo, *dirs, **opts):
33 33 '''removes files not tracked by Mercurial
34 34
35 35 Delete files not known to Mercurial. This is useful to test local
36 36 and uncommitted changes in an otherwise-clean source tree.
37 37
38 38 This means that purge will delete:
39 39
40 - Unknown files: files marked with "?" by "hg status"
40 - Unknown files: files marked with "?" by :hg:`status`
41 41 - Empty directories: in fact Mercurial ignores directories unless
42 42 they contain files under source control management
43 43
44 44 But it will leave untouched:
45 45
46 46 - Modified and unmodified tracked files
47 47 - Ignored files (unless --all is specified)
48 - New files added to the repository (with "hg add")
48 - New files added to the repository (with :hg:`add`)
49 49
50 50 If directories are given on the command line, only files in these
51 51 directories are considered.
52 52
53 53 Be careful with purge, as you could irreversibly delete some files
54 54 you forgot to add to the repository. If you only want to print the
55 55 list of files that this program would delete, use the --print
56 56 option.
57 57 '''
58 58 act = not opts['print']
59 59 eol = '\n'
60 60 if opts['print0']:
61 61 eol = '\0'
62 62 act = False # --print0 implies --print
63 63
64 64 def remove(remove_func, name):
65 65 if act:
66 66 try:
67 67 remove_func(repo.wjoin(name))
68 68 except OSError:
69 69 m = _('%s cannot be removed') % name
70 70 if opts['abort_on_err']:
71 71 raise util.Abort(m)
72 72 ui.warn(_('warning: %s\n') % m)
73 73 else:
74 74 ui.write('%s%s' % (name, eol))
75 75
76 76 def removefile(path):
77 77 try:
78 78 os.remove(path)
79 79 except OSError:
80 80 # read-only files cannot be unlinked under Windows
81 81 s = os.stat(path)
82 82 if (s.st_mode & stat.S_IWRITE) != 0:
83 83 raise
84 84 os.chmod(path, stat.S_IMODE(s.st_mode) | stat.S_IWRITE)
85 85 os.remove(path)
86 86
87 87 directories = []
88 88 match = cmdutil.match(repo, dirs, opts)
89 89 match.dir = directories.append
90 90 status = repo.status(match=match, ignored=opts['all'], unknown=True)
91 91
92 92 for f in sorted(status[4] + status[5]):
93 93 ui.note(_('Removing file %s\n') % f)
94 94 remove(removefile, f)
95 95
96 96 for f in sorted(directories, reverse=True):
97 97 if match(f) and not os.listdir(repo.wjoin(f)):
98 98 ui.note(_('Removing directory %s\n') % f)
99 99 remove(os.rmdir, f)
100 100
101 101 cmdtable = {
102 102 'purge|clean':
103 103 (purge,
104 104 [('a', 'abort-on-err', None, _('abort if an error occurs')),
105 105 ('', 'all', None, _('purge ignored files too')),
106 106 ('p', 'print', None, _('print filenames instead of deleting them')),
107 107 ('0', 'print0', None, _('end filenames with NUL, for use with xargs'
108 108 ' (implies -p/--print)')),
109 109 ] + commands.walkopts,
110 110 _('hg purge [OPTION]... [DIR]...'))
111 111 }
@@ -1,564 +1,564
1 1 # record.py
2 2 #
3 3 # Copyright 2007 Bryan O'Sullivan <bos@serpentine.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 '''commands to interactively select changes for commit/qrefresh'''
9 9
10 10 from mercurial.i18n import gettext, _
11 11 from mercurial import cmdutil, commands, extensions, hg, mdiff, patch
12 12 from mercurial import util
13 13 import copy, cStringIO, errno, operator, os, re, tempfile
14 14
15 15 lines_re = re.compile(r'@@ -(\d+),(\d+) \+(\d+),(\d+) @@\s*(.*)')
16 16
17 17 def scanpatch(fp):
18 18 """like patch.iterhunks, but yield different events
19 19
20 20 - ('file', [header_lines + fromfile + tofile])
21 21 - ('context', [context_lines])
22 22 - ('hunk', [hunk_lines])
23 23 - ('range', (-start,len, +start,len, diffp))
24 24 """
25 25 lr = patch.linereader(fp)
26 26
27 27 def scanwhile(first, p):
28 28 """scan lr while predicate holds"""
29 29 lines = [first]
30 30 while True:
31 31 line = lr.readline()
32 32 if not line:
33 33 break
34 34 if p(line):
35 35 lines.append(line)
36 36 else:
37 37 lr.push(line)
38 38 break
39 39 return lines
40 40
41 41 while True:
42 42 line = lr.readline()
43 43 if not line:
44 44 break
45 45 if line.startswith('diff --git a/'):
46 46 def notheader(line):
47 47 s = line.split(None, 1)
48 48 return not s or s[0] not in ('---', 'diff')
49 49 header = scanwhile(line, notheader)
50 50 fromfile = lr.readline()
51 51 if fromfile.startswith('---'):
52 52 tofile = lr.readline()
53 53 header += [fromfile, tofile]
54 54 else:
55 55 lr.push(fromfile)
56 56 yield 'file', header
57 57 elif line[0] == ' ':
58 58 yield 'context', scanwhile(line, lambda l: l[0] in ' \\')
59 59 elif line[0] in '-+':
60 60 yield 'hunk', scanwhile(line, lambda l: l[0] in '-+\\')
61 61 else:
62 62 m = lines_re.match(line)
63 63 if m:
64 64 yield 'range', m.groups()
65 65 else:
66 66 raise patch.PatchError('unknown patch content: %r' % line)
67 67
68 68 class header(object):
69 69 """patch header
70 70
71 71 XXX shoudn't we move this to mercurial/patch.py ?
72 72 """
73 73 diff_re = re.compile('diff --git a/(.*) b/(.*)$')
74 74 allhunks_re = re.compile('(?:index|new file|deleted file) ')
75 75 pretty_re = re.compile('(?:new file|deleted file) ')
76 76 special_re = re.compile('(?:index|new|deleted|copy|rename) ')
77 77
78 78 def __init__(self, header):
79 79 self.header = header
80 80 self.hunks = []
81 81
82 82 def binary(self):
83 83 for h in self.header:
84 84 if h.startswith('index '):
85 85 return True
86 86
87 87 def pretty(self, fp):
88 88 for h in self.header:
89 89 if h.startswith('index '):
90 90 fp.write(_('this modifies a binary file (all or nothing)\n'))
91 91 break
92 92 if self.pretty_re.match(h):
93 93 fp.write(h)
94 94 if self.binary():
95 95 fp.write(_('this is a binary file\n'))
96 96 break
97 97 if h.startswith('---'):
98 98 fp.write(_('%d hunks, %d lines changed\n') %
99 99 (len(self.hunks),
100 100 sum([h.added + h.removed for h in self.hunks])))
101 101 break
102 102 fp.write(h)
103 103
104 104 def write(self, fp):
105 105 fp.write(''.join(self.header))
106 106
107 107 def allhunks(self):
108 108 for h in self.header:
109 109 if self.allhunks_re.match(h):
110 110 return True
111 111
112 112 def files(self):
113 113 fromfile, tofile = self.diff_re.match(self.header[0]).groups()
114 114 if fromfile == tofile:
115 115 return [fromfile]
116 116 return [fromfile, tofile]
117 117
118 118 def filename(self):
119 119 return self.files()[-1]
120 120
121 121 def __repr__(self):
122 122 return '<header %s>' % (' '.join(map(repr, self.files())))
123 123
124 124 def special(self):
125 125 for h in self.header:
126 126 if self.special_re.match(h):
127 127 return True
128 128
129 129 def countchanges(hunk):
130 130 """hunk -> (n+,n-)"""
131 131 add = len([h for h in hunk if h[0] == '+'])
132 132 rem = len([h for h in hunk if h[0] == '-'])
133 133 return add, rem
134 134
135 135 class hunk(object):
136 136 """patch hunk
137 137
138 138 XXX shouldn't we merge this with patch.hunk ?
139 139 """
140 140 maxcontext = 3
141 141
142 142 def __init__(self, header, fromline, toline, proc, before, hunk, after):
143 143 def trimcontext(number, lines):
144 144 delta = len(lines) - self.maxcontext
145 145 if False and delta > 0:
146 146 return number + delta, lines[:self.maxcontext]
147 147 return number, lines
148 148
149 149 self.header = header
150 150 self.fromline, self.before = trimcontext(fromline, before)
151 151 self.toline, self.after = trimcontext(toline, after)
152 152 self.proc = proc
153 153 self.hunk = hunk
154 154 self.added, self.removed = countchanges(self.hunk)
155 155
156 156 def write(self, fp):
157 157 delta = len(self.before) + len(self.after)
158 158 if self.after and self.after[-1] == '\\ No newline at end of file\n':
159 159 delta -= 1
160 160 fromlen = delta + self.removed
161 161 tolen = delta + self.added
162 162 fp.write('@@ -%d,%d +%d,%d @@%s\n' %
163 163 (self.fromline, fromlen, self.toline, tolen,
164 164 self.proc and (' ' + self.proc)))
165 165 fp.write(''.join(self.before + self.hunk + self.after))
166 166
167 167 pretty = write
168 168
169 169 def filename(self):
170 170 return self.header.filename()
171 171
172 172 def __repr__(self):
173 173 return '<hunk %r@%d>' % (self.filename(), self.fromline)
174 174
175 175 def parsepatch(fp):
176 176 """patch -> [] of hunks """
177 177 class parser(object):
178 178 """patch parsing state machine"""
179 179 def __init__(self):
180 180 self.fromline = 0
181 181 self.toline = 0
182 182 self.proc = ''
183 183 self.header = None
184 184 self.context = []
185 185 self.before = []
186 186 self.hunk = []
187 187 self.stream = []
188 188
189 189 def addrange(self, (fromstart, fromend, tostart, toend, proc)):
190 190 self.fromline = int(fromstart)
191 191 self.toline = int(tostart)
192 192 self.proc = proc
193 193
194 194 def addcontext(self, context):
195 195 if self.hunk:
196 196 h = hunk(self.header, self.fromline, self.toline, self.proc,
197 197 self.before, self.hunk, context)
198 198 self.header.hunks.append(h)
199 199 self.stream.append(h)
200 200 self.fromline += len(self.before) + h.removed
201 201 self.toline += len(self.before) + h.added
202 202 self.before = []
203 203 self.hunk = []
204 204 self.proc = ''
205 205 self.context = context
206 206
207 207 def addhunk(self, hunk):
208 208 if self.context:
209 209 self.before = self.context
210 210 self.context = []
211 211 self.hunk = hunk
212 212
213 213 def newfile(self, hdr):
214 214 self.addcontext([])
215 215 h = header(hdr)
216 216 self.stream.append(h)
217 217 self.header = h
218 218
219 219 def finished(self):
220 220 self.addcontext([])
221 221 return self.stream
222 222
223 223 transitions = {
224 224 'file': {'context': addcontext,
225 225 'file': newfile,
226 226 'hunk': addhunk,
227 227 'range': addrange},
228 228 'context': {'file': newfile,
229 229 'hunk': addhunk,
230 230 'range': addrange},
231 231 'hunk': {'context': addcontext,
232 232 'file': newfile,
233 233 'range': addrange},
234 234 'range': {'context': addcontext,
235 235 'hunk': addhunk},
236 236 }
237 237
238 238 p = parser()
239 239
240 240 state = 'context'
241 241 for newstate, data in scanpatch(fp):
242 242 try:
243 243 p.transitions[state][newstate](p, data)
244 244 except KeyError:
245 245 raise patch.PatchError('unhandled transition: %s -> %s' %
246 246 (state, newstate))
247 247 state = newstate
248 248 return p.finished()
249 249
250 250 def filterpatch(ui, chunks):
251 251 """Interactively filter patch chunks into applied-only chunks"""
252 252 chunks = list(chunks)
253 253 chunks.reverse()
254 254 seen = set()
255 255 def consumefile():
256 256 """fetch next portion from chunks until a 'header' is seen
257 257 NB: header == new-file mark
258 258 """
259 259 consumed = []
260 260 while chunks:
261 261 if isinstance(chunks[-1], header):
262 262 break
263 263 else:
264 264 consumed.append(chunks.pop())
265 265 return consumed
266 266
267 267 resp_all = [None] # this two are changed from inside prompt,
268 268 resp_file = [None] # so can't be usual variables
269 269 applied = {} # 'filename' -> [] of chunks
270 270 def prompt(query):
271 271 """prompt query, and process base inputs
272 272
273 273 - y/n for the rest of file
274 274 - y/n for the rest
275 275 - ? (help)
276 276 - q (quit)
277 277
278 278 Returns True/False and sets reps_all and resp_file as
279 279 appropriate.
280 280 """
281 281 if resp_all[0] is not None:
282 282 return resp_all[0]
283 283 if resp_file[0] is not None:
284 284 return resp_file[0]
285 285 while True:
286 286 resps = _('[Ynsfdaq?]')
287 287 choices = (_('&Yes, record this change'),
288 288 _('&No, skip this change'),
289 289 _('&Skip remaining changes to this file'),
290 290 _('Record remaining changes to this &file'),
291 291 _('&Done, skip remaining changes and files'),
292 292 _('Record &all changes to all remaining files'),
293 293 _('&Quit, recording no changes'),
294 294 _('&?'))
295 295 r = ui.promptchoice("%s %s" % (query, resps), choices)
296 296 ui.write("\n")
297 297 if r == 7: # ?
298 298 doc = gettext(record.__doc__)
299 299 c = doc.find(_('y - record this change'))
300 300 for l in doc[c:].splitlines():
301 301 if l:
302 302 ui.write(l.strip(), '\n')
303 303 continue
304 304 elif r == 0: # yes
305 305 ret = True
306 306 elif r == 1: # no
307 307 ret = False
308 308 elif r == 2: # Skip
309 309 ret = resp_file[0] = False
310 310 elif r == 3: # file (Record remaining)
311 311 ret = resp_file[0] = True
312 312 elif r == 4: # done, skip remaining
313 313 ret = resp_all[0] = False
314 314 elif r == 5: # all
315 315 ret = resp_all[0] = True
316 316 elif r == 6: # quit
317 317 raise util.Abort(_('user quit'))
318 318 return ret
319 319 pos, total = 0, len(chunks) - 1
320 320 while chunks:
321 321 pos = total - len(chunks) + 1
322 322 chunk = chunks.pop()
323 323 if isinstance(chunk, header):
324 324 # new-file mark
325 325 resp_file = [None]
326 326 fixoffset = 0
327 327 hdr = ''.join(chunk.header)
328 328 if hdr in seen:
329 329 consumefile()
330 330 continue
331 331 seen.add(hdr)
332 332 if resp_all[0] is None:
333 333 chunk.pretty(ui)
334 334 r = prompt(_('examine changes to %s?') %
335 335 _(' and ').join(map(repr, chunk.files())))
336 336 if r:
337 337 applied[chunk.filename()] = [chunk]
338 338 if chunk.allhunks():
339 339 applied[chunk.filename()] += consumefile()
340 340 else:
341 341 consumefile()
342 342 else:
343 343 # new hunk
344 344 if resp_file[0] is None and resp_all[0] is None:
345 345 chunk.pretty(ui)
346 346 r = total == 1 and prompt(_('record this change to %r?') %
347 347 chunk.filename()) \
348 348 or prompt(_('record change %d/%d to %r?') %
349 349 (pos, total, chunk.filename()))
350 350 if r:
351 351 if fixoffset:
352 352 chunk = copy.copy(chunk)
353 353 chunk.toline += fixoffset
354 354 applied[chunk.filename()].append(chunk)
355 355 else:
356 356 fixoffset += chunk.removed - chunk.added
357 357 return reduce(operator.add, [h for h in applied.itervalues()
358 358 if h[0].special() or len(h) > 1], [])
359 359
360 360 def record(ui, repo, *pats, **opts):
361 361 '''interactively select changes to commit
362 362
363 If a list of files is omitted, all changes reported by "hg status"
363 If a list of files is omitted, all changes reported by :hg:`status`
364 364 will be candidates for recording.
365 365
366 See 'hg help dates' for a list of formats valid for -d/--date.
366 See :hg:`help dates` for a list of formats valid for -d/--date.
367 367
368 368 You will be prompted for whether to record changes to each
369 369 modified file, and for files with multiple changes, for each
370 370 change to use. For each query, the following responses are
371 371 possible::
372 372
373 373 y - record this change
374 374 n - skip this change
375 375
376 376 s - skip remaining changes to this file
377 377 f - record remaining changes to this file
378 378
379 379 d - done, skip remaining changes and files
380 380 a - record all changes to all remaining files
381 381 q - quit, recording no changes
382 382
383 383 ? - display help'''
384 384
385 385 dorecord(ui, repo, commands.commit, *pats, **opts)
386 386
387 387
388 388 def qrecord(ui, repo, patch, *pats, **opts):
389 389 '''interactively record a new patch
390 390
391 See 'hg help qnew' & 'hg help record' for more information and
391 See :hg:`help qnew` & :hg:`help record` for more information and
392 392 usage.
393 393 '''
394 394
395 395 try:
396 396 mq = extensions.find('mq')
397 397 except KeyError:
398 398 raise util.Abort(_("'mq' extension not loaded"))
399 399
400 400 def committomq(ui, repo, *pats, **opts):
401 401 mq.new(ui, repo, patch, *pats, **opts)
402 402
403 403 opts = opts.copy()
404 404 opts['force'] = True # always 'qnew -f'
405 405 dorecord(ui, repo, committomq, *pats, **opts)
406 406
407 407
408 408 def dorecord(ui, repo, commitfunc, *pats, **opts):
409 409 if not ui.interactive():
410 410 raise util.Abort(_('running non-interactively, use commit instead'))
411 411
412 412 def recordfunc(ui, repo, message, match, opts):
413 413 """This is generic record driver.
414 414
415 415 Its job is to interactively filter local changes, and accordingly
416 416 prepare working dir into a state, where the job can be delegated to
417 417 non-interactive commit command such as 'commit' or 'qrefresh'.
418 418
419 419 After the actual job is done by non-interactive command, working dir
420 420 state is restored to original.
421 421
422 422 In the end we'll record intresting changes, and everything else will be
423 423 left in place, so the user can continue his work.
424 424 """
425 425
426 426 changes = repo.status(match=match)[:3]
427 427 diffopts = mdiff.diffopts(git=True, nodates=True)
428 428 chunks = patch.diff(repo, changes=changes, opts=diffopts)
429 429 fp = cStringIO.StringIO()
430 430 fp.write(''.join(chunks))
431 431 fp.seek(0)
432 432
433 433 # 1. filter patch, so we have intending-to apply subset of it
434 434 chunks = filterpatch(ui, parsepatch(fp))
435 435 del fp
436 436
437 437 contenders = set()
438 438 for h in chunks:
439 439 try:
440 440 contenders.update(set(h.files()))
441 441 except AttributeError:
442 442 pass
443 443
444 444 changed = changes[0] + changes[1] + changes[2]
445 445 newfiles = [f for f in changed if f in contenders]
446 446 if not newfiles:
447 447 ui.status(_('no changes to record\n'))
448 448 return 0
449 449
450 450 modified = set(changes[0])
451 451
452 452 # 2. backup changed files, so we can restore them in the end
453 453 backups = {}
454 454 backupdir = repo.join('record-backups')
455 455 try:
456 456 os.mkdir(backupdir)
457 457 except OSError, err:
458 458 if err.errno != errno.EEXIST:
459 459 raise
460 460 try:
461 461 # backup continues
462 462 for f in newfiles:
463 463 if f not in modified:
464 464 continue
465 465 fd, tmpname = tempfile.mkstemp(prefix=f.replace('/', '_')+'.',
466 466 dir=backupdir)
467 467 os.close(fd)
468 468 ui.debug('backup %r as %r\n' % (f, tmpname))
469 469 util.copyfile(repo.wjoin(f), tmpname)
470 470 backups[f] = tmpname
471 471
472 472 fp = cStringIO.StringIO()
473 473 for c in chunks:
474 474 if c.filename() in backups:
475 475 c.write(fp)
476 476 dopatch = fp.tell()
477 477 fp.seek(0)
478 478
479 479 # 3a. apply filtered patch to clean repo (clean)
480 480 if backups:
481 481 hg.revert(repo, repo.dirstate.parents()[0], backups.has_key)
482 482
483 483 # 3b. (apply)
484 484 if dopatch:
485 485 try:
486 486 ui.debug('applying patch\n')
487 487 ui.debug(fp.getvalue())
488 488 pfiles = {}
489 489 patch.internalpatch(fp, ui, 1, repo.root, files=pfiles,
490 490 eolmode=None)
491 491 patch.updatedir(ui, repo, pfiles)
492 492 except patch.PatchError, err:
493 493 s = str(err)
494 494 if s:
495 495 raise util.Abort(s)
496 496 else:
497 497 raise util.Abort(_('patch failed to apply'))
498 498 del fp
499 499
500 500 # 4. We prepared working directory according to filtered patch.
501 501 # Now is the time to delegate the job to commit/qrefresh or the like!
502 502
503 503 # it is important to first chdir to repo root -- we'll call a
504 504 # highlevel command with list of pathnames relative to repo root
505 505 cwd = os.getcwd()
506 506 os.chdir(repo.root)
507 507 try:
508 508 commitfunc(ui, repo, *newfiles, **opts)
509 509 finally:
510 510 os.chdir(cwd)
511 511
512 512 return 0
513 513 finally:
514 514 # 5. finally restore backed-up files
515 515 try:
516 516 for realname, tmpname in backups.iteritems():
517 517 ui.debug('restoring %r to %r\n' % (tmpname, realname))
518 518 util.copyfile(tmpname, repo.wjoin(realname))
519 519 os.unlink(tmpname)
520 520 os.rmdir(backupdir)
521 521 except OSError:
522 522 pass
523 523
524 524 # wrap ui.write so diff output can be labeled/colorized
525 525 def wrapwrite(orig, *args, **kw):
526 526 label = kw.pop('label', '')
527 527 for chunk, l in patch.difflabel(lambda: args):
528 528 orig(chunk, label=label + l)
529 529 oldwrite = ui.write
530 530 extensions.wrapfunction(ui, 'write', wrapwrite)
531 531 try:
532 532 return cmdutil.commit(ui, repo, recordfunc, pats, opts)
533 533 finally:
534 534 ui.write = oldwrite
535 535
536 536 cmdtable = {
537 537 "record":
538 538 (record,
539 539
540 540 # add commit options
541 541 commands.table['^commit|ci'][1],
542 542
543 543 _('hg record [OPTION]... [FILE]...')),
544 544 }
545 545
546 546
547 547 def uisetup(ui):
548 548 try:
549 549 mq = extensions.find('mq')
550 550 except KeyError:
551 551 return
552 552
553 553 qcmdtable = {
554 554 "qrecord":
555 555 (qrecord,
556 556
557 557 # add qnew options, except '--force'
558 558 [opt for opt in mq.cmdtable['^qnew'][1] if opt[1] != 'force'],
559 559
560 560 _('hg qrecord [OPTION]... PATCH [FILE]...')),
561 561 }
562 562
563 563 cmdtable.update(qcmdtable)
564 564
@@ -1,3923 +1,3923
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, nullid, nullrev, short
9 9 from lock import release
10 10 from i18n import _, gettext
11 11 import os, re, sys, difflib, time, tempfile
12 12 import hg, util, revlog, bundlerepo, extensions, copies, error
13 13 import patch, help, mdiff, url, encoding, templatekw
14 14 import archival, changegroup, cmdutil, sshserver, hbisect
15 15 from hgweb import server, hgweb_mod, hgwebdir_mod
16 16 import merge as mergemod
17 17 import minirst
18 18
19 19 # Commands start here, listed alphabetically
20 20
21 21 def add(ui, repo, *pats, **opts):
22 22 """add the specified files on the next commit
23 23
24 24 Schedule files to be version controlled and added to the
25 25 repository.
26 26
27 27 The files will be added to the repository at the next commit. To
28 28 undo an add before that, see hg forget.
29 29
30 30 If no names are given, add all files to the repository.
31 31
32 32 .. container:: verbose
33 33
34 34 An example showing how new (unknown) files are added
35 automatically by ``hg add``::
35 automatically by :hg:`add`::
36 36
37 37 $ ls
38 38 foo.c
39 39 $ hg status
40 40 ? foo.c
41 41 $ hg add
42 42 adding foo.c
43 43 $ hg status
44 44 A foo.c
45 45 """
46 46
47 47 bad = []
48 48 names = []
49 49 m = cmdutil.match(repo, pats, opts)
50 50 oldbad = m.bad
51 51 m.bad = lambda x, y: bad.append(x) or oldbad(x, y)
52 52
53 53 for f in repo.walk(m):
54 54 exact = m.exact(f)
55 55 if exact or f not in repo.dirstate:
56 56 names.append(f)
57 57 if ui.verbose or not exact:
58 58 ui.status(_('adding %s\n') % m.rel(f))
59 59 if not opts.get('dry_run'):
60 60 bad += [f for f in repo.add(names) if f in m.files()]
61 61 return bad and 1 or 0
62 62
63 63 def addremove(ui, repo, *pats, **opts):
64 64 """add all new files, delete all missing files
65 65
66 66 Add all new files and remove all missing files from the
67 67 repository.
68 68
69 69 New files are ignored if they match any of the patterns in
70 70 .hgignore. As with add, these changes take effect at the next
71 71 commit.
72 72
73 73 Use the -s/--similarity option to detect renamed files. With a
74 74 parameter greater than 0, this compares every removed file with
75 75 every added file and records those similar enough as renames. This
76 76 option takes a percentage between 0 (disabled) and 100 (files must
77 77 be identical) as its parameter. Detecting renamed files this way
78 78 can be expensive.
79 79 """
80 80 try:
81 81 sim = float(opts.get('similarity') or 0)
82 82 except ValueError:
83 83 raise util.Abort(_('similarity must be a number'))
84 84 if sim < 0 or sim > 100:
85 85 raise util.Abort(_('similarity must be between 0 and 100'))
86 86 return cmdutil.addremove(repo, pats, opts, similarity=sim / 100.0)
87 87
88 88 def annotate(ui, repo, *pats, **opts):
89 89 """show changeset information by line for each file
90 90
91 91 List changes in files, showing the revision id responsible for
92 92 each line
93 93
94 94 This command is useful for discovering when a change was made and
95 95 by whom.
96 96
97 97 Without the -a/--text option, annotate will avoid processing files
98 98 it detects as binary. With -a, annotate will annotate the file
99 99 anyway, although the results will probably be neither useful
100 100 nor desirable.
101 101 """
102 102 if opts.get('follow'):
103 103 # --follow is deprecated and now just an alias for -f/--file
104 104 # to mimic the behavior of Mercurial before version 1.5
105 105 opts['file'] = 1
106 106
107 107 datefunc = ui.quiet and util.shortdate or util.datestr
108 108 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
109 109
110 110 if not pats:
111 111 raise util.Abort(_('at least one filename or pattern is required'))
112 112
113 113 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
114 114 ('number', lambda x: str(x[0].rev())),
115 115 ('changeset', lambda x: short(x[0].node())),
116 116 ('date', getdate),
117 117 ('file', lambda x: x[0].path()),
118 118 ]
119 119
120 120 if (not opts.get('user') and not opts.get('changeset')
121 121 and not opts.get('date') and not opts.get('file')):
122 122 opts['number'] = 1
123 123
124 124 linenumber = opts.get('line_number') is not None
125 125 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
126 126 raise util.Abort(_('at least one of -n/-c is required for -l'))
127 127
128 128 funcmap = [func for op, func in opmap if opts.get(op)]
129 129 if linenumber:
130 130 lastfunc = funcmap[-1]
131 131 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
132 132
133 133 ctx = repo[opts.get('rev')]
134 134 m = cmdutil.match(repo, pats, opts)
135 135 follow = not opts.get('no_follow')
136 136 for abs in ctx.walk(m):
137 137 fctx = ctx[abs]
138 138 if not opts.get('text') and util.binary(fctx.data()):
139 139 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
140 140 continue
141 141
142 142 lines = fctx.annotate(follow=follow, linenumber=linenumber)
143 143 pieces = []
144 144
145 145 for f in funcmap:
146 146 l = [f(n) for n, dummy in lines]
147 147 if l:
148 148 ml = max(map(len, l))
149 149 pieces.append(["%*s" % (ml, x) for x in l])
150 150
151 151 if pieces:
152 152 for p, l in zip(zip(*pieces), lines):
153 153 ui.write("%s: %s" % (" ".join(p), l[1]))
154 154
155 155 def archive(ui, repo, dest, **opts):
156 156 '''create an unversioned archive of a repository revision
157 157
158 158 By default, the revision used is the parent of the working
159 159 directory; use -r/--rev to specify a different revision.
160 160
161 161 The archive type is automatically detected based on file
162 162 extension (or override using -t/--type).
163 163
164 164 Valid types are:
165 165
166 166 :``files``: a directory full of files (default)
167 167 :``tar``: tar archive, uncompressed
168 168 :``tbz2``: tar archive, compressed using bzip2
169 169 :``tgz``: tar archive, compressed using gzip
170 170 :``uzip``: zip archive, uncompressed
171 171 :``zip``: zip archive, compressed using deflate
172 172
173 173 The exact name of the destination archive or directory is given
174 using a format string; see 'hg help export' for details.
174 using a format string; see :hg:`help export` for details.
175 175
176 176 Each member added to an archive file has a directory prefix
177 177 prepended. Use -p/--prefix to specify a format string for the
178 178 prefix. The default is the basename of the archive, with suffixes
179 179 removed.
180 180 '''
181 181
182 182 ctx = repo[opts.get('rev')]
183 183 if not ctx:
184 184 raise util.Abort(_('no working directory: please specify a revision'))
185 185 node = ctx.node()
186 186 dest = cmdutil.make_filename(repo, dest, node)
187 187 if os.path.realpath(dest) == repo.root:
188 188 raise util.Abort(_('repository root cannot be destination'))
189 189
190 190 def guess_type():
191 191 exttypes = {
192 192 'tar': ['.tar'],
193 193 'tbz2': ['.tbz2', '.tar.bz2'],
194 194 'tgz': ['.tgz', '.tar.gz'],
195 195 'zip': ['.zip'],
196 196 }
197 197
198 198 for type, extensions in exttypes.items():
199 199 if util.any(dest.endswith(ext) for ext in extensions):
200 200 return type
201 201 return None
202 202
203 203 kind = opts.get('type') or guess_type() or 'files'
204 204 prefix = opts.get('prefix')
205 205
206 206 if dest == '-':
207 207 if kind == 'files':
208 208 raise util.Abort(_('cannot archive plain files to stdout'))
209 209 dest = sys.stdout
210 210 if not prefix:
211 211 prefix = os.path.basename(repo.root) + '-%h'
212 212
213 213 prefix = cmdutil.make_filename(repo, prefix, node)
214 214 matchfn = cmdutil.match(repo, [], opts)
215 215 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
216 216 matchfn, prefix)
217 217
218 218 def backout(ui, repo, node=None, rev=None, **opts):
219 219 '''reverse effect of earlier changeset
220 220
221 221 Commit the backed out changes as a new changeset. The new
222 222 changeset is a child of the backed out changeset.
223 223
224 224 If you backout a changeset other than the tip, a new head is
225 225 created. This head will be the new tip and you should merge this
226 226 backout changeset with another head.
227 227
228 228 The --merge option remembers the parent of the working directory
229 229 before starting the backout, then merges the new head with that
230 230 changeset afterwards. This saves you from doing the merge by hand.
231 231 The result of this merge is not committed, as with a normal merge.
232 232
233 See 'hg help dates' for a list of formats valid for -d/--date.
233 See :hg:`help dates` for a list of formats valid for -d/--date.
234 234 '''
235 235 if rev and node:
236 236 raise util.Abort(_("please specify just one revision"))
237 237
238 238 if not rev:
239 239 rev = node
240 240
241 241 if not rev:
242 242 raise util.Abort(_("please specify a revision to backout"))
243 243
244 244 date = opts.get('date')
245 245 if date:
246 246 opts['date'] = util.parsedate(date)
247 247
248 248 cmdutil.bail_if_changed(repo)
249 249 node = repo.lookup(rev)
250 250
251 251 op1, op2 = repo.dirstate.parents()
252 252 a = repo.changelog.ancestor(op1, node)
253 253 if a != node:
254 254 raise util.Abort(_('cannot backout change on a different branch'))
255 255
256 256 p1, p2 = repo.changelog.parents(node)
257 257 if p1 == nullid:
258 258 raise util.Abort(_('cannot backout a change with no parents'))
259 259 if p2 != nullid:
260 260 if not opts.get('parent'):
261 261 raise util.Abort(_('cannot backout a merge changeset without '
262 262 '--parent'))
263 263 p = repo.lookup(opts['parent'])
264 264 if p not in (p1, p2):
265 265 raise util.Abort(_('%s is not a parent of %s') %
266 266 (short(p), short(node)))
267 267 parent = p
268 268 else:
269 269 if opts.get('parent'):
270 270 raise util.Abort(_('cannot use --parent on non-merge changeset'))
271 271 parent = p1
272 272
273 273 # the backout should appear on the same branch
274 274 branch = repo.dirstate.branch()
275 275 hg.clean(repo, node, show_stats=False)
276 276 repo.dirstate.setbranch(branch)
277 277 revert_opts = opts.copy()
278 278 revert_opts['date'] = None
279 279 revert_opts['all'] = True
280 280 revert_opts['rev'] = hex(parent)
281 281 revert_opts['no_backup'] = None
282 282 revert(ui, repo, **revert_opts)
283 283 commit_opts = opts.copy()
284 284 commit_opts['addremove'] = False
285 285 if not commit_opts['message'] and not commit_opts['logfile']:
286 286 # we don't translate commit messages
287 287 commit_opts['message'] = "Backed out changeset %s" % short(node)
288 288 commit_opts['force_editor'] = True
289 289 commit(ui, repo, **commit_opts)
290 290 def nice(node):
291 291 return '%d:%s' % (repo.changelog.rev(node), short(node))
292 292 ui.status(_('changeset %s backs out changeset %s\n') %
293 293 (nice(repo.changelog.tip()), nice(node)))
294 294 if op1 != node:
295 295 hg.clean(repo, op1, show_stats=False)
296 296 if opts.get('merge'):
297 297 ui.status(_('merging with changeset %s\n')
298 298 % nice(repo.changelog.tip()))
299 299 hg.merge(repo, hex(repo.changelog.tip()))
300 300 else:
301 301 ui.status(_('the backout changeset is a new head - '
302 302 'do not forget to merge\n'))
303 303 ui.status(_('(use "backout --merge" '
304 304 'if you want to auto-merge)\n'))
305 305
306 306 def bisect(ui, repo, rev=None, extra=None, command=None,
307 307 reset=None, good=None, bad=None, skip=None, noupdate=None):
308 308 """subdivision search of changesets
309 309
310 310 This command helps to find changesets which introduce problems. To
311 311 use, mark the earliest changeset you know exhibits the problem as
312 312 bad, then mark the latest changeset which is free from the problem
313 313 as good. Bisect will update your working directory to a revision
314 314 for testing (unless the -U/--noupdate option is specified). Once
315 315 you have performed tests, mark the working directory as good or
316 316 bad, and bisect will either update to another candidate changeset
317 317 or announce that it has found the bad revision.
318 318
319 319 As a shortcut, you can also use the revision argument to mark a
320 320 revision as good or bad without checking it out first.
321 321
322 322 If you supply a command, it will be used for automatic bisection.
323 323 Its exit status will be used to mark revisions as good or bad:
324 324 status 0 means good, 125 means to skip the revision, 127
325 325 (command not found) will abort the bisection, and any other
326 326 non-zero exit status means the revision is bad.
327 327 """
328 328 def print_result(nodes, good):
329 329 displayer = cmdutil.show_changeset(ui, repo, {})
330 330 if len(nodes) == 1:
331 331 # narrowed it down to a single revision
332 332 if good:
333 333 ui.write(_("The first good revision is:\n"))
334 334 else:
335 335 ui.write(_("The first bad revision is:\n"))
336 336 displayer.show(repo[nodes[0]])
337 337 else:
338 338 # multiple possible revisions
339 339 if good:
340 340 ui.write(_("Due to skipped revisions, the first "
341 341 "good revision could be any of:\n"))
342 342 else:
343 343 ui.write(_("Due to skipped revisions, the first "
344 344 "bad revision could be any of:\n"))
345 345 for n in nodes:
346 346 displayer.show(repo[n])
347 347 displayer.close()
348 348
349 349 def check_state(state, interactive=True):
350 350 if not state['good'] or not state['bad']:
351 351 if (good or bad or skip or reset) and interactive:
352 352 return
353 353 if not state['good']:
354 354 raise util.Abort(_('cannot bisect (no known good revisions)'))
355 355 else:
356 356 raise util.Abort(_('cannot bisect (no known bad revisions)'))
357 357 return True
358 358
359 359 # backward compatibility
360 360 if rev in "good bad reset init".split():
361 361 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
362 362 cmd, rev, extra = rev, extra, None
363 363 if cmd == "good":
364 364 good = True
365 365 elif cmd == "bad":
366 366 bad = True
367 367 else:
368 368 reset = True
369 369 elif extra or good + bad + skip + reset + bool(command) > 1:
370 370 raise util.Abort(_('incompatible arguments'))
371 371
372 372 if reset:
373 373 p = repo.join("bisect.state")
374 374 if os.path.exists(p):
375 375 os.unlink(p)
376 376 return
377 377
378 378 state = hbisect.load_state(repo)
379 379
380 380 if command:
381 381 changesets = 1
382 382 try:
383 383 while changesets:
384 384 # update state
385 385 status = util.system(command)
386 386 if status == 125:
387 387 transition = "skip"
388 388 elif status == 0:
389 389 transition = "good"
390 390 # status < 0 means process was killed
391 391 elif status == 127:
392 392 raise util.Abort(_("failed to execute %s") % command)
393 393 elif status < 0:
394 394 raise util.Abort(_("%s killed") % command)
395 395 else:
396 396 transition = "bad"
397 397 ctx = repo[rev or '.']
398 398 state[transition].append(ctx.node())
399 399 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
400 400 check_state(state, interactive=False)
401 401 # bisect
402 402 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
403 403 # update to next check
404 404 cmdutil.bail_if_changed(repo)
405 405 hg.clean(repo, nodes[0], show_stats=False)
406 406 finally:
407 407 hbisect.save_state(repo, state)
408 408 return print_result(nodes, good)
409 409
410 410 # update state
411 411 node = repo.lookup(rev or '.')
412 412 if good or bad or skip:
413 413 if good:
414 414 state['good'].append(node)
415 415 elif bad:
416 416 state['bad'].append(node)
417 417 elif skip:
418 418 state['skip'].append(node)
419 419 hbisect.save_state(repo, state)
420 420
421 421 if not check_state(state):
422 422 return
423 423
424 424 # actually bisect
425 425 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
426 426 if changesets == 0:
427 427 print_result(nodes, good)
428 428 else:
429 429 assert len(nodes) == 1 # only a single node can be tested next
430 430 node = nodes[0]
431 431 # compute the approximate number of remaining tests
432 432 tests, size = 0, 2
433 433 while size <= changesets:
434 434 tests, size = tests + 1, size * 2
435 435 rev = repo.changelog.rev(node)
436 436 ui.write(_("Testing changeset %d:%s "
437 437 "(%d changesets remaining, ~%d tests)\n")
438 438 % (rev, short(node), changesets, tests))
439 439 if not noupdate:
440 440 cmdutil.bail_if_changed(repo)
441 441 return hg.clean(repo, node)
442 442
443 443 def branch(ui, repo, label=None, **opts):
444 444 """set or show the current branch name
445 445
446 446 With no argument, show the current branch name. With one argument,
447 447 set the working directory branch name (the branch will not exist
448 448 in the repository until the next commit). Standard practice
449 449 recommends that primary development take place on the 'default'
450 450 branch.
451 451
452 452 Unless -f/--force is specified, branch will not let you set a
453 453 branch name that already exists, even if it's inactive.
454 454
455 455 Use -C/--clean to reset the working directory branch to that of
456 456 the parent of the working directory, negating a previous branch
457 457 change.
458 458
459 Use the command 'hg update' to switch to an existing branch. Use
460 'hg commit --close-branch' to mark this branch as closed.
459 Use the command :hg:`update` to switch to an existing branch. Use
460 :hg:`commit --close-branch` to mark this branch as closed.
461 461 """
462 462
463 463 if opts.get('clean'):
464 464 label = repo[None].parents()[0].branch()
465 465 repo.dirstate.setbranch(label)
466 466 ui.status(_('reset working directory to branch %s\n') % label)
467 467 elif label:
468 468 utflabel = encoding.fromlocal(label)
469 469 if not opts.get('force') and utflabel in repo.branchtags():
470 470 if label not in [p.branch() for p in repo.parents()]:
471 471 raise util.Abort(_('a branch of the same name already exists'
472 472 " (use 'hg update' to switch to it)"))
473 473 repo.dirstate.setbranch(utflabel)
474 474 ui.status(_('marked working directory as branch %s\n') % label)
475 475 else:
476 476 ui.write("%s\n" % encoding.tolocal(repo.dirstate.branch()))
477 477
478 478 def branches(ui, repo, active=False, closed=False):
479 479 """list repository named branches
480 480
481 481 List the repository's named branches, indicating which ones are
482 482 inactive. If -c/--closed is specified, also list branches which have
483 483 been marked closed (see hg commit --close-branch).
484 484
485 485 If -a/--active is specified, only show active branches. A branch
486 486 is considered active if it contains repository heads.
487 487
488 Use the command 'hg update' to switch to an existing branch.
488 Use the command :hg:`update` to switch to an existing branch.
489 489 """
490 490
491 491 hexfunc = ui.debugflag and hex or short
492 492 activebranches = [repo[n].branch() for n in repo.heads()]
493 493 def testactive(tag, node):
494 494 realhead = tag in activebranches
495 495 open = node in repo.branchheads(tag, closed=False)
496 496 return realhead and open
497 497 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
498 498 for tag, node in repo.branchtags().items()],
499 499 reverse=True)
500 500
501 501 for isactive, node, tag in branches:
502 502 if (not active) or isactive:
503 503 encodedtag = encoding.tolocal(tag)
504 504 if ui.quiet:
505 505 ui.write("%s\n" % encodedtag)
506 506 else:
507 507 hn = repo.lookup(node)
508 508 if isactive:
509 509 notice = ''
510 510 elif hn not in repo.branchheads(tag, closed=False):
511 511 if not closed:
512 512 continue
513 513 notice = _(' (closed)')
514 514 else:
515 515 notice = _(' (inactive)')
516 516 rev = str(node).rjust(31 - encoding.colwidth(encodedtag))
517 517 data = encodedtag, rev, hexfunc(hn), notice
518 518 ui.write("%s %s:%s%s\n" % data)
519 519
520 520 def bundle(ui, repo, fname, dest=None, **opts):
521 521 """create a changegroup file
522 522
523 523 Generate a compressed changegroup file collecting changesets not
524 524 known to be in another repository.
525 525
526 526 If you omit the destination repository, then hg assumes the
527 527 destination will have all the nodes you specify with --base
528 528 parameters. To create a bundle containing all changesets, use
529 529 -a/--all (or --base null).
530 530
531 531 You can change compression method with the -t/--type option.
532 532 The available compression methods are: none, bzip2, and
533 533 gzip (by default, bundles are compressed using bzip2).
534 534
535 535 The bundle file can then be transferred using conventional means
536 536 and applied to another repository with the unbundle or pull
537 537 command. This is useful when direct push and pull are not
538 538 available or when exporting an entire repository is undesirable.
539 539
540 540 Applying bundles preserves all changeset contents including
541 541 permissions, copy/rename information, and revision history.
542 542 """
543 543 revs = opts.get('rev') or None
544 544 if revs:
545 545 revs = [repo.lookup(rev) for rev in revs]
546 546 if opts.get('all'):
547 547 base = ['null']
548 548 else:
549 549 base = opts.get('base')
550 550 if base:
551 551 if dest:
552 552 raise util.Abort(_("--base is incompatible with specifying "
553 553 "a destination"))
554 554 base = [repo.lookup(rev) for rev in base]
555 555 # create the right base
556 556 # XXX: nodesbetween / changegroup* should be "fixed" instead
557 557 o = []
558 558 has = set((nullid,))
559 559 for n in base:
560 560 has.update(repo.changelog.reachable(n))
561 561 if revs:
562 562 visit = list(revs)
563 563 has.difference_update(revs)
564 564 else:
565 565 visit = repo.changelog.heads()
566 566 seen = {}
567 567 while visit:
568 568 n = visit.pop(0)
569 569 parents = [p for p in repo.changelog.parents(n) if p not in has]
570 570 if len(parents) == 0:
571 571 if n not in has:
572 572 o.append(n)
573 573 else:
574 574 for p in parents:
575 575 if p not in seen:
576 576 seen[p] = 1
577 577 visit.append(p)
578 578 else:
579 579 dest = ui.expandpath(dest or 'default-push', dest or 'default')
580 580 dest, branches = hg.parseurl(dest, opts.get('branch'))
581 581 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
582 582 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
583 583 o = repo.findoutgoing(other, force=opts.get('force'))
584 584
585 585 if not o:
586 586 ui.status(_("no changes found\n"))
587 587 return
588 588
589 589 if revs:
590 590 cg = repo.changegroupsubset(o, revs, 'bundle')
591 591 else:
592 592 cg = repo.changegroup(o, 'bundle')
593 593
594 594 bundletype = opts.get('type', 'bzip2').lower()
595 595 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
596 596 bundletype = btypes.get(bundletype)
597 597 if bundletype not in changegroup.bundletypes:
598 598 raise util.Abort(_('unknown bundle type specified with --type'))
599 599
600 600 changegroup.writebundle(cg, fname, bundletype)
601 601
602 602 def cat(ui, repo, file1, *pats, **opts):
603 603 """output the current or given revision of files
604 604
605 605 Print the specified files as they were at the given revision. If
606 606 no revision is given, the parent of the working directory is used,
607 607 or tip if no revision is checked out.
608 608
609 609 Output may be to a file, in which case the name of the file is
610 610 given using a format string. The formatting rules are the same as
611 611 for the export command, with the following additions:
612 612
613 613 :``%s``: basename of file being printed
614 614 :``%d``: dirname of file being printed, or '.' if in repository root
615 615 :``%p``: root-relative path name of file being printed
616 616 """
617 617 ctx = repo[opts.get('rev')]
618 618 err = 1
619 619 m = cmdutil.match(repo, (file1,) + pats, opts)
620 620 for abs in ctx.walk(m):
621 621 fp = cmdutil.make_file(repo, opts.get('output'), ctx.node(), pathname=abs)
622 622 data = ctx[abs].data()
623 623 if opts.get('decode'):
624 624 data = repo.wwritedata(abs, data)
625 625 fp.write(data)
626 626 err = 0
627 627 return err
628 628
629 629 def clone(ui, source, dest=None, **opts):
630 630 """make a copy of an existing repository
631 631
632 632 Create a copy of an existing repository in a new directory.
633 633
634 634 If no destination directory name is specified, it defaults to the
635 635 basename of the source.
636 636
637 637 The location of the source is added to the new repository's
638 638 .hg/hgrc file, as the default to be used for future pulls.
639 639
640 See 'hg help urls' for valid source format details.
640 See :hg:`help urls` for valid source format details.
641 641
642 642 It is possible to specify an ``ssh://`` URL as the destination, but no
643 643 .hg/hgrc and working directory will be created on the remote side.
644 Please see 'hg help urls' for important details about ``ssh://`` URLs.
644 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
645 645
646 646 A set of changesets (tags, or branch names) to pull may be specified
647 647 by listing each changeset (tag, or branch name) with -r/--rev.
648 648 If -r/--rev is used, the cloned repository will contain only a subset
649 649 of the changesets of the source repository. Only the set of changesets
650 650 defined by all -r/--rev options (including all their ancestors)
651 651 will be pulled into the destination repository.
652 652 No subsequent changesets (including subsequent tags) will be present
653 653 in the destination.
654 654
655 655 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
656 656 local source repositories.
657 657
658 658 For efficiency, hardlinks are used for cloning whenever the source
659 659 and destination are on the same filesystem (note this applies only
660 660 to the repository data, not to the working directory). Some
661 661 filesystems, such as AFS, implement hardlinking incorrectly, but
662 662 do not report errors. In these cases, use the --pull option to
663 663 avoid hardlinking.
664 664
665 665 In some cases, you can clone repositories and the working directory
666 666 using full hardlinks with ::
667 667
668 668 $ cp -al REPO REPOCLONE
669 669
670 670 This is the fastest way to clone, but it is not always safe. The
671 671 operation is not atomic (making sure REPO is not modified during
672 672 the operation is up to you) and you have to make sure your editor
673 673 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
674 674 this is not compatible with certain extensions that place their
675 675 metadata under the .hg directory, such as mq.
676 676
677 677 Mercurial will update the working directory to the first applicable
678 678 revision from this list:
679 679
680 680 a) null if -U or the source repository has no changesets
681 681 b) if -u . and the source repository is local, the first parent of
682 682 the source repository's working directory
683 683 c) the changeset specified with -u (if a branch name, this means the
684 684 latest head of that branch)
685 685 d) the changeset specified with -r
686 686 e) the tipmost head specified with -b
687 687 f) the tipmost head specified with the url#branch source syntax
688 688 g) the tipmost head of the default branch
689 689 h) tip
690 690 """
691 691 if opts.get('noupdate') and opts.get('updaterev'):
692 692 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
693 693
694 694 hg.clone(cmdutil.remoteui(ui, opts), source, dest,
695 695 pull=opts.get('pull'),
696 696 stream=opts.get('uncompressed'),
697 697 rev=opts.get('rev'),
698 698 update=opts.get('updaterev') or not opts.get('noupdate'),
699 699 branch=opts.get('branch'))
700 700
701 701 def commit(ui, repo, *pats, **opts):
702 702 """commit the specified files or all outstanding changes
703 703
704 704 Commit changes to the given files into the repository. Unlike a
705 705 centralized RCS, this operation is a local operation. See hg push
706 706 for a way to actively distribute your changes.
707 707
708 If a list of files is omitted, all changes reported by "hg status"
708 If a list of files is omitted, all changes reported by :hg:`status`
709 709 will be committed.
710 710
711 711 If you are committing the result of a merge, do not provide any
712 712 filenames or -I/-X filters.
713 713
714 714 If no commit message is specified, the configured editor is
715 715 started to prompt you for a message.
716 716
717 See 'hg help dates' for a list of formats valid for -d/--date.
717 See :hg:`help dates` for a list of formats valid for -d/--date.
718 718 """
719 719 extra = {}
720 720 if opts.get('close_branch'):
721 721 extra['close'] = 1
722 722 e = cmdutil.commiteditor
723 723 if opts.get('force_editor'):
724 724 e = cmdutil.commitforceeditor
725 725
726 726 def commitfunc(ui, repo, message, match, opts):
727 727 return repo.commit(message, opts.get('user'), opts.get('date'), match,
728 728 editor=e, extra=extra)
729 729
730 730 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
731 731 if not node:
732 732 ui.status(_("nothing changed\n"))
733 733 return
734 734 cl = repo.changelog
735 735 rev = cl.rev(node)
736 736 parents = cl.parentrevs(rev)
737 737 if rev - 1 in parents:
738 738 # one of the parents was the old tip
739 739 pass
740 740 elif (parents == (nullrev, nullrev) or
741 741 len(cl.heads(cl.node(parents[0]))) > 1 and
742 742 (parents[1] == nullrev or len(cl.heads(cl.node(parents[1]))) > 1)):
743 743 ui.status(_('created new head\n'))
744 744
745 745 if ui.debugflag:
746 746 ui.write(_('committed changeset %d:%s\n') % (rev, hex(node)))
747 747 elif ui.verbose:
748 748 ui.write(_('committed changeset %d:%s\n') % (rev, short(node)))
749 749
750 750 def copy(ui, repo, *pats, **opts):
751 751 """mark files as copied for the next commit
752 752
753 753 Mark dest as having copies of source files. If dest is a
754 754 directory, copies are put in that directory. If dest is a file,
755 755 the source must be a single file.
756 756
757 757 By default, this command copies the contents of files as they
758 758 exist in the working directory. If invoked with -A/--after, the
759 759 operation is recorded, but no copying is performed.
760 760
761 761 This command takes effect with the next commit. To undo a copy
762 762 before that, see hg revert.
763 763 """
764 764 wlock = repo.wlock(False)
765 765 try:
766 766 return cmdutil.copy(ui, repo, pats, opts)
767 767 finally:
768 768 wlock.release()
769 769
770 770 def debugancestor(ui, repo, *args):
771 771 """find the ancestor revision of two revisions in a given index"""
772 772 if len(args) == 3:
773 773 index, rev1, rev2 = args
774 774 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
775 775 lookup = r.lookup
776 776 elif len(args) == 2:
777 777 if not repo:
778 778 raise util.Abort(_("There is no Mercurial repository here "
779 779 "(.hg not found)"))
780 780 rev1, rev2 = args
781 781 r = repo.changelog
782 782 lookup = repo.lookup
783 783 else:
784 784 raise util.Abort(_('either two or three arguments required'))
785 785 a = r.ancestor(lookup(rev1), lookup(rev2))
786 786 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
787 787
788 788 def debugcommands(ui, cmd='', *args):
789 789 for cmd, vals in sorted(table.iteritems()):
790 790 cmd = cmd.split('|')[0].strip('^')
791 791 opts = ', '.join([i[1] for i in vals[1]])
792 792 ui.write('%s: %s\n' % (cmd, opts))
793 793
794 794 def debugcomplete(ui, cmd='', **opts):
795 795 """returns the completion list associated with the given command"""
796 796
797 797 if opts.get('options'):
798 798 options = []
799 799 otables = [globalopts]
800 800 if cmd:
801 801 aliases, entry = cmdutil.findcmd(cmd, table, False)
802 802 otables.append(entry[1])
803 803 for t in otables:
804 804 for o in t:
805 805 if "(DEPRECATED)" in o[3]:
806 806 continue
807 807 if o[0]:
808 808 options.append('-%s' % o[0])
809 809 options.append('--%s' % o[1])
810 810 ui.write("%s\n" % "\n".join(options))
811 811 return
812 812
813 813 cmdlist = cmdutil.findpossible(cmd, table)
814 814 if ui.verbose:
815 815 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
816 816 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
817 817
818 818 def debugfsinfo(ui, path = "."):
819 819 open('.debugfsinfo', 'w').write('')
820 820 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
821 821 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
822 822 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
823 823 and 'yes' or 'no'))
824 824 os.unlink('.debugfsinfo')
825 825
826 826 def debugrebuildstate(ui, repo, rev="tip"):
827 827 """rebuild the dirstate as it would look like for the given revision"""
828 828 ctx = repo[rev]
829 829 wlock = repo.wlock()
830 830 try:
831 831 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
832 832 finally:
833 833 wlock.release()
834 834
835 835 def debugcheckstate(ui, repo):
836 836 """validate the correctness of the current dirstate"""
837 837 parent1, parent2 = repo.dirstate.parents()
838 838 m1 = repo[parent1].manifest()
839 839 m2 = repo[parent2].manifest()
840 840 errors = 0
841 841 for f in repo.dirstate:
842 842 state = repo.dirstate[f]
843 843 if state in "nr" and f not in m1:
844 844 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
845 845 errors += 1
846 846 if state in "a" and f in m1:
847 847 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
848 848 errors += 1
849 849 if state in "m" and f not in m1 and f not in m2:
850 850 ui.warn(_("%s in state %s, but not in either manifest\n") %
851 851 (f, state))
852 852 errors += 1
853 853 for f in m1:
854 854 state = repo.dirstate[f]
855 855 if state not in "nrm":
856 856 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
857 857 errors += 1
858 858 if errors:
859 859 error = _(".hg/dirstate inconsistent with current parent's manifest")
860 860 raise util.Abort(error)
861 861
862 862 def showconfig(ui, repo, *values, **opts):
863 863 """show combined config settings from all hgrc files
864 864
865 865 With no arguments, print names and values of all config items.
866 866
867 867 With one argument of the form section.name, print just the value
868 868 of that config item.
869 869
870 870 With multiple arguments, print names and values of all config
871 871 items with matching section names.
872 872
873 873 With --debug, the source (filename and line number) is printed
874 874 for each config item.
875 875 """
876 876
877 877 untrusted = bool(opts.get('untrusted'))
878 878 if values:
879 879 if len([v for v in values if '.' in v]) > 1:
880 880 raise util.Abort(_('only one config item permitted'))
881 881 for section, name, value in ui.walkconfig(untrusted=untrusted):
882 882 sectname = section + '.' + name
883 883 if values:
884 884 for v in values:
885 885 if v == section:
886 886 ui.debug('%s: ' %
887 887 ui.configsource(section, name, untrusted))
888 888 ui.write('%s=%s\n' % (sectname, value))
889 889 elif v == sectname:
890 890 ui.debug('%s: ' %
891 891 ui.configsource(section, name, untrusted))
892 892 ui.write(value, '\n')
893 893 else:
894 894 ui.debug('%s: ' %
895 895 ui.configsource(section, name, untrusted))
896 896 ui.write('%s=%s\n' % (sectname, value))
897 897
898 898 def debugsetparents(ui, repo, rev1, rev2=None):
899 899 """manually set the parents of the current working directory
900 900
901 901 This is useful for writing repository conversion tools, but should
902 902 be used with care.
903 903 """
904 904
905 905 if not rev2:
906 906 rev2 = hex(nullid)
907 907
908 908 wlock = repo.wlock()
909 909 try:
910 910 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
911 911 finally:
912 912 wlock.release()
913 913
914 914 def debugstate(ui, repo, nodates=None):
915 915 """show the contents of the current dirstate"""
916 916 timestr = ""
917 917 showdate = not nodates
918 918 for file_, ent in sorted(repo.dirstate._map.iteritems()):
919 919 if showdate:
920 920 if ent[3] == -1:
921 921 # Pad or slice to locale representation
922 922 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
923 923 time.localtime(0)))
924 924 timestr = 'unset'
925 925 timestr = (timestr[:locale_len] +
926 926 ' ' * (locale_len - len(timestr)))
927 927 else:
928 928 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
929 929 time.localtime(ent[3]))
930 930 if ent[1] & 020000:
931 931 mode = 'lnk'
932 932 else:
933 933 mode = '%3o' % (ent[1] & 0777)
934 934 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
935 935 for f in repo.dirstate.copies():
936 936 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
937 937
938 938 def debugsub(ui, repo, rev=None):
939 939 if rev == '':
940 940 rev = None
941 941 for k, v in sorted(repo[rev].substate.items()):
942 942 ui.write('path %s\n' % k)
943 943 ui.write(' source %s\n' % v[0])
944 944 ui.write(' revision %s\n' % v[1])
945 945
946 946 def debugdata(ui, file_, rev):
947 947 """dump the contents of a data file revision"""
948 948 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
949 949 try:
950 950 ui.write(r.revision(r.lookup(rev)))
951 951 except KeyError:
952 952 raise util.Abort(_('invalid revision identifier %s') % rev)
953 953
954 954 def debugdate(ui, date, range=None, **opts):
955 955 """parse and display a date"""
956 956 if opts["extended"]:
957 957 d = util.parsedate(date, util.extendeddateformats)
958 958 else:
959 959 d = util.parsedate(date)
960 960 ui.write("internal: %s %s\n" % d)
961 961 ui.write("standard: %s\n" % util.datestr(d))
962 962 if range:
963 963 m = util.matchdate(range)
964 964 ui.write("match: %s\n" % m(d[0]))
965 965
966 966 def debugindex(ui, file_):
967 967 """dump the contents of an index file"""
968 968 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
969 969 ui.write(" rev offset length base linkrev"
970 970 " nodeid p1 p2\n")
971 971 for i in r:
972 972 node = r.node(i)
973 973 try:
974 974 pp = r.parents(node)
975 975 except:
976 976 pp = [nullid, nullid]
977 977 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
978 978 i, r.start(i), r.length(i), r.base(i), r.linkrev(i),
979 979 short(node), short(pp[0]), short(pp[1])))
980 980
981 981 def debugindexdot(ui, file_):
982 982 """dump an index DAG as a graphviz dot file"""
983 983 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
984 984 ui.write("digraph G {\n")
985 985 for i in r:
986 986 node = r.node(i)
987 987 pp = r.parents(node)
988 988 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
989 989 if pp[1] != nullid:
990 990 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
991 991 ui.write("}\n")
992 992
993 993 def debuginstall(ui):
994 994 '''test Mercurial installation'''
995 995
996 996 def writetemp(contents):
997 997 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
998 998 f = os.fdopen(fd, "wb")
999 999 f.write(contents)
1000 1000 f.close()
1001 1001 return name
1002 1002
1003 1003 problems = 0
1004 1004
1005 1005 # encoding
1006 1006 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1007 1007 try:
1008 1008 encoding.fromlocal("test")
1009 1009 except util.Abort, inst:
1010 1010 ui.write(" %s\n" % inst)
1011 1011 ui.write(_(" (check that your locale is properly set)\n"))
1012 1012 problems += 1
1013 1013
1014 1014 # compiled modules
1015 1015 ui.status(_("Checking extensions...\n"))
1016 1016 try:
1017 1017 import bdiff, mpatch, base85
1018 1018 except Exception, inst:
1019 1019 ui.write(" %s\n" % inst)
1020 1020 ui.write(_(" One or more extensions could not be found"))
1021 1021 ui.write(_(" (check that you compiled the extensions)\n"))
1022 1022 problems += 1
1023 1023
1024 1024 # templates
1025 1025 ui.status(_("Checking templates...\n"))
1026 1026 try:
1027 1027 import templater
1028 1028 templater.templater(templater.templatepath("map-cmdline.default"))
1029 1029 except Exception, inst:
1030 1030 ui.write(" %s\n" % inst)
1031 1031 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1032 1032 problems += 1
1033 1033
1034 1034 # patch
1035 1035 ui.status(_("Checking patch...\n"))
1036 1036 patchproblems = 0
1037 1037 a = "1\n2\n3\n4\n"
1038 1038 b = "1\n2\n3\ninsert\n4\n"
1039 1039 fa = writetemp(a)
1040 1040 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
1041 1041 os.path.basename(fa))
1042 1042 fd = writetemp(d)
1043 1043
1044 1044 files = {}
1045 1045 try:
1046 1046 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
1047 1047 except util.Abort, e:
1048 1048 ui.write(_(" patch call failed:\n"))
1049 1049 ui.write(" " + str(e) + "\n")
1050 1050 patchproblems += 1
1051 1051 else:
1052 1052 if list(files) != [os.path.basename(fa)]:
1053 1053 ui.write(_(" unexpected patch output!\n"))
1054 1054 patchproblems += 1
1055 1055 a = open(fa).read()
1056 1056 if a != b:
1057 1057 ui.write(_(" patch test failed!\n"))
1058 1058 patchproblems += 1
1059 1059
1060 1060 if patchproblems:
1061 1061 if ui.config('ui', 'patch'):
1062 1062 ui.write(_(" (Current patch tool may be incompatible with patch,"
1063 1063 " or misconfigured. Please check your .hgrc file)\n"))
1064 1064 else:
1065 1065 ui.write(_(" Internal patcher failure, please report this error"
1066 1066 " to http://mercurial.selenic.com/bts/\n"))
1067 1067 problems += patchproblems
1068 1068
1069 1069 os.unlink(fa)
1070 1070 os.unlink(fd)
1071 1071
1072 1072 # editor
1073 1073 ui.status(_("Checking commit editor...\n"))
1074 1074 editor = ui.geteditor()
1075 1075 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
1076 1076 if not cmdpath:
1077 1077 if editor == 'vi':
1078 1078 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1079 1079 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1080 1080 else:
1081 1081 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1082 1082 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1083 1083 problems += 1
1084 1084
1085 1085 # check username
1086 1086 ui.status(_("Checking username...\n"))
1087 1087 try:
1088 1088 user = ui.username()
1089 1089 except util.Abort, e:
1090 1090 ui.write(" %s\n" % e)
1091 1091 ui.write(_(" (specify a username in your .hgrc file)\n"))
1092 1092 problems += 1
1093 1093
1094 1094 if not problems:
1095 1095 ui.status(_("No problems detected\n"))
1096 1096 else:
1097 1097 ui.write(_("%s problems detected,"
1098 1098 " please check your install!\n") % problems)
1099 1099
1100 1100 return problems
1101 1101
1102 1102 def debugrename(ui, repo, file1, *pats, **opts):
1103 1103 """dump rename information"""
1104 1104
1105 1105 ctx = repo[opts.get('rev')]
1106 1106 m = cmdutil.match(repo, (file1,) + pats, opts)
1107 1107 for abs in ctx.walk(m):
1108 1108 fctx = ctx[abs]
1109 1109 o = fctx.filelog().renamed(fctx.filenode())
1110 1110 rel = m.rel(abs)
1111 1111 if o:
1112 1112 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1113 1113 else:
1114 1114 ui.write(_("%s not renamed\n") % rel)
1115 1115
1116 1116 def debugwalk(ui, repo, *pats, **opts):
1117 1117 """show how files match on given patterns"""
1118 1118 m = cmdutil.match(repo, pats, opts)
1119 1119 items = list(repo.walk(m))
1120 1120 if not items:
1121 1121 return
1122 1122 fmt = 'f %%-%ds %%-%ds %%s' % (
1123 1123 max([len(abs) for abs in items]),
1124 1124 max([len(m.rel(abs)) for abs in items]))
1125 1125 for abs in items:
1126 1126 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
1127 1127 ui.write("%s\n" % line.rstrip())
1128 1128
1129 1129 def diff(ui, repo, *pats, **opts):
1130 1130 """diff repository (or selected files)
1131 1131
1132 1132 Show differences between revisions for the specified files.
1133 1133
1134 1134 Differences between files are shown using the unified diff format.
1135 1135
1136 1136 NOTE: diff may generate unexpected results for merges, as it will
1137 1137 default to comparing against the working directory's first parent
1138 1138 changeset if no revisions are specified.
1139 1139
1140 1140 When two revision arguments are given, then changes are shown
1141 1141 between those revisions. If only one revision is specified then
1142 1142 that revision is compared to the working directory, and, when no
1143 1143 revisions are specified, the working directory files are compared
1144 1144 to its parent.
1145 1145
1146 1146 Alternatively you can specify -c/--change with a revision to see
1147 1147 the changes in that changeset relative to its first parent.
1148 1148
1149 1149 Without the -a/--text option, diff will avoid generating diffs of
1150 1150 files it detects as binary. With -a, diff will generate a diff
1151 1151 anyway, probably with undesirable results.
1152 1152
1153 1153 Use the -g/--git option to generate diffs in the git extended diff
1154 format. For more information, read 'hg help diffs'.
1154 format. For more information, read :hg:`help diffs`.
1155 1155 """
1156 1156
1157 1157 revs = opts.get('rev')
1158 1158 change = opts.get('change')
1159 1159 stat = opts.get('stat')
1160 1160 reverse = opts.get('reverse')
1161 1161
1162 1162 if revs and change:
1163 1163 msg = _('cannot specify --rev and --change at the same time')
1164 1164 raise util.Abort(msg)
1165 1165 elif change:
1166 1166 node2 = repo.lookup(change)
1167 1167 node1 = repo[node2].parents()[0].node()
1168 1168 else:
1169 1169 node1, node2 = cmdutil.revpair(repo, revs)
1170 1170
1171 1171 if reverse:
1172 1172 node1, node2 = node2, node1
1173 1173
1174 1174 if stat:
1175 1175 opts['unified'] = '0'
1176 1176 diffopts = patch.diffopts(ui, opts)
1177 1177
1178 1178 m = cmdutil.match(repo, pats, opts)
1179 1179 if stat:
1180 1180 it = patch.diff(repo, node1, node2, match=m, opts=diffopts)
1181 1181 width = 80
1182 1182 if not ui.plain():
1183 1183 width = util.termwidth()
1184 1184 for chunk, label in patch.diffstatui(util.iterlines(it), width=width,
1185 1185 git=diffopts.git):
1186 1186 ui.write(chunk, label=label)
1187 1187 else:
1188 1188 it = patch.diffui(repo, node1, node2, match=m, opts=diffopts)
1189 1189 for chunk, label in it:
1190 1190 ui.write(chunk, label=label)
1191 1191
1192 1192 def export(ui, repo, *changesets, **opts):
1193 1193 """dump the header and diffs for one or more changesets
1194 1194
1195 1195 Print the changeset header and diffs for one or more revisions.
1196 1196
1197 1197 The information shown in the changeset header is: author, date,
1198 1198 branch name (if non-default), changeset hash, parent(s) and commit
1199 1199 comment.
1200 1200
1201 1201 NOTE: export may generate unexpected diff output for merge
1202 1202 changesets, as it will compare the merge changeset against its
1203 1203 first parent only.
1204 1204
1205 1205 Output may be to a file, in which case the name of the file is
1206 1206 given using a format string. The formatting rules are as follows:
1207 1207
1208 1208 :``%%``: literal "%" character
1209 1209 :``%H``: changeset hash (40 bytes of hexadecimal)
1210 1210 :``%N``: number of patches being generated
1211 1211 :``%R``: changeset revision number
1212 1212 :``%b``: basename of the exporting repository
1213 1213 :``%h``: short-form changeset hash (12 bytes of hexadecimal)
1214 1214 :``%n``: zero-padded sequence number, starting at 1
1215 1215 :``%r``: zero-padded changeset revision number
1216 1216
1217 1217 Without the -a/--text option, export will avoid generating diffs
1218 1218 of files it detects as binary. With -a, export will generate a
1219 1219 diff anyway, probably with undesirable results.
1220 1220
1221 1221 Use the -g/--git option to generate diffs in the git extended diff
1222 format. See 'hg help diffs' for more information.
1222 format. See :hg:`help diffs` for more information.
1223 1223
1224 1224 With the --switch-parent option, the diff will be against the
1225 1225 second parent. It can be useful to review a merge.
1226 1226 """
1227 1227 changesets += tuple(opts.get('rev', []))
1228 1228 if not changesets:
1229 1229 raise util.Abort(_("export requires at least one changeset"))
1230 1230 revs = cmdutil.revrange(repo, changesets)
1231 1231 if len(revs) > 1:
1232 1232 ui.note(_('exporting patches:\n'))
1233 1233 else:
1234 1234 ui.note(_('exporting patch:\n'))
1235 1235 cmdutil.export(repo, revs, template=opts.get('output'),
1236 1236 switch_parent=opts.get('switch_parent'),
1237 1237 opts=patch.diffopts(ui, opts))
1238 1238
1239 1239 def forget(ui, repo, *pats, **opts):
1240 1240 """forget the specified files on the next commit
1241 1241
1242 1242 Mark the specified files so they will no longer be tracked
1243 1243 after the next commit.
1244 1244
1245 1245 This only removes files from the current branch, not from the
1246 1246 entire project history, and it does not delete them from the
1247 1247 working directory.
1248 1248
1249 1249 To undo a forget before the next commit, see hg add.
1250 1250 """
1251 1251
1252 1252 if not pats:
1253 1253 raise util.Abort(_('no files specified'))
1254 1254
1255 1255 m = cmdutil.match(repo, pats, opts)
1256 1256 s = repo.status(match=m, clean=True)
1257 1257 forget = sorted(s[0] + s[1] + s[3] + s[6])
1258 1258
1259 1259 for f in m.files():
1260 1260 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
1261 1261 ui.warn(_('not removing %s: file is already untracked\n')
1262 1262 % m.rel(f))
1263 1263
1264 1264 for f in forget:
1265 1265 if ui.verbose or not m.exact(f):
1266 1266 ui.status(_('removing %s\n') % m.rel(f))
1267 1267
1268 1268 repo.remove(forget, unlink=False)
1269 1269
1270 1270 def grep(ui, repo, pattern, *pats, **opts):
1271 1271 """search for a pattern in specified files and revisions
1272 1272
1273 1273 Search revisions of files for a regular expression.
1274 1274
1275 1275 This command behaves differently than Unix grep. It only accepts
1276 1276 Python/Perl regexps. It searches repository history, not the
1277 1277 working directory. It always prints the revision number in which a
1278 1278 match appears.
1279 1279
1280 1280 By default, grep only prints output for the first revision of a
1281 1281 file in which it finds a match. To get it to print every revision
1282 1282 that contains a change in match status ("-" for a match that
1283 1283 becomes a non-match, or "+" for a non-match that becomes a match),
1284 1284 use the --all flag.
1285 1285 """
1286 1286 reflags = 0
1287 1287 if opts.get('ignore_case'):
1288 1288 reflags |= re.I
1289 1289 try:
1290 1290 regexp = re.compile(pattern, reflags)
1291 1291 except Exception, inst:
1292 1292 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
1293 1293 return None
1294 1294 sep, eol = ':', '\n'
1295 1295 if opts.get('print0'):
1296 1296 sep = eol = '\0'
1297 1297
1298 1298 getfile = util.lrucachefunc(repo.file)
1299 1299
1300 1300 def matchlines(body):
1301 1301 begin = 0
1302 1302 linenum = 0
1303 1303 while True:
1304 1304 match = regexp.search(body, begin)
1305 1305 if not match:
1306 1306 break
1307 1307 mstart, mend = match.span()
1308 1308 linenum += body.count('\n', begin, mstart) + 1
1309 1309 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1310 1310 begin = body.find('\n', mend) + 1 or len(body)
1311 1311 lend = begin - 1
1312 1312 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1313 1313
1314 1314 class linestate(object):
1315 1315 def __init__(self, line, linenum, colstart, colend):
1316 1316 self.line = line
1317 1317 self.linenum = linenum
1318 1318 self.colstart = colstart
1319 1319 self.colend = colend
1320 1320
1321 1321 def __hash__(self):
1322 1322 return hash((self.linenum, self.line))
1323 1323
1324 1324 def __eq__(self, other):
1325 1325 return self.line == other.line
1326 1326
1327 1327 matches = {}
1328 1328 copies = {}
1329 1329 def grepbody(fn, rev, body):
1330 1330 matches[rev].setdefault(fn, [])
1331 1331 m = matches[rev][fn]
1332 1332 for lnum, cstart, cend, line in matchlines(body):
1333 1333 s = linestate(line, lnum, cstart, cend)
1334 1334 m.append(s)
1335 1335
1336 1336 def difflinestates(a, b):
1337 1337 sm = difflib.SequenceMatcher(None, a, b)
1338 1338 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1339 1339 if tag == 'insert':
1340 1340 for i in xrange(blo, bhi):
1341 1341 yield ('+', b[i])
1342 1342 elif tag == 'delete':
1343 1343 for i in xrange(alo, ahi):
1344 1344 yield ('-', a[i])
1345 1345 elif tag == 'replace':
1346 1346 for i in xrange(alo, ahi):
1347 1347 yield ('-', a[i])
1348 1348 for i in xrange(blo, bhi):
1349 1349 yield ('+', b[i])
1350 1350
1351 1351 def display(fn, ctx, pstates, states):
1352 1352 rev = ctx.rev()
1353 1353 datefunc = ui.quiet and util.shortdate or util.datestr
1354 1354 found = False
1355 1355 filerevmatches = {}
1356 1356 if opts.get('all'):
1357 1357 iter = difflinestates(pstates, states)
1358 1358 else:
1359 1359 iter = [('', l) for l in states]
1360 1360 for change, l in iter:
1361 1361 cols = [fn, str(rev)]
1362 1362 before, match, after = None, None, None
1363 1363 if opts.get('line_number'):
1364 1364 cols.append(str(l.linenum))
1365 1365 if opts.get('all'):
1366 1366 cols.append(change)
1367 1367 if opts.get('user'):
1368 1368 cols.append(ui.shortuser(ctx.user()))
1369 1369 if opts.get('date'):
1370 1370 cols.append(datefunc(ctx.date()))
1371 1371 if opts.get('files_with_matches'):
1372 1372 c = (fn, rev)
1373 1373 if c in filerevmatches:
1374 1374 continue
1375 1375 filerevmatches[c] = 1
1376 1376 else:
1377 1377 before = l.line[:l.colstart]
1378 1378 match = l.line[l.colstart:l.colend]
1379 1379 after = l.line[l.colend:]
1380 1380 ui.write(sep.join(cols))
1381 1381 if before is not None:
1382 1382 ui.write(sep + before)
1383 1383 ui.write(match, label='grep.match')
1384 1384 ui.write(after)
1385 1385 ui.write(eol)
1386 1386 found = True
1387 1387 return found
1388 1388
1389 1389 skip = {}
1390 1390 revfiles = {}
1391 1391 matchfn = cmdutil.match(repo, pats, opts)
1392 1392 found = False
1393 1393 follow = opts.get('follow')
1394 1394
1395 1395 def prep(ctx, fns):
1396 1396 rev = ctx.rev()
1397 1397 pctx = ctx.parents()[0]
1398 1398 parent = pctx.rev()
1399 1399 matches.setdefault(rev, {})
1400 1400 matches.setdefault(parent, {})
1401 1401 files = revfiles.setdefault(rev, [])
1402 1402 for fn in fns:
1403 1403 flog = getfile(fn)
1404 1404 try:
1405 1405 fnode = ctx.filenode(fn)
1406 1406 except error.LookupError:
1407 1407 continue
1408 1408
1409 1409 copied = flog.renamed(fnode)
1410 1410 copy = follow and copied and copied[0]
1411 1411 if copy:
1412 1412 copies.setdefault(rev, {})[fn] = copy
1413 1413 if fn in skip:
1414 1414 if copy:
1415 1415 skip[copy] = True
1416 1416 continue
1417 1417 files.append(fn)
1418 1418
1419 1419 if fn not in matches[rev]:
1420 1420 grepbody(fn, rev, flog.read(fnode))
1421 1421
1422 1422 pfn = copy or fn
1423 1423 if pfn not in matches[parent]:
1424 1424 try:
1425 1425 fnode = pctx.filenode(pfn)
1426 1426 grepbody(pfn, parent, flog.read(fnode))
1427 1427 except error.LookupError:
1428 1428 pass
1429 1429
1430 1430 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
1431 1431 rev = ctx.rev()
1432 1432 parent = ctx.parents()[0].rev()
1433 1433 for fn in sorted(revfiles.get(rev, [])):
1434 1434 states = matches[rev][fn]
1435 1435 copy = copies.get(rev, {}).get(fn)
1436 1436 if fn in skip:
1437 1437 if copy:
1438 1438 skip[copy] = True
1439 1439 continue
1440 1440 pstates = matches.get(parent, {}).get(copy or fn, [])
1441 1441 if pstates or states:
1442 1442 r = display(fn, ctx, pstates, states)
1443 1443 found = found or r
1444 1444 if r and not opts.get('all'):
1445 1445 skip[fn] = True
1446 1446 if copy:
1447 1447 skip[copy] = True
1448 1448 del matches[rev]
1449 1449 del revfiles[rev]
1450 1450
1451 1451 def heads(ui, repo, *branchrevs, **opts):
1452 1452 """show current repository heads or show branch heads
1453 1453
1454 1454 With no arguments, show all repository branch heads.
1455 1455
1456 1456 Repository "heads" are changesets with no child changesets. They are
1457 1457 where development generally takes place and are the usual targets
1458 1458 for update and merge operations. Branch heads are changesets that have
1459 1459 no child changeset on the same branch.
1460 1460
1461 1461 If one or more REVs are given, only branch heads on the branches
1462 1462 associated with the specified changesets are shown.
1463 1463
1464 1464 If -c/--closed is specified, also show branch heads marked closed
1465 1465 (see hg commit --close-branch).
1466 1466
1467 1467 If STARTREV is specified, only those heads that are descendants of
1468 1468 STARTREV will be displayed.
1469 1469
1470 1470 If -t/--topo is specified, named branch mechanics will be ignored and only
1471 1471 changesets without children will be shown.
1472 1472 """
1473 1473
1474 1474 if opts.get('rev'):
1475 1475 start = repo.lookup(opts['rev'])
1476 1476 else:
1477 1477 start = None
1478 1478
1479 1479 if opts.get('topo'):
1480 1480 heads = [repo[h] for h in repo.heads(start)]
1481 1481 else:
1482 1482 heads = []
1483 1483 for b, ls in repo.branchmap().iteritems():
1484 1484 if start is None:
1485 1485 heads += [repo[h] for h in ls]
1486 1486 continue
1487 1487 startrev = repo.changelog.rev(start)
1488 1488 descendants = set(repo.changelog.descendants(startrev))
1489 1489 descendants.add(startrev)
1490 1490 rev = repo.changelog.rev
1491 1491 heads += [repo[h] for h in ls if rev(h) in descendants]
1492 1492
1493 1493 if branchrevs:
1494 1494 decode, encode = encoding.fromlocal, encoding.tolocal
1495 1495 branches = set(repo[decode(br)].branch() for br in branchrevs)
1496 1496 heads = [h for h in heads if h.branch() in branches]
1497 1497
1498 1498 if not opts.get('closed'):
1499 1499 heads = [h for h in heads if not h.extra().get('close')]
1500 1500
1501 1501 if opts.get('active') and branchrevs:
1502 1502 dagheads = repo.heads(start)
1503 1503 heads = [h for h in heads if h.node() in dagheads]
1504 1504
1505 1505 if branchrevs:
1506 1506 haveheads = set(h.branch() for h in heads)
1507 1507 if branches - haveheads:
1508 1508 headless = ', '.join(encode(b) for b in branches - haveheads)
1509 1509 msg = _('no open branch heads found on branches %s')
1510 1510 if opts.get('rev'):
1511 1511 msg += _(' (started at %s)' % opts['rev'])
1512 1512 ui.warn((msg + '\n') % headless)
1513 1513
1514 1514 if not heads:
1515 1515 return 1
1516 1516
1517 1517 heads = sorted(heads, key=lambda x: -x.rev())
1518 1518 displayer = cmdutil.show_changeset(ui, repo, opts)
1519 1519 for ctx in heads:
1520 1520 displayer.show(ctx)
1521 1521 displayer.close()
1522 1522
1523 1523 def help_(ui, name=None, with_version=False, unknowncmd=False):
1524 1524 """show help for a given topic or a help overview
1525 1525
1526 1526 With no arguments, print a list of commands with short help messages.
1527 1527
1528 1528 Given a topic, extension, or command name, print help for that
1529 1529 topic."""
1530 1530 option_lists = []
1531 1531 textwidth = util.termwidth() - 2
1532 1532
1533 1533 def addglobalopts(aliases):
1534 1534 if ui.verbose:
1535 1535 option_lists.append((_("global options:"), globalopts))
1536 1536 if name == 'shortlist':
1537 1537 option_lists.append((_('use "hg help" for the full list '
1538 1538 'of commands'), ()))
1539 1539 else:
1540 1540 if name == 'shortlist':
1541 1541 msg = _('use "hg help" for the full list of commands '
1542 1542 'or "hg -v" for details')
1543 1543 elif aliases:
1544 1544 msg = _('use "hg -v help%s" to show aliases and '
1545 1545 'global options') % (name and " " + name or "")
1546 1546 else:
1547 1547 msg = _('use "hg -v help %s" to show global options') % name
1548 1548 option_lists.append((msg, ()))
1549 1549
1550 1550 def helpcmd(name):
1551 1551 if with_version:
1552 1552 version_(ui)
1553 1553 ui.write('\n')
1554 1554
1555 1555 try:
1556 1556 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
1557 1557 except error.AmbiguousCommand, inst:
1558 1558 # py3k fix: except vars can't be used outside the scope of the
1559 1559 # except block, nor can be used inside a lambda. python issue4617
1560 1560 prefix = inst.args[0]
1561 1561 select = lambda c: c.lstrip('^').startswith(prefix)
1562 1562 helplist(_('list of commands:\n\n'), select)
1563 1563 return
1564 1564
1565 1565 # check if it's an invalid alias and display its error if it is
1566 1566 if getattr(entry[0], 'badalias', False):
1567 1567 if not unknowncmd:
1568 1568 entry[0](ui)
1569 1569 return
1570 1570
1571 1571 # synopsis
1572 1572 if len(entry) > 2:
1573 1573 if entry[2].startswith('hg'):
1574 1574 ui.write("%s\n" % entry[2])
1575 1575 else:
1576 1576 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
1577 1577 else:
1578 1578 ui.write('hg %s\n' % aliases[0])
1579 1579
1580 1580 # aliases
1581 1581 if not ui.quiet and len(aliases) > 1:
1582 1582 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1583 1583
1584 1584 # description
1585 1585 doc = gettext(entry[0].__doc__)
1586 1586 if not doc:
1587 1587 doc = _("(no help text available)")
1588 1588 if hasattr(entry[0], 'definition'): # aliased command
1589 1589 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
1590 1590 if ui.quiet:
1591 1591 doc = doc.splitlines()[0]
1592 1592 keep = ui.verbose and ['verbose'] or []
1593 1593 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
1594 1594 ui.write("\n%s\n" % formatted)
1595 1595 if pruned:
1596 1596 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
1597 1597
1598 1598 if not ui.quiet:
1599 1599 # options
1600 1600 if entry[1]:
1601 1601 option_lists.append((_("options:\n"), entry[1]))
1602 1602
1603 1603 addglobalopts(False)
1604 1604
1605 1605 def helplist(header, select=None):
1606 1606 h = {}
1607 1607 cmds = {}
1608 1608 for c, e in table.iteritems():
1609 1609 f = c.split("|", 1)[0]
1610 1610 if select and not select(f):
1611 1611 continue
1612 1612 if (not select and name != 'shortlist' and
1613 1613 e[0].__module__ != __name__):
1614 1614 continue
1615 1615 if name == "shortlist" and not f.startswith("^"):
1616 1616 continue
1617 1617 f = f.lstrip("^")
1618 1618 if not ui.debugflag and f.startswith("debug"):
1619 1619 continue
1620 1620 doc = e[0].__doc__
1621 1621 if doc and 'DEPRECATED' in doc and not ui.verbose:
1622 1622 continue
1623 1623 doc = gettext(doc)
1624 1624 if not doc:
1625 1625 doc = _("(no help text available)")
1626 1626 h[f] = doc.splitlines()[0].rstrip()
1627 1627 cmds[f] = c.lstrip("^")
1628 1628
1629 1629 if not h:
1630 1630 ui.status(_('no commands defined\n'))
1631 1631 return
1632 1632
1633 1633 ui.status(header)
1634 1634 fns = sorted(h)
1635 1635 m = max(map(len, fns))
1636 1636 for f in fns:
1637 1637 if ui.verbose:
1638 1638 commands = cmds[f].replace("|",", ")
1639 1639 ui.write(" %s:\n %s\n"%(commands, h[f]))
1640 1640 else:
1641 1641 ui.write(' %-*s %s\n' % (m, f, util.wrap(h[f], m + 4)))
1642 1642
1643 1643 if not ui.quiet:
1644 1644 addglobalopts(True)
1645 1645
1646 1646 def helptopic(name):
1647 1647 for names, header, doc in help.helptable:
1648 1648 if name in names:
1649 1649 break
1650 1650 else:
1651 1651 raise error.UnknownCommand(name)
1652 1652
1653 1653 # description
1654 1654 if not doc:
1655 1655 doc = _("(no help text available)")
1656 1656 if hasattr(doc, '__call__'):
1657 1657 doc = doc()
1658 1658
1659 1659 ui.write("%s\n\n" % header)
1660 1660 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
1661 1661
1662 1662 def helpext(name):
1663 1663 try:
1664 1664 mod = extensions.find(name)
1665 1665 doc = gettext(mod.__doc__) or _('no help text available')
1666 1666 except KeyError:
1667 1667 mod = None
1668 1668 doc = extensions.disabledext(name)
1669 1669 if not doc:
1670 1670 raise error.UnknownCommand(name)
1671 1671
1672 1672 if '\n' not in doc:
1673 1673 head, tail = doc, ""
1674 1674 else:
1675 1675 head, tail = doc.split('\n', 1)
1676 1676 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
1677 1677 if tail:
1678 1678 ui.write(minirst.format(tail, textwidth))
1679 1679 ui.status('\n\n')
1680 1680
1681 1681 if mod:
1682 1682 try:
1683 1683 ct = mod.cmdtable
1684 1684 except AttributeError:
1685 1685 ct = {}
1686 1686 modcmds = set([c.split('|', 1)[0] for c in ct])
1687 1687 helplist(_('list of commands:\n\n'), modcmds.__contains__)
1688 1688 else:
1689 1689 ui.write(_('use "hg help extensions" for information on enabling '
1690 1690 'extensions\n'))
1691 1691
1692 1692 def helpextcmd(name):
1693 1693 cmd, ext, mod = extensions.disabledcmd(name, ui.config('ui', 'strict'))
1694 1694 doc = gettext(mod.__doc__).splitlines()[0]
1695 1695
1696 1696 msg = help.listexts(_("'%s' is provided by the following "
1697 1697 "extension:") % cmd, {ext: doc}, len(ext),
1698 1698 indent=4)
1699 1699 ui.write(minirst.format(msg, textwidth))
1700 1700 ui.write('\n\n')
1701 1701 ui.write(_('use "hg help extensions" for information on enabling '
1702 1702 'extensions\n'))
1703 1703
1704 1704 if name and name != 'shortlist':
1705 1705 i = None
1706 1706 if unknowncmd:
1707 1707 queries = (helpextcmd,)
1708 1708 else:
1709 1709 queries = (helptopic, helpcmd, helpext, helpextcmd)
1710 1710 for f in queries:
1711 1711 try:
1712 1712 f(name)
1713 1713 i = None
1714 1714 break
1715 1715 except error.UnknownCommand, inst:
1716 1716 i = inst
1717 1717 if i:
1718 1718 raise i
1719 1719
1720 1720 else:
1721 1721 # program name
1722 1722 if ui.verbose or with_version:
1723 1723 version_(ui)
1724 1724 else:
1725 1725 ui.status(_("Mercurial Distributed SCM\n"))
1726 1726 ui.status('\n')
1727 1727
1728 1728 # list of commands
1729 1729 if name == "shortlist":
1730 1730 header = _('basic commands:\n\n')
1731 1731 else:
1732 1732 header = _('list of commands:\n\n')
1733 1733
1734 1734 helplist(header)
1735 1735 if name != 'shortlist':
1736 1736 exts, maxlength = extensions.enabled()
1737 1737 text = help.listexts(_('enabled extensions:'), exts, maxlength)
1738 1738 if text:
1739 1739 ui.write("\n%s\n" % minirst.format(text, textwidth))
1740 1740
1741 1741 # list all option lists
1742 1742 opt_output = []
1743 1743 for title, options in option_lists:
1744 1744 opt_output.append(("\n%s" % title, None))
1745 1745 for shortopt, longopt, default, desc in options:
1746 1746 if _("DEPRECATED") in desc and not ui.verbose:
1747 1747 continue
1748 1748 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
1749 1749 longopt and " --%s" % longopt),
1750 1750 "%s%s" % (desc,
1751 1751 default
1752 1752 and _(" (default: %s)") % default
1753 1753 or "")))
1754 1754
1755 1755 if not name:
1756 1756 ui.write(_("\nadditional help topics:\n\n"))
1757 1757 topics = []
1758 1758 for names, header, doc in help.helptable:
1759 1759 topics.append((sorted(names, key=len, reverse=True)[0], header))
1760 1760 topics_len = max([len(s[0]) for s in topics])
1761 1761 for t, desc in topics:
1762 1762 ui.write(" %-*s %s\n" % (topics_len, t, desc))
1763 1763
1764 1764 if opt_output:
1765 1765 opts_len = max([len(line[0]) for line in opt_output if line[1]] or [0])
1766 1766 for first, second in opt_output:
1767 1767 if second:
1768 1768 second = util.wrap(second, opts_len + 3)
1769 1769 ui.write(" %-*s %s\n" % (opts_len, first, second))
1770 1770 else:
1771 1771 ui.write("%s\n" % first)
1772 1772
1773 1773 def identify(ui, repo, source=None,
1774 1774 rev=None, num=None, id=None, branch=None, tags=None):
1775 1775 """identify the working copy or specified revision
1776 1776
1777 1777 With no revision, print a summary of the current state of the
1778 1778 repository.
1779 1779
1780 1780 Specifying a path to a repository root or Mercurial bundle will
1781 1781 cause lookup to operate on that repository/bundle.
1782 1782
1783 1783 This summary identifies the repository state using one or two
1784 1784 parent hash identifiers, followed by a "+" if there are
1785 1785 uncommitted changes in the working directory, a list of tags for
1786 1786 this revision and a branch name for non-default branches.
1787 1787 """
1788 1788
1789 1789 if not repo and not source:
1790 1790 raise util.Abort(_("There is no Mercurial repository here "
1791 1791 "(.hg not found)"))
1792 1792
1793 1793 hexfunc = ui.debugflag and hex or short
1794 1794 default = not (num or id or branch or tags)
1795 1795 output = []
1796 1796
1797 1797 revs = []
1798 1798 if source:
1799 1799 source, branches = hg.parseurl(ui.expandpath(source))
1800 1800 repo = hg.repository(ui, source)
1801 1801 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
1802 1802
1803 1803 if not repo.local():
1804 1804 if not rev and revs:
1805 1805 rev = revs[0]
1806 1806 if not rev:
1807 1807 rev = "tip"
1808 1808 if num or branch or tags:
1809 1809 raise util.Abort(
1810 1810 "can't query remote revision number, branch, or tags")
1811 1811 output = [hexfunc(repo.lookup(rev))]
1812 1812 elif not rev:
1813 1813 ctx = repo[None]
1814 1814 parents = ctx.parents()
1815 1815 changed = False
1816 1816 if default or id or num:
1817 1817 changed = util.any(repo.status())
1818 1818 if default or id:
1819 1819 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
1820 1820 (changed) and "+" or "")]
1821 1821 if num:
1822 1822 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
1823 1823 (changed) and "+" or ""))
1824 1824 else:
1825 1825 ctx = repo[rev]
1826 1826 if default or id:
1827 1827 output = [hexfunc(ctx.node())]
1828 1828 if num:
1829 1829 output.append(str(ctx.rev()))
1830 1830
1831 1831 if repo.local() and default and not ui.quiet:
1832 1832 b = encoding.tolocal(ctx.branch())
1833 1833 if b != 'default':
1834 1834 output.append("(%s)" % b)
1835 1835
1836 1836 # multiple tags for a single parent separated by '/'
1837 1837 t = "/".join(ctx.tags())
1838 1838 if t:
1839 1839 output.append(t)
1840 1840
1841 1841 if branch:
1842 1842 output.append(encoding.tolocal(ctx.branch()))
1843 1843
1844 1844 if tags:
1845 1845 output.extend(ctx.tags())
1846 1846
1847 1847 ui.write("%s\n" % ' '.join(output))
1848 1848
1849 1849 def import_(ui, repo, patch1, *patches, **opts):
1850 1850 """import an ordered set of patches
1851 1851
1852 1852 Import a list of patches and commit them individually (unless
1853 1853 --no-commit is specified).
1854 1854
1855 1855 If there are outstanding changes in the working directory, import
1856 1856 will abort unless given the -f/--force flag.
1857 1857
1858 1858 You can import a patch straight from a mail message. Even patches
1859 1859 as attachments work (to use the body part, it must have type
1860 1860 text/plain or text/x-patch). From and Subject headers of email
1861 1861 message are used as default committer and commit message. All
1862 1862 text/plain body parts before first diff are added to commit
1863 1863 message.
1864 1864
1865 1865 If the imported patch was generated by hg export, user and
1866 1866 description from patch override values from message headers and
1867 1867 body. Values given on command line with -m/--message and -u/--user
1868 1868 override these.
1869 1869
1870 1870 If --exact is specified, import will set the working directory to
1871 1871 the parent of each patch before applying it, and will abort if the
1872 1872 resulting changeset has a different ID than the one recorded in
1873 1873 the patch. This may happen due to character set problems or other
1874 1874 deficiencies in the text patch format.
1875 1875
1876 1876 With -s/--similarity, hg will attempt to discover renames and
1877 1877 copies in the patch in the same way as 'addremove'.
1878 1878
1879 1879 To read a patch from standard input, use "-" as the patch name. If
1880 1880 a URL is specified, the patch will be downloaded from it.
1881 See 'hg help dates' for a list of formats valid for -d/--date.
1881 See :hg:`help dates` for a list of formats valid for -d/--date.
1882 1882 """
1883 1883 patches = (patch1,) + patches
1884 1884
1885 1885 date = opts.get('date')
1886 1886 if date:
1887 1887 opts['date'] = util.parsedate(date)
1888 1888
1889 1889 try:
1890 1890 sim = float(opts.get('similarity') or 0)
1891 1891 except ValueError:
1892 1892 raise util.Abort(_('similarity must be a number'))
1893 1893 if sim < 0 or sim > 100:
1894 1894 raise util.Abort(_('similarity must be between 0 and 100'))
1895 1895
1896 1896 if opts.get('exact') or not opts.get('force'):
1897 1897 cmdutil.bail_if_changed(repo)
1898 1898
1899 1899 d = opts["base"]
1900 1900 strip = opts["strip"]
1901 1901 wlock = lock = None
1902 1902
1903 1903 def tryone(ui, hunk):
1904 1904 tmpname, message, user, date, branch, nodeid, p1, p2 = \
1905 1905 patch.extract(ui, hunk)
1906 1906
1907 1907 if not tmpname:
1908 1908 return None
1909 1909 commitid = _('to working directory')
1910 1910
1911 1911 try:
1912 1912 cmdline_message = cmdutil.logmessage(opts)
1913 1913 if cmdline_message:
1914 1914 # pickup the cmdline msg
1915 1915 message = cmdline_message
1916 1916 elif message:
1917 1917 # pickup the patch msg
1918 1918 message = message.strip()
1919 1919 else:
1920 1920 # launch the editor
1921 1921 message = None
1922 1922 ui.debug('message:\n%s\n' % message)
1923 1923
1924 1924 wp = repo.parents()
1925 1925 if opts.get('exact'):
1926 1926 if not nodeid or not p1:
1927 1927 raise util.Abort(_('not a Mercurial patch'))
1928 1928 p1 = repo.lookup(p1)
1929 1929 p2 = repo.lookup(p2 or hex(nullid))
1930 1930
1931 1931 if p1 != wp[0].node():
1932 1932 hg.clean(repo, p1)
1933 1933 repo.dirstate.setparents(p1, p2)
1934 1934 elif p2:
1935 1935 try:
1936 1936 p1 = repo.lookup(p1)
1937 1937 p2 = repo.lookup(p2)
1938 1938 if p1 == wp[0].node():
1939 1939 repo.dirstate.setparents(p1, p2)
1940 1940 except error.RepoError:
1941 1941 pass
1942 1942 if opts.get('exact') or opts.get('import_branch'):
1943 1943 repo.dirstate.setbranch(branch or 'default')
1944 1944
1945 1945 files = {}
1946 1946 try:
1947 1947 patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
1948 1948 files=files, eolmode=None)
1949 1949 finally:
1950 1950 files = patch.updatedir(ui, repo, files,
1951 1951 similarity=sim / 100.0)
1952 1952 if not opts.get('no_commit'):
1953 1953 if opts.get('exact'):
1954 1954 m = None
1955 1955 else:
1956 1956 m = cmdutil.matchfiles(repo, files or [])
1957 1957 n = repo.commit(message, opts.get('user') or user,
1958 1958 opts.get('date') or date, match=m,
1959 1959 editor=cmdutil.commiteditor)
1960 1960 if opts.get('exact'):
1961 1961 if hex(n) != nodeid:
1962 1962 repo.rollback()
1963 1963 raise util.Abort(_('patch is damaged'
1964 1964 ' or loses information'))
1965 1965 # Force a dirstate write so that the next transaction
1966 1966 # backups an up-do-date file.
1967 1967 repo.dirstate.write()
1968 1968 if n:
1969 1969 commitid = short(n)
1970 1970
1971 1971 return commitid
1972 1972 finally:
1973 1973 os.unlink(tmpname)
1974 1974
1975 1975 try:
1976 1976 wlock = repo.wlock()
1977 1977 lock = repo.lock()
1978 1978 lastcommit = None
1979 1979 for p in patches:
1980 1980 pf = os.path.join(d, p)
1981 1981
1982 1982 if pf == '-':
1983 1983 ui.status(_("applying patch from stdin\n"))
1984 1984 pf = sys.stdin
1985 1985 else:
1986 1986 ui.status(_("applying %s\n") % p)
1987 1987 pf = url.open(ui, pf)
1988 1988
1989 1989 haspatch = False
1990 1990 for hunk in patch.split(pf):
1991 1991 commitid = tryone(ui, hunk)
1992 1992 if commitid:
1993 1993 haspatch = True
1994 1994 if lastcommit:
1995 1995 ui.status(_('applied %s\n') % lastcommit)
1996 1996 lastcommit = commitid
1997 1997
1998 1998 if not haspatch:
1999 1999 raise util.Abort(_('no diffs found'))
2000 2000
2001 2001 finally:
2002 2002 release(lock, wlock)
2003 2003
2004 2004 def incoming(ui, repo, source="default", **opts):
2005 2005 """show new changesets found in source
2006 2006
2007 2007 Show new changesets found in the specified path/URL or the default
2008 2008 pull location. These are the changesets that would have been pulled
2009 2009 if a pull at the time you issued this command.
2010 2010
2011 2011 For remote repository, using --bundle avoids downloading the
2012 2012 changesets twice if the incoming is followed by a pull.
2013 2013
2014 2014 See pull for valid source format details.
2015 2015 """
2016 2016 limit = cmdutil.loglimit(opts)
2017 2017 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2018 2018 other = hg.repository(cmdutil.remoteui(repo, opts), source)
2019 2019 ui.status(_('comparing with %s\n') % url.hidepassword(source))
2020 2020 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2021 2021 if revs:
2022 2022 revs = [other.lookup(rev) for rev in revs]
2023 2023 common, incoming, rheads = repo.findcommonincoming(other, heads=revs,
2024 2024 force=opts["force"])
2025 2025 if not incoming:
2026 2026 try:
2027 2027 os.unlink(opts["bundle"])
2028 2028 except:
2029 2029 pass
2030 2030 ui.status(_("no changes found\n"))
2031 2031 return 1
2032 2032
2033 2033 cleanup = None
2034 2034 try:
2035 2035 fname = opts["bundle"]
2036 2036 if fname or not other.local():
2037 2037 # create a bundle (uncompressed if other repo is not local)
2038 2038
2039 2039 if revs is None and other.capable('changegroupsubset'):
2040 2040 revs = rheads
2041 2041
2042 2042 if revs is None:
2043 2043 cg = other.changegroup(incoming, "incoming")
2044 2044 else:
2045 2045 cg = other.changegroupsubset(incoming, revs, 'incoming')
2046 2046 bundletype = other.local() and "HG10BZ" or "HG10UN"
2047 2047 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
2048 2048 # keep written bundle?
2049 2049 if opts["bundle"]:
2050 2050 cleanup = None
2051 2051 if not other.local():
2052 2052 # use the created uncompressed bundlerepo
2053 2053 other = bundlerepo.bundlerepository(ui, repo.root, fname)
2054 2054
2055 2055 o = other.changelog.nodesbetween(incoming, revs)[0]
2056 2056 if opts.get('newest_first'):
2057 2057 o.reverse()
2058 2058 displayer = cmdutil.show_changeset(ui, other, opts)
2059 2059 count = 0
2060 2060 for n in o:
2061 2061 if limit is not None and count >= limit:
2062 2062 break
2063 2063 parents = [p for p in other.changelog.parents(n) if p != nullid]
2064 2064 if opts.get('no_merges') and len(parents) == 2:
2065 2065 continue
2066 2066 count += 1
2067 2067 displayer.show(other[n])
2068 2068 displayer.close()
2069 2069 finally:
2070 2070 if hasattr(other, 'close'):
2071 2071 other.close()
2072 2072 if cleanup:
2073 2073 os.unlink(cleanup)
2074 2074
2075 2075 def init(ui, dest=".", **opts):
2076 2076 """create a new repository in the given directory
2077 2077
2078 2078 Initialize a new repository in the given directory. If the given
2079 2079 directory does not exist, it will be created.
2080 2080
2081 2081 If no directory is given, the current directory is used.
2082 2082
2083 2083 It is possible to specify an ``ssh://`` URL as the destination.
2084 See 'hg help urls' for more information.
2084 See :hg:`help urls` for more information.
2085 2085 """
2086 2086 hg.repository(cmdutil.remoteui(ui, opts), dest, create=1)
2087 2087
2088 2088 def locate(ui, repo, *pats, **opts):
2089 2089 """locate files matching specific patterns
2090 2090
2091 2091 Print files under Mercurial control in the working directory whose
2092 2092 names match the given patterns.
2093 2093
2094 2094 By default, this command searches all directories in the working
2095 2095 directory. To search just the current directory and its
2096 2096 subdirectories, use "--include .".
2097 2097
2098 2098 If no patterns are given to match, this command prints the names
2099 2099 of all files under Mercurial control in the working directory.
2100 2100
2101 2101 If you want to feed the output of this command into the "xargs"
2102 2102 command, use the -0 option to both this command and "xargs". This
2103 2103 will avoid the problem of "xargs" treating single filenames that
2104 2104 contain whitespace as multiple filenames.
2105 2105 """
2106 2106 end = opts.get('print0') and '\0' or '\n'
2107 2107 rev = opts.get('rev') or None
2108 2108
2109 2109 ret = 1
2110 2110 m = cmdutil.match(repo, pats, opts, default='relglob')
2111 2111 m.bad = lambda x, y: False
2112 2112 for abs in repo[rev].walk(m):
2113 2113 if not rev and abs not in repo.dirstate:
2114 2114 continue
2115 2115 if opts.get('fullpath'):
2116 2116 ui.write(repo.wjoin(abs), end)
2117 2117 else:
2118 2118 ui.write(((pats and m.rel(abs)) or abs), end)
2119 2119 ret = 0
2120 2120
2121 2121 return ret
2122 2122
2123 2123 def log(ui, repo, *pats, **opts):
2124 2124 """show revision history of entire repository or files
2125 2125
2126 2126 Print the revision history of the specified files or the entire
2127 2127 project.
2128 2128
2129 2129 File history is shown without following rename or copy history of
2130 2130 files. Use -f/--follow with a filename to follow history across
2131 2131 renames and copies. --follow without a filename will only show
2132 2132 ancestors or descendants of the starting revision. --follow-first
2133 2133 only follows the first parent of merge revisions.
2134 2134
2135 2135 If no revision range is specified, the default is tip:0 unless
2136 2136 --follow is set, in which case the working directory parent is
2137 2137 used as the starting revision.
2138 2138
2139 See 'hg help dates' for a list of formats valid for -d/--date.
2139 See :hg:`help dates` for a list of formats valid for -d/--date.
2140 2140
2141 2141 By default this command prints revision number and changeset id,
2142 2142 tags, non-trivial parents, user, date and time, and a summary for
2143 2143 each commit. When the -v/--verbose switch is used, the list of
2144 2144 changed files and full commit message are shown.
2145 2145
2146 2146 NOTE: log -p/--patch may generate unexpected diff output for merge
2147 2147 changesets, as it will only compare the merge changeset against
2148 2148 its first parent. Also, only files different from BOTH parents
2149 2149 will appear in files:.
2150 2150 """
2151 2151
2152 2152 matchfn = cmdutil.match(repo, pats, opts)
2153 2153 limit = cmdutil.loglimit(opts)
2154 2154 count = 0
2155 2155
2156 2156 endrev = None
2157 2157 if opts.get('copies') and opts.get('rev'):
2158 2158 endrev = max(cmdutil.revrange(repo, opts.get('rev'))) + 1
2159 2159
2160 2160 df = False
2161 2161 if opts["date"]:
2162 2162 df = util.matchdate(opts["date"])
2163 2163
2164 2164 branches = opts.get('branch', []) + opts.get('only_branch', [])
2165 2165 opts['branch'] = [repo.lookupbranch(b) for b in branches]
2166 2166
2167 2167 displayer = cmdutil.show_changeset(ui, repo, opts, True, matchfn)
2168 2168 def prep(ctx, fns):
2169 2169 rev = ctx.rev()
2170 2170 parents = [p for p in repo.changelog.parentrevs(rev)
2171 2171 if p != nullrev]
2172 2172 if opts.get('no_merges') and len(parents) == 2:
2173 2173 return
2174 2174 if opts.get('only_merges') and len(parents) != 2:
2175 2175 return
2176 2176 if opts.get('branch') and ctx.branch() not in opts['branch']:
2177 2177 return
2178 2178 if df and not df(ctx.date()[0]):
2179 2179 return
2180 2180 if opts['user'] and not [k for k in opts['user'] if k in ctx.user()]:
2181 2181 return
2182 2182 if opts.get('keyword'):
2183 2183 for k in [kw.lower() for kw in opts['keyword']]:
2184 2184 if (k in ctx.user().lower() or
2185 2185 k in ctx.description().lower() or
2186 2186 k in " ".join(ctx.files()).lower()):
2187 2187 break
2188 2188 else:
2189 2189 return
2190 2190
2191 2191 copies = None
2192 2192 if opts.get('copies') and rev:
2193 2193 copies = []
2194 2194 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2195 2195 for fn in ctx.files():
2196 2196 rename = getrenamed(fn, rev)
2197 2197 if rename:
2198 2198 copies.append((fn, rename[0]))
2199 2199
2200 2200 displayer.show(ctx, copies=copies)
2201 2201
2202 2202 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2203 2203 if count == limit:
2204 2204 break
2205 2205 if displayer.flush(ctx.rev()):
2206 2206 count += 1
2207 2207 displayer.close()
2208 2208
2209 2209 def manifest(ui, repo, node=None, rev=None):
2210 2210 """output the current or given revision of the project manifest
2211 2211
2212 2212 Print a list of version controlled files for the given revision.
2213 2213 If no revision is given, the first parent of the working directory
2214 2214 is used, or the null revision if no revision is checked out.
2215 2215
2216 2216 With -v, print file permissions, symlink and executable bits.
2217 2217 With --debug, print file revision hashes.
2218 2218 """
2219 2219
2220 2220 if rev and node:
2221 2221 raise util.Abort(_("please specify just one revision"))
2222 2222
2223 2223 if not node:
2224 2224 node = rev
2225 2225
2226 2226 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
2227 2227 ctx = repo[node]
2228 2228 for f in ctx:
2229 2229 if ui.debugflag:
2230 2230 ui.write("%40s " % hex(ctx.manifest()[f]))
2231 2231 if ui.verbose:
2232 2232 ui.write(decor[ctx.flags(f)])
2233 2233 ui.write("%s\n" % f)
2234 2234
2235 2235 def merge(ui, repo, node=None, **opts):
2236 2236 """merge working directory with another revision
2237 2237
2238 2238 The current working directory is updated with all changes made in
2239 2239 the requested revision since the last common predecessor revision.
2240 2240
2241 2241 Files that changed between either parent are marked as changed for
2242 2242 the next commit and a commit must be performed before any further
2243 2243 updates to the repository are allowed. The next commit will have
2244 2244 two parents.
2245 2245
2246 2246 If no revision is specified, the working directory's parent is a
2247 2247 head revision, and the current branch contains exactly one other
2248 2248 head, the other head is merged with by default. Otherwise, an
2249 2249 explicit revision with which to merge with must be provided.
2250 2250 """
2251 2251
2252 2252 if opts.get('rev') and node:
2253 2253 raise util.Abort(_("please specify just one revision"))
2254 2254 if not node:
2255 2255 node = opts.get('rev')
2256 2256
2257 2257 if not node:
2258 2258 branch = repo.changectx(None).branch()
2259 2259 bheads = repo.branchheads(branch)
2260 2260 if len(bheads) > 2:
2261 2261 ui.warn(_("abort: branch '%s' has %d heads - "
2262 2262 "please merge with an explicit rev\n")
2263 2263 % (branch, len(bheads)))
2264 2264 ui.status(_("(run 'hg heads .' to see heads)\n"))
2265 2265 return False
2266 2266
2267 2267 parent = repo.dirstate.parents()[0]
2268 2268 if len(bheads) == 1:
2269 2269 if len(repo.heads()) > 1:
2270 2270 ui.warn(_("abort: branch '%s' has one head - "
2271 2271 "please merge with an explicit rev\n" % branch))
2272 2272 ui.status(_("(run 'hg heads' to see all heads)\n"))
2273 2273 return False
2274 2274 msg = _('there is nothing to merge')
2275 2275 if parent != repo.lookup(repo[None].branch()):
2276 2276 msg = _('%s - use "hg update" instead') % msg
2277 2277 raise util.Abort(msg)
2278 2278
2279 2279 if parent not in bheads:
2280 2280 raise util.Abort(_('working dir not at a head rev - '
2281 2281 'use "hg update" or merge with an explicit rev'))
2282 2282 node = parent == bheads[0] and bheads[-1] or bheads[0]
2283 2283
2284 2284 if opts.get('preview'):
2285 2285 # find nodes that are ancestors of p2 but not of p1
2286 2286 p1 = repo.lookup('.')
2287 2287 p2 = repo.lookup(node)
2288 2288 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
2289 2289
2290 2290 displayer = cmdutil.show_changeset(ui, repo, opts)
2291 2291 for node in nodes:
2292 2292 displayer.show(repo[node])
2293 2293 displayer.close()
2294 2294 return 0
2295 2295
2296 2296 return hg.merge(repo, node, force=opts.get('force'))
2297 2297
2298 2298 def outgoing(ui, repo, dest=None, **opts):
2299 2299 """show changesets not found in the destination
2300 2300
2301 2301 Show changesets not found in the specified destination repository
2302 2302 or the default push location. These are the changesets that would
2303 2303 be pushed if a push was requested.
2304 2304
2305 2305 See pull for details of valid destination formats.
2306 2306 """
2307 2307 limit = cmdutil.loglimit(opts)
2308 2308 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2309 2309 dest, branches = hg.parseurl(dest, opts.get('branch'))
2310 2310 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2311 2311 if revs:
2312 2312 revs = [repo.lookup(rev) for rev in revs]
2313 2313
2314 2314 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
2315 2315 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
2316 2316 o = repo.findoutgoing(other, force=opts.get('force'))
2317 2317 if not o:
2318 2318 ui.status(_("no changes found\n"))
2319 2319 return 1
2320 2320 o = repo.changelog.nodesbetween(o, revs)[0]
2321 2321 if opts.get('newest_first'):
2322 2322 o.reverse()
2323 2323 displayer = cmdutil.show_changeset(ui, repo, opts)
2324 2324 count = 0
2325 2325 for n in o:
2326 2326 if limit is not None and count >= limit:
2327 2327 break
2328 2328 parents = [p for p in repo.changelog.parents(n) if p != nullid]
2329 2329 if opts.get('no_merges') and len(parents) == 2:
2330 2330 continue
2331 2331 count += 1
2332 2332 displayer.show(repo[n])
2333 2333 displayer.close()
2334 2334
2335 2335 def parents(ui, repo, file_=None, **opts):
2336 2336 """show the parents of the working directory or revision
2337 2337
2338 2338 Print the working directory's parent revisions. If a revision is
2339 2339 given via -r/--rev, the parent of that revision will be printed.
2340 2340 If a file argument is given, the revision in which the file was
2341 2341 last changed (before the working directory revision or the
2342 2342 argument to --rev if given) is printed.
2343 2343 """
2344 2344 rev = opts.get('rev')
2345 2345 if rev:
2346 2346 ctx = repo[rev]
2347 2347 else:
2348 2348 ctx = repo[None]
2349 2349
2350 2350 if file_:
2351 2351 m = cmdutil.match(repo, (file_,), opts)
2352 2352 if m.anypats() or len(m.files()) != 1:
2353 2353 raise util.Abort(_('can only specify an explicit filename'))
2354 2354 file_ = m.files()[0]
2355 2355 filenodes = []
2356 2356 for cp in ctx.parents():
2357 2357 if not cp:
2358 2358 continue
2359 2359 try:
2360 2360 filenodes.append(cp.filenode(file_))
2361 2361 except error.LookupError:
2362 2362 pass
2363 2363 if not filenodes:
2364 2364 raise util.Abort(_("'%s' not found in manifest!") % file_)
2365 2365 fl = repo.file(file_)
2366 2366 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
2367 2367 else:
2368 2368 p = [cp.node() for cp in ctx.parents()]
2369 2369
2370 2370 displayer = cmdutil.show_changeset(ui, repo, opts)
2371 2371 for n in p:
2372 2372 if n != nullid:
2373 2373 displayer.show(repo[n])
2374 2374 displayer.close()
2375 2375
2376 2376 def paths(ui, repo, search=None):
2377 2377 """show aliases for remote repositories
2378 2378
2379 2379 Show definition of symbolic path name NAME. If no name is given,
2380 2380 show definition of all available names.
2381 2381
2382 2382 Path names are defined in the [paths] section of /etc/mercurial/hgrc
2383 2383 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
2384 2384
2385 2385 The names 'default' and 'default-push' have a special meaning.
2386 2386 They are the locations used when pulling and pushing respectively
2387 2387 unless a location is specified. When cloning a repository, the
2388 2388 clone source is written as 'default' in .hg/hgrc.
2389 2389
2390 See 'hg help urls' for more information.
2390 See :hg:`help urls` for more information.
2391 2391 """
2392 2392 if search:
2393 2393 for name, path in ui.configitems("paths"):
2394 2394 if name == search:
2395 2395 ui.write("%s\n" % url.hidepassword(path))
2396 2396 return
2397 2397 ui.warn(_("not found!\n"))
2398 2398 return 1
2399 2399 else:
2400 2400 for name, path in ui.configitems("paths"):
2401 2401 ui.write("%s = %s\n" % (name, url.hidepassword(path)))
2402 2402
2403 2403 def postincoming(ui, repo, modheads, optupdate, checkout):
2404 2404 if modheads == 0:
2405 2405 return
2406 2406 if optupdate:
2407 2407 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
2408 2408 return hg.update(repo, checkout)
2409 2409 else:
2410 2410 ui.status(_("not updating, since new heads added\n"))
2411 2411 if modheads > 1:
2412 2412 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2413 2413 else:
2414 2414 ui.status(_("(run 'hg update' to get a working copy)\n"))
2415 2415
2416 2416 def pull(ui, repo, source="default", **opts):
2417 2417 """pull changes from the specified source
2418 2418
2419 2419 Pull changes from a remote repository to a local one.
2420 2420
2421 2421 This finds all changes from the repository at the specified path
2422 2422 or URL and adds them to a local repository (the current one unless
2423 2423 -R is specified). By default, this does not update the copy of the
2424 2424 project in the working directory.
2425 2425
2426 2426 Use hg incoming if you want to see what would have been added by a
2427 2427 pull at the time you issued this command. If you then decide to
2428 2428 added those changes to the repository, you should use pull -r X
2429 2429 where X is the last changeset listed by hg incoming.
2430 2430
2431 2431 If SOURCE is omitted, the 'default' path will be used.
2432 See 'hg help urls' for more information.
2432 See :hg:`help urls` for more information.
2433 2433 """
2434 2434 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2435 2435 other = hg.repository(cmdutil.remoteui(repo, opts), source)
2436 2436 ui.status(_('pulling from %s\n') % url.hidepassword(source))
2437 2437 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2438 2438 if revs:
2439 2439 try:
2440 2440 revs = [other.lookup(rev) for rev in revs]
2441 2441 except error.CapabilityError:
2442 2442 err = _("Other repository doesn't support revision lookup, "
2443 2443 "so a rev cannot be specified.")
2444 2444 raise util.Abort(err)
2445 2445
2446 2446 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
2447 2447 if checkout:
2448 2448 checkout = str(repo.changelog.rev(other.lookup(checkout)))
2449 2449 return postincoming(ui, repo, modheads, opts.get('update'), checkout)
2450 2450
2451 2451 def push(ui, repo, dest=None, **opts):
2452 2452 """push changes to the specified destination
2453 2453
2454 2454 Push changes from the local repository to the specified destination.
2455 2455
2456 2456 This is the symmetrical operation for pull. It moves changes from
2457 2457 the current repository to a different one. If the destination is
2458 2458 local this is identical to a pull in that directory from the
2459 2459 current one.
2460 2460
2461 2461 By default, push will refuse to run if it detects the result would
2462 2462 increase the number of remote heads. This generally indicates the
2463 2463 user forgot to pull and merge before pushing.
2464 2464
2465 2465 If -r/--rev is used, the named revision and all its ancestors will
2466 2466 be pushed to the remote repository.
2467 2467
2468 Please see 'hg help urls' for important details about ``ssh://``
2468 Please see :hg:`help urls` for important details about ``ssh://``
2469 2469 URLs. If DESTINATION is omitted, a default path will be used.
2470 2470 """
2471 2471 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2472 2472 dest, branches = hg.parseurl(dest, opts.get('branch'))
2473 2473 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2474 2474 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
2475 2475 ui.status(_('pushing to %s\n') % url.hidepassword(dest))
2476 2476 if revs:
2477 2477 revs = [repo.lookup(rev) for rev in revs]
2478 2478
2479 2479 # push subrepos depth-first for coherent ordering
2480 2480 c = repo['']
2481 2481 subs = c.substate # only repos that are committed
2482 2482 for s in sorted(subs):
2483 2483 c.sub(s).push(opts.get('force'))
2484 2484
2485 2485 r = repo.push(other, opts.get('force'), revs=revs)
2486 2486 return r == 0
2487 2487
2488 2488 def recover(ui, repo):
2489 2489 """roll back an interrupted transaction
2490 2490
2491 2491 Recover from an interrupted commit or pull.
2492 2492
2493 2493 This command tries to fix the repository status after an
2494 2494 interrupted operation. It should only be necessary when Mercurial
2495 2495 suggests it.
2496 2496 """
2497 2497 if repo.recover():
2498 2498 return hg.verify(repo)
2499 2499 return 1
2500 2500
2501 2501 def remove(ui, repo, *pats, **opts):
2502 2502 """remove the specified files on the next commit
2503 2503
2504 2504 Schedule the indicated files for removal from the repository.
2505 2505
2506 2506 This only removes files from the current branch, not from the
2507 2507 entire project history. -A/--after can be used to remove only
2508 2508 files that have already been deleted, -f/--force can be used to
2509 2509 force deletion, and -Af can be used to remove files from the next
2510 2510 revision without deleting them from the working directory.
2511 2511
2512 2512 The following table details the behavior of remove for different
2513 2513 file states (columns) and option combinations (rows). The file
2514 2514 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
2515 2515 reported by hg status). The actions are Warn, Remove (from branch)
2516 2516 and Delete (from disk)::
2517 2517
2518 2518 A C M !
2519 2519 none W RD W R
2520 2520 -f R RD RD R
2521 2521 -A W W W R
2522 2522 -Af R R R R
2523 2523
2524 2524 This command schedules the files to be removed at the next commit.
2525 2525 To undo a remove before that, see hg revert.
2526 2526 """
2527 2527
2528 2528 after, force = opts.get('after'), opts.get('force')
2529 2529 if not pats and not after:
2530 2530 raise util.Abort(_('no files specified'))
2531 2531
2532 2532 m = cmdutil.match(repo, pats, opts)
2533 2533 s = repo.status(match=m, clean=True)
2534 2534 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2535 2535
2536 2536 for f in m.files():
2537 2537 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2538 2538 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
2539 2539
2540 2540 def warn(files, reason):
2541 2541 for f in files:
2542 2542 ui.warn(_('not removing %s: file %s (use -f to force removal)\n')
2543 2543 % (m.rel(f), reason))
2544 2544
2545 2545 if force:
2546 2546 remove, forget = modified + deleted + clean, added
2547 2547 elif after:
2548 2548 remove, forget = deleted, []
2549 2549 warn(modified + added + clean, _('still exists'))
2550 2550 else:
2551 2551 remove, forget = deleted + clean, []
2552 2552 warn(modified, _('is modified'))
2553 2553 warn(added, _('has been marked for add'))
2554 2554
2555 2555 for f in sorted(remove + forget):
2556 2556 if ui.verbose or not m.exact(f):
2557 2557 ui.status(_('removing %s\n') % m.rel(f))
2558 2558
2559 2559 repo.forget(forget)
2560 2560 repo.remove(remove, unlink=not after)
2561 2561
2562 2562 def rename(ui, repo, *pats, **opts):
2563 2563 """rename files; equivalent of copy + remove
2564 2564
2565 2565 Mark dest as copies of sources; mark sources for deletion. If dest
2566 2566 is a directory, copies are put in that directory. If dest is a
2567 2567 file, there can only be one source.
2568 2568
2569 2569 By default, this command copies the contents of files as they
2570 2570 exist in the working directory. If invoked with -A/--after, the
2571 2571 operation is recorded, but no copying is performed.
2572 2572
2573 2573 This command takes effect at the next commit. To undo a rename
2574 2574 before that, see hg revert.
2575 2575 """
2576 2576 wlock = repo.wlock(False)
2577 2577 try:
2578 2578 return cmdutil.copy(ui, repo, pats, opts, rename=True)
2579 2579 finally:
2580 2580 wlock.release()
2581 2581
2582 2582 def resolve(ui, repo, *pats, **opts):
2583 2583 """various operations to help finish a merge
2584 2584
2585 2585 This command includes several actions that are often useful while
2586 2586 performing a merge, after running ``merge`` but before running
2587 2587 ``commit``. (It is only meaningful if your working directory has
2588 2588 two parents.) It is most relevant for merges with unresolved
2589 2589 conflicts, which are typically a result of non-interactive merging with
2590 2590 ``internal:merge`` or a command-line merge tool like ``diff3``.
2591 2591
2592 2592 The available actions are:
2593 2593
2594 2594 1) list files that were merged with conflicts (U, for unresolved)
2595 2595 and without conflicts (R, for resolved): ``hg resolve -l``
2596 2596 (this is like ``status`` for merges)
2597 2597 2) record that you have resolved conflicts in certain files:
2598 2598 ``hg resolve -m [file ...]`` (default: mark all unresolved files)
2599 2599 3) forget that you have resolved conflicts in certain files:
2600 2600 ``hg resolve -u [file ...]`` (default: unmark all resolved files)
2601 2601 4) discard your current attempt(s) at resolving conflicts and
2602 2602 restart the merge from scratch: ``hg resolve file...``
2603 2603 (or ``-a`` for all unresolved files)
2604 2604
2605 2605 Note that Mercurial will not let you commit files with unresolved merge
2606 2606 conflicts. You must use ``hg resolve -m ...`` before you can commit
2607 2607 after a conflicting merge.
2608 2608 """
2609 2609
2610 2610 all, mark, unmark, show, nostatus = \
2611 2611 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
2612 2612
2613 2613 if (show and (mark or unmark)) or (mark and unmark):
2614 2614 raise util.Abort(_("too many options specified"))
2615 2615 if pats and all:
2616 2616 raise util.Abort(_("can't specify --all and patterns"))
2617 2617 if not (all or pats or show or mark or unmark):
2618 2618 raise util.Abort(_('no files or directories specified; '
2619 2619 'use --all to remerge all files'))
2620 2620
2621 2621 ms = mergemod.mergestate(repo)
2622 2622 m = cmdutil.match(repo, pats, opts)
2623 2623
2624 2624 for f in ms:
2625 2625 if m(f):
2626 2626 if show:
2627 2627 if nostatus:
2628 2628 ui.write("%s\n" % f)
2629 2629 else:
2630 2630 ui.write("%s %s\n" % (ms[f].upper(), f),
2631 2631 label='resolve.' +
2632 2632 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
2633 2633 elif mark:
2634 2634 ms.mark(f, "r")
2635 2635 elif unmark:
2636 2636 ms.mark(f, "u")
2637 2637 else:
2638 2638 wctx = repo[None]
2639 2639 mctx = wctx.parents()[-1]
2640 2640
2641 2641 # backup pre-resolve (merge uses .orig for its own purposes)
2642 2642 a = repo.wjoin(f)
2643 2643 util.copyfile(a, a + ".resolve")
2644 2644
2645 2645 # resolve file
2646 2646 ms.resolve(f, wctx, mctx)
2647 2647
2648 2648 # replace filemerge's .orig file with our resolve file
2649 2649 util.rename(a + ".resolve", a + ".orig")
2650 2650
2651 2651 def revert(ui, repo, *pats, **opts):
2652 2652 """restore individual files or directories to an earlier state
2653 2653
2654 2654 (Use update -r to check out earlier revisions, revert does not
2655 2655 change the working directory parents.)
2656 2656
2657 2657 With no revision specified, revert the named files or directories
2658 2658 to the contents they had in the parent of the working directory.
2659 2659 This restores the contents of the affected files to an unmodified
2660 2660 state and unschedules adds, removes, copies, and renames. If the
2661 2661 working directory has two parents, you must explicitly specify a
2662 2662 revision.
2663 2663
2664 2664 Using the -r/--rev option, revert the given files or directories
2665 2665 to their contents as of a specific revision. This can be helpful
2666 to "roll back" some or all of an earlier change. See 'hg help
2667 dates' for a list of formats valid for -d/--date.
2666 to "roll back" some or all of an earlier change. See :hg:`help
2667 dates` for a list of formats valid for -d/--date.
2668 2668
2669 2669 Revert modifies the working directory. It does not commit any
2670 2670 changes, or change the parent of the working directory. If you
2671 2671 revert to a revision other than the parent of the working
2672 2672 directory, the reverted files will thus appear modified
2673 2673 afterwards.
2674 2674
2675 2675 If a file has been deleted, it is restored. If the executable mode
2676 2676 of a file was changed, it is reset.
2677 2677
2678 2678 If names are given, all files matching the names are reverted.
2679 2679 If no arguments are given, no files are reverted.
2680 2680
2681 2681 Modified files are saved with a .orig suffix before reverting.
2682 2682 To disable these backups, use --no-backup.
2683 2683 """
2684 2684
2685 2685 if opts["date"]:
2686 2686 if opts["rev"]:
2687 2687 raise util.Abort(_("you can't specify a revision and a date"))
2688 2688 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
2689 2689
2690 2690 if not pats and not opts.get('all'):
2691 2691 raise util.Abort(_('no files or directories specified; '
2692 2692 'use --all to revert the whole repo'))
2693 2693
2694 2694 parent, p2 = repo.dirstate.parents()
2695 2695 if not opts.get('rev') and p2 != nullid:
2696 2696 raise util.Abort(_('uncommitted merge - please provide a '
2697 2697 'specific revision'))
2698 2698 ctx = repo[opts.get('rev')]
2699 2699 node = ctx.node()
2700 2700 mf = ctx.manifest()
2701 2701 if node == parent:
2702 2702 pmf = mf
2703 2703 else:
2704 2704 pmf = None
2705 2705
2706 2706 # need all matching names in dirstate and manifest of target rev,
2707 2707 # so have to walk both. do not print errors if files exist in one
2708 2708 # but not other.
2709 2709
2710 2710 names = {}
2711 2711
2712 2712 wlock = repo.wlock()
2713 2713 try:
2714 2714 # walk dirstate.
2715 2715
2716 2716 m = cmdutil.match(repo, pats, opts)
2717 2717 m.bad = lambda x, y: False
2718 2718 for abs in repo.walk(m):
2719 2719 names[abs] = m.rel(abs), m.exact(abs)
2720 2720
2721 2721 # walk target manifest.
2722 2722
2723 2723 def badfn(path, msg):
2724 2724 if path in names:
2725 2725 return
2726 2726 path_ = path + '/'
2727 2727 for f in names:
2728 2728 if f.startswith(path_):
2729 2729 return
2730 2730 ui.warn("%s: %s\n" % (m.rel(path), msg))
2731 2731
2732 2732 m = cmdutil.match(repo, pats, opts)
2733 2733 m.bad = badfn
2734 2734 for abs in repo[node].walk(m):
2735 2735 if abs not in names:
2736 2736 names[abs] = m.rel(abs), m.exact(abs)
2737 2737
2738 2738 m = cmdutil.matchfiles(repo, names)
2739 2739 changes = repo.status(match=m)[:4]
2740 2740 modified, added, removed, deleted = map(set, changes)
2741 2741
2742 2742 # if f is a rename, also revert the source
2743 2743 cwd = repo.getcwd()
2744 2744 for f in added:
2745 2745 src = repo.dirstate.copied(f)
2746 2746 if src and src not in names and repo.dirstate[src] == 'r':
2747 2747 removed.add(src)
2748 2748 names[src] = (repo.pathto(src, cwd), True)
2749 2749
2750 2750 def removeforget(abs):
2751 2751 if repo.dirstate[abs] == 'a':
2752 2752 return _('forgetting %s\n')
2753 2753 return _('removing %s\n')
2754 2754
2755 2755 revert = ([], _('reverting %s\n'))
2756 2756 add = ([], _('adding %s\n'))
2757 2757 remove = ([], removeforget)
2758 2758 undelete = ([], _('undeleting %s\n'))
2759 2759
2760 2760 disptable = (
2761 2761 # dispatch table:
2762 2762 # file state
2763 2763 # action if in target manifest
2764 2764 # action if not in target manifest
2765 2765 # make backup if in target manifest
2766 2766 # make backup if not in target manifest
2767 2767 (modified, revert, remove, True, True),
2768 2768 (added, revert, remove, True, False),
2769 2769 (removed, undelete, None, False, False),
2770 2770 (deleted, revert, remove, False, False),
2771 2771 )
2772 2772
2773 2773 for abs, (rel, exact) in sorted(names.items()):
2774 2774 mfentry = mf.get(abs)
2775 2775 target = repo.wjoin(abs)
2776 2776 def handle(xlist, dobackup):
2777 2777 xlist[0].append(abs)
2778 2778 if dobackup and not opts.get('no_backup') and util.lexists(target):
2779 2779 bakname = "%s.orig" % rel
2780 2780 ui.note(_('saving current version of %s as %s\n') %
2781 2781 (rel, bakname))
2782 2782 if not opts.get('dry_run'):
2783 2783 util.copyfile(target, bakname)
2784 2784 if ui.verbose or not exact:
2785 2785 msg = xlist[1]
2786 2786 if not isinstance(msg, basestring):
2787 2787 msg = msg(abs)
2788 2788 ui.status(msg % rel)
2789 2789 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2790 2790 if abs not in table:
2791 2791 continue
2792 2792 # file has changed in dirstate
2793 2793 if mfentry:
2794 2794 handle(hitlist, backuphit)
2795 2795 elif misslist is not None:
2796 2796 handle(misslist, backupmiss)
2797 2797 break
2798 2798 else:
2799 2799 if abs not in repo.dirstate:
2800 2800 if mfentry:
2801 2801 handle(add, True)
2802 2802 elif exact:
2803 2803 ui.warn(_('file not managed: %s\n') % rel)
2804 2804 continue
2805 2805 # file has not changed in dirstate
2806 2806 if node == parent:
2807 2807 if exact:
2808 2808 ui.warn(_('no changes needed to %s\n') % rel)
2809 2809 continue
2810 2810 if pmf is None:
2811 2811 # only need parent manifest in this unlikely case,
2812 2812 # so do not read by default
2813 2813 pmf = repo[parent].manifest()
2814 2814 if abs in pmf:
2815 2815 if mfentry:
2816 2816 # if version of file is same in parent and target
2817 2817 # manifests, do nothing
2818 2818 if (pmf[abs] != mfentry or
2819 2819 pmf.flags(abs) != mf.flags(abs)):
2820 2820 handle(revert, False)
2821 2821 else:
2822 2822 handle(remove, False)
2823 2823
2824 2824 if not opts.get('dry_run'):
2825 2825 def checkout(f):
2826 2826 fc = ctx[f]
2827 2827 repo.wwrite(f, fc.data(), fc.flags())
2828 2828
2829 2829 audit_path = util.path_auditor(repo.root)
2830 2830 for f in remove[0]:
2831 2831 if repo.dirstate[f] == 'a':
2832 2832 repo.dirstate.forget(f)
2833 2833 continue
2834 2834 audit_path(f)
2835 2835 try:
2836 2836 util.unlink(repo.wjoin(f))
2837 2837 except OSError:
2838 2838 pass
2839 2839 repo.dirstate.remove(f)
2840 2840
2841 2841 normal = None
2842 2842 if node == parent:
2843 2843 # We're reverting to our parent. If possible, we'd like status
2844 2844 # to report the file as clean. We have to use normallookup for
2845 2845 # merges to avoid losing information about merged/dirty files.
2846 2846 if p2 != nullid:
2847 2847 normal = repo.dirstate.normallookup
2848 2848 else:
2849 2849 normal = repo.dirstate.normal
2850 2850 for f in revert[0]:
2851 2851 checkout(f)
2852 2852 if normal:
2853 2853 normal(f)
2854 2854
2855 2855 for f in add[0]:
2856 2856 checkout(f)
2857 2857 repo.dirstate.add(f)
2858 2858
2859 2859 normal = repo.dirstate.normallookup
2860 2860 if node == parent and p2 == nullid:
2861 2861 normal = repo.dirstate.normal
2862 2862 for f in undelete[0]:
2863 2863 checkout(f)
2864 2864 normal(f)
2865 2865
2866 2866 finally:
2867 2867 wlock.release()
2868 2868
2869 2869 def rollback(ui, repo, **opts):
2870 2870 """roll back the last transaction (dangerous)
2871 2871
2872 2872 This command should be used with care. There is only one level of
2873 2873 rollback, and there is no way to undo a rollback. It will also
2874 2874 restore the dirstate at the time of the last transaction, losing
2875 2875 any dirstate changes since that time. This command does not alter
2876 2876 the working directory.
2877 2877
2878 2878 Transactions are used to encapsulate the effects of all commands
2879 2879 that create new changesets or propagate existing changesets into a
2880 2880 repository. For example, the following commands are transactional,
2881 2881 and their effects can be rolled back:
2882 2882
2883 2883 - commit
2884 2884 - import
2885 2885 - pull
2886 2886 - push (with this repository as the destination)
2887 2887 - unbundle
2888 2888
2889 2889 This command is not intended for use on public repositories. Once
2890 2890 changes are visible for pull by other users, rolling a transaction
2891 2891 back locally is ineffective (someone else may already have pulled
2892 2892 the changes). Furthermore, a race is possible with readers of the
2893 2893 repository; for example an in-progress pull from the repository
2894 2894 may fail if a rollback is performed.
2895 2895 """
2896 2896 repo.rollback(opts.get('dry_run'))
2897 2897
2898 2898 def root(ui, repo):
2899 2899 """print the root (top) of the current working directory
2900 2900
2901 2901 Print the root directory of the current repository.
2902 2902 """
2903 2903 ui.write(repo.root + "\n")
2904 2904
2905 2905 def serve(ui, repo, **opts):
2906 2906 """start stand-alone webserver
2907 2907
2908 2908 Start a local HTTP repository browser and pull server.
2909 2909
2910 2910 By default, the server logs accesses to stdout and errors to
2911 2911 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
2912 2912 files.
2913 2913
2914 2914 To have the server choose a free port number to listen on, specify
2915 2915 a port number of 0; in this case, the server will print the port
2916 2916 number it uses.
2917 2917 """
2918 2918
2919 2919 if opts["stdio"]:
2920 2920 if repo is None:
2921 2921 raise error.RepoError(_("There is no Mercurial repository here"
2922 2922 " (.hg not found)"))
2923 2923 s = sshserver.sshserver(ui, repo)
2924 2924 s.serve_forever()
2925 2925
2926 2926 # this way we can check if something was given in the command-line
2927 2927 if opts.get('port'):
2928 2928 opts['port'] = int(opts.get('port'))
2929 2929
2930 2930 baseui = repo and repo.baseui or ui
2931 2931 optlist = ("name templates style address port prefix ipv6"
2932 2932 " accesslog errorlog certificate encoding")
2933 2933 for o in optlist.split():
2934 2934 val = opts.get(o, '')
2935 2935 if val in (None, ''): # should check against default options instead
2936 2936 continue
2937 2937 baseui.setconfig("web", o, val)
2938 2938 if repo and repo.ui != baseui:
2939 2939 repo.ui.setconfig("web", o, val)
2940 2940
2941 2941 if opts.get('webdir_conf'):
2942 2942 app = hgwebdir_mod.hgwebdir(opts['webdir_conf'], ui)
2943 2943 elif repo is not None:
2944 2944 app = hgweb_mod.hgweb(hg.repository(repo.ui, repo.root))
2945 2945 else:
2946 2946 raise error.RepoError(_("There is no Mercurial repository"
2947 2947 " here (.hg not found)"))
2948 2948
2949 2949 class service(object):
2950 2950 def init(self):
2951 2951 util.set_signal_handler()
2952 2952 self.httpd = server.create_server(ui, app)
2953 2953
2954 2954 if opts['port'] and not ui.verbose:
2955 2955 return
2956 2956
2957 2957 if self.httpd.prefix:
2958 2958 prefix = self.httpd.prefix.strip('/') + '/'
2959 2959 else:
2960 2960 prefix = ''
2961 2961
2962 2962 port = ':%d' % self.httpd.port
2963 2963 if port == ':80':
2964 2964 port = ''
2965 2965
2966 2966 bindaddr = self.httpd.addr
2967 2967 if bindaddr == '0.0.0.0':
2968 2968 bindaddr = '*'
2969 2969 elif ':' in bindaddr: # IPv6
2970 2970 bindaddr = '[%s]' % bindaddr
2971 2971
2972 2972 fqaddr = self.httpd.fqaddr
2973 2973 if ':' in fqaddr:
2974 2974 fqaddr = '[%s]' % fqaddr
2975 2975 if opts['port']:
2976 2976 write = ui.status
2977 2977 else:
2978 2978 write = ui.write
2979 2979 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
2980 2980 (fqaddr, port, prefix, bindaddr, self.httpd.port))
2981 2981
2982 2982 def run(self):
2983 2983 self.httpd.serve_forever()
2984 2984
2985 2985 service = service()
2986 2986
2987 2987 cmdutil.service(opts, initfn=service.init, runfn=service.run)
2988 2988
2989 2989 def status(ui, repo, *pats, **opts):
2990 2990 """show changed files in the working directory
2991 2991
2992 2992 Show status of files in the repository. If names are given, only
2993 2993 files that match are shown. Files that are clean or ignored or
2994 2994 the source of a copy/move operation, are not listed unless
2995 2995 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
2996 2996 Unless options described with "show only ..." are given, the
2997 2997 options -mardu are used.
2998 2998
2999 2999 Option -q/--quiet hides untracked (unknown and ignored) files
3000 3000 unless explicitly requested with -u/--unknown or -i/--ignored.
3001 3001
3002 3002 NOTE: status may appear to disagree with diff if permissions have
3003 3003 changed or a merge has occurred. The standard diff format does not
3004 3004 report permission changes and diff only reports changes relative
3005 3005 to one merge parent.
3006 3006
3007 3007 If one revision is given, it is used as the base revision.
3008 3008 If two revisions are given, the differences between them are
3009 3009 shown. The --change option can also be used as a shortcut to list
3010 3010 the changed files of a revision from its first parent.
3011 3011
3012 3012 The codes used to show the status of files are::
3013 3013
3014 3014 M = modified
3015 3015 A = added
3016 3016 R = removed
3017 3017 C = clean
3018 3018 ! = missing (deleted by non-hg command, but still tracked)
3019 3019 ? = not tracked
3020 3020 I = ignored
3021 3021 = origin of the previous file listed as A (added)
3022 3022 """
3023 3023
3024 3024 revs = opts.get('rev')
3025 3025 change = opts.get('change')
3026 3026
3027 3027 if revs and change:
3028 3028 msg = _('cannot specify --rev and --change at the same time')
3029 3029 raise util.Abort(msg)
3030 3030 elif change:
3031 3031 node2 = repo.lookup(change)
3032 3032 node1 = repo[node2].parents()[0].node()
3033 3033 else:
3034 3034 node1, node2 = cmdutil.revpair(repo, revs)
3035 3035
3036 3036 cwd = (pats and repo.getcwd()) or ''
3037 3037 end = opts.get('print0') and '\0' or '\n'
3038 3038 copy = {}
3039 3039 states = 'modified added removed deleted unknown ignored clean'.split()
3040 3040 show = [k for k in states if opts.get(k)]
3041 3041 if opts.get('all'):
3042 3042 show += ui.quiet and (states[:4] + ['clean']) or states
3043 3043 if not show:
3044 3044 show = ui.quiet and states[:4] or states[:5]
3045 3045
3046 3046 stat = repo.status(node1, node2, cmdutil.match(repo, pats, opts),
3047 3047 'ignored' in show, 'clean' in show, 'unknown' in show)
3048 3048 changestates = zip(states, 'MAR!?IC', stat)
3049 3049
3050 3050 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
3051 3051 ctxn = repo[nullid]
3052 3052 ctx1 = repo[node1]
3053 3053 ctx2 = repo[node2]
3054 3054 added = stat[1]
3055 3055 if node2 is None:
3056 3056 added = stat[0] + stat[1] # merged?
3057 3057
3058 3058 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
3059 3059 if k in added:
3060 3060 copy[k] = v
3061 3061 elif v in added:
3062 3062 copy[v] = k
3063 3063
3064 3064 for state, char, files in changestates:
3065 3065 if state in show:
3066 3066 format = "%s %%s%s" % (char, end)
3067 3067 if opts.get('no_status'):
3068 3068 format = "%%s%s" % end
3069 3069
3070 3070 for f in files:
3071 3071 ui.write(format % repo.pathto(f, cwd),
3072 3072 label='status.' + state)
3073 3073 if f in copy:
3074 3074 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
3075 3075 label='status.copied')
3076 3076
3077 3077 def summary(ui, repo, **opts):
3078 3078 """summarize working directory state
3079 3079
3080 3080 This generates a brief summary of the working directory state,
3081 3081 including parents, branch, commit status, and available updates.
3082 3082
3083 3083 With the --remote option, this will check the default paths for
3084 3084 incoming and outgoing changes. This can be time-consuming.
3085 3085 """
3086 3086
3087 3087 ctx = repo[None]
3088 3088 parents = ctx.parents()
3089 3089 pnode = parents[0].node()
3090 3090
3091 3091 for p in parents:
3092 3092 # label with log.changeset (instead of log.parent) since this
3093 3093 # shows a working directory parent *changeset*:
3094 3094 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
3095 3095 label='log.changeset')
3096 3096 ui.write(' '.join(p.tags()), label='log.tag')
3097 3097 if p.rev() == -1:
3098 3098 if not len(repo):
3099 3099 ui.write(_(' (empty repository)'))
3100 3100 else:
3101 3101 ui.write(_(' (no revision checked out)'))
3102 3102 ui.write('\n')
3103 3103 if p.description():
3104 3104 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
3105 3105 label='log.summary')
3106 3106
3107 3107 branch = ctx.branch()
3108 3108 bheads = repo.branchheads(branch)
3109 3109 m = _('branch: %s\n') % branch
3110 3110 if branch != 'default':
3111 3111 ui.write(m, label='log.branch')
3112 3112 else:
3113 3113 ui.status(m, label='log.branch')
3114 3114
3115 3115 st = list(repo.status(unknown=True))[:6]
3116 3116 ms = mergemod.mergestate(repo)
3117 3117 st.append([f for f in ms if ms[f] == 'u'])
3118 3118 labels = [ui.label(_('%d modified'), 'status.modified'),
3119 3119 ui.label(_('%d added'), 'status.added'),
3120 3120 ui.label(_('%d removed'), 'status.removed'),
3121 3121 ui.label(_('%d deleted'), 'status.deleted'),
3122 3122 ui.label(_('%d unknown'), 'status.unknown'),
3123 3123 ui.label(_('%d ignored'), 'status.ignored'),
3124 3124 ui.label(_('%d unresolved'), 'resolve.unresolved')]
3125 3125 t = []
3126 3126 for s, l in zip(st, labels):
3127 3127 if s:
3128 3128 t.append(l % len(s))
3129 3129
3130 3130 t = ', '.join(t)
3131 3131 cleanworkdir = False
3132 3132
3133 3133 if len(parents) > 1:
3134 3134 t += _(' (merge)')
3135 3135 elif branch != parents[0].branch():
3136 3136 t += _(' (new branch)')
3137 3137 elif (not st[0] and not st[1] and not st[2]):
3138 3138 t += _(' (clean)')
3139 3139 cleanworkdir = True
3140 3140 elif pnode not in bheads:
3141 3141 t += _(' (new branch head)')
3142 3142
3143 3143 if cleanworkdir:
3144 3144 ui.status(_('commit: %s\n') % t.strip())
3145 3145 else:
3146 3146 ui.write(_('commit: %s\n') % t.strip())
3147 3147
3148 3148 # all ancestors of branch heads - all ancestors of parent = new csets
3149 3149 new = [0] * len(repo)
3150 3150 cl = repo.changelog
3151 3151 for a in [cl.rev(n) for n in bheads]:
3152 3152 new[a] = 1
3153 3153 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
3154 3154 new[a] = 1
3155 3155 for a in [p.rev() for p in parents]:
3156 3156 if a >= 0:
3157 3157 new[a] = 0
3158 3158 for a in cl.ancestors(*[p.rev() for p in parents]):
3159 3159 new[a] = 0
3160 3160 new = sum(new)
3161 3161
3162 3162 if new == 0:
3163 3163 ui.status(_('update: (current)\n'))
3164 3164 elif pnode not in bheads:
3165 3165 ui.write(_('update: %d new changesets (update)\n') % new)
3166 3166 else:
3167 3167 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
3168 3168 (new, len(bheads)))
3169 3169
3170 3170 if opts.get('remote'):
3171 3171 t = []
3172 3172 source, branches = hg.parseurl(ui.expandpath('default'))
3173 3173 other = hg.repository(cmdutil.remoteui(repo, {}), source)
3174 3174 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3175 3175 ui.debug('comparing with %s\n' % url.hidepassword(source))
3176 3176 repo.ui.pushbuffer()
3177 3177 common, incoming, rheads = repo.findcommonincoming(other)
3178 3178 repo.ui.popbuffer()
3179 3179 if incoming:
3180 3180 t.append(_('1 or more incoming'))
3181 3181
3182 3182 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
3183 3183 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3184 3184 other = hg.repository(cmdutil.remoteui(repo, {}), dest)
3185 3185 ui.debug('comparing with %s\n' % url.hidepassword(dest))
3186 3186 repo.ui.pushbuffer()
3187 3187 o = repo.findoutgoing(other)
3188 3188 repo.ui.popbuffer()
3189 3189 o = repo.changelog.nodesbetween(o, None)[0]
3190 3190 if o:
3191 3191 t.append(_('%d outgoing') % len(o))
3192 3192
3193 3193 if t:
3194 3194 ui.write(_('remote: %s\n') % (', '.join(t)))
3195 3195 else:
3196 3196 ui.status(_('remote: (synced)\n'))
3197 3197
3198 3198 def tag(ui, repo, name1, *names, **opts):
3199 3199 """add one or more tags for the current or given revision
3200 3200
3201 3201 Name a particular revision using <name>.
3202 3202
3203 3203 Tags are used to name particular revisions of the repository and are
3204 3204 very useful to compare different revisions, to go back to significant
3205 3205 earlier versions or to mark branch points as releases, etc.
3206 3206
3207 3207 If no revision is given, the parent of the working directory is
3208 3208 used, or tip if no revision is checked out.
3209 3209
3210 3210 To facilitate version control, distribution, and merging of tags,
3211 3211 they are stored as a file named ".hgtags" which is managed
3212 3212 similarly to other project files and can be hand-edited if
3213 3213 necessary. The file '.hg/localtags' is used for local tags (not
3214 3214 shared among repositories).
3215 3215
3216 See 'hg help dates' for a list of formats valid for -d/--date.
3216 See :hg:`help dates` for a list of formats valid for -d/--date.
3217 3217 """
3218 3218
3219 3219 rev_ = "."
3220 3220 names = (name1,) + names
3221 3221 if len(names) != len(set(names)):
3222 3222 raise util.Abort(_('tag names must be unique'))
3223 3223 for n in names:
3224 3224 if n in ['tip', '.', 'null']:
3225 3225 raise util.Abort(_('the name \'%s\' is reserved') % n)
3226 3226 if opts.get('rev') and opts.get('remove'):
3227 3227 raise util.Abort(_("--rev and --remove are incompatible"))
3228 3228 if opts.get('rev'):
3229 3229 rev_ = opts['rev']
3230 3230 message = opts.get('message')
3231 3231 if opts.get('remove'):
3232 3232 expectedtype = opts.get('local') and 'local' or 'global'
3233 3233 for n in names:
3234 3234 if not repo.tagtype(n):
3235 3235 raise util.Abort(_('tag \'%s\' does not exist') % n)
3236 3236 if repo.tagtype(n) != expectedtype:
3237 3237 if expectedtype == 'global':
3238 3238 raise util.Abort(_('tag \'%s\' is not a global tag') % n)
3239 3239 else:
3240 3240 raise util.Abort(_('tag \'%s\' is not a local tag') % n)
3241 3241 rev_ = nullid
3242 3242 if not message:
3243 3243 # we don't translate commit messages
3244 3244 message = 'Removed tag %s' % ', '.join(names)
3245 3245 elif not opts.get('force'):
3246 3246 for n in names:
3247 3247 if n in repo.tags():
3248 3248 raise util.Abort(_('tag \'%s\' already exists '
3249 3249 '(use -f to force)') % n)
3250 3250 if not rev_ and repo.dirstate.parents()[1] != nullid:
3251 3251 raise util.Abort(_('uncommitted merge - please provide a '
3252 3252 'specific revision'))
3253 3253 r = repo[rev_].node()
3254 3254
3255 3255 if not message:
3256 3256 # we don't translate commit messages
3257 3257 message = ('Added tag %s for changeset %s' %
3258 3258 (', '.join(names), short(r)))
3259 3259
3260 3260 date = opts.get('date')
3261 3261 if date:
3262 3262 date = util.parsedate(date)
3263 3263
3264 3264 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
3265 3265
3266 3266 def tags(ui, repo):
3267 3267 """list repository tags
3268 3268
3269 3269 This lists both regular and local tags. When the -v/--verbose
3270 3270 switch is used, a third column "local" is printed for local tags.
3271 3271 """
3272 3272
3273 3273 hexfunc = ui.debugflag and hex or short
3274 3274 tagtype = ""
3275 3275
3276 3276 for t, n in reversed(repo.tagslist()):
3277 3277 if ui.quiet:
3278 3278 ui.write("%s\n" % t)
3279 3279 continue
3280 3280
3281 3281 try:
3282 3282 hn = hexfunc(n)
3283 3283 r = "%5d:%s" % (repo.changelog.rev(n), hn)
3284 3284 except error.LookupError:
3285 3285 r = " ?:%s" % hn
3286 3286 else:
3287 3287 spaces = " " * (30 - encoding.colwidth(t))
3288 3288 if ui.verbose:
3289 3289 if repo.tagtype(t) == 'local':
3290 3290 tagtype = " local"
3291 3291 else:
3292 3292 tagtype = ""
3293 3293 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
3294 3294
3295 3295 def tip(ui, repo, **opts):
3296 3296 """show the tip revision
3297 3297
3298 3298 The tip revision (usually just called the tip) is the changeset
3299 3299 most recently added to the repository (and therefore the most
3300 3300 recently changed head).
3301 3301
3302 3302 If you have just made a commit, that commit will be the tip. If
3303 3303 you have just pulled changes from another repository, the tip of
3304 3304 that repository becomes the current tip. The "tip" tag is special
3305 3305 and cannot be renamed or assigned to a different changeset.
3306 3306 """
3307 3307 displayer = cmdutil.show_changeset(ui, repo, opts)
3308 3308 displayer.show(repo[len(repo) - 1])
3309 3309 displayer.close()
3310 3310
3311 3311 def unbundle(ui, repo, fname1, *fnames, **opts):
3312 3312 """apply one or more changegroup files
3313 3313
3314 3314 Apply one or more compressed changegroup files generated by the
3315 3315 bundle command.
3316 3316 """
3317 3317 fnames = (fname1,) + fnames
3318 3318
3319 3319 lock = repo.lock()
3320 3320 try:
3321 3321 for fname in fnames:
3322 3322 f = url.open(ui, fname)
3323 3323 gen = changegroup.readbundle(f, fname)
3324 3324 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
3325 3325 finally:
3326 3326 lock.release()
3327 3327
3328 3328 return postincoming(ui, repo, modheads, opts.get('update'), None)
3329 3329
3330 3330 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
3331 3331 """update working directory (or switch revisions)
3332 3332
3333 3333 Update the repository's working directory to the specified
3334 3334 changeset.
3335 3335
3336 3336 If no changeset is specified, attempt to update to the head of the
3337 3337 current branch. If this head is a descendant of the working
3338 3338 directory's parent, update to it, otherwise abort.
3339 3339
3340 3340 The following rules apply when the working directory contains
3341 3341 uncommitted changes:
3342 3342
3343 3343 1. If neither -c/--check nor -C/--clean is specified, and if
3344 3344 the requested changeset is an ancestor or descendant of
3345 3345 the working directory's parent, the uncommitted changes
3346 3346 are merged into the requested changeset and the merged
3347 3347 result is left uncommitted. If the requested changeset is
3348 3348 not an ancestor or descendant (that is, it is on another
3349 3349 branch), the update is aborted and the uncommitted changes
3350 3350 are preserved.
3351 3351
3352 3352 2. With the -c/--check option, the update is aborted and the
3353 3353 uncommitted changes are preserved.
3354 3354
3355 3355 3. With the -C/--clean option, uncommitted changes are discarded and
3356 3356 the working directory is updated to the requested changeset.
3357 3357
3358 Use null as the changeset to remove the working directory (like 'hg
3359 clone -U').
3360
3361 If you want to update just one file to an older changeset, use 'hg revert'.
3362
3363 See 'hg help dates' for a list of formats valid for -d/--date.
3358 Use null as the changeset to remove the working directory (like
3359 :hg:`clone -U`).
3360
3361 If you want to update just one file to an older changeset, use :hg:`revert`.
3362
3363 See :hg:`help dates` for a list of formats valid for -d/--date.
3364 3364 """
3365 3365 if rev and node:
3366 3366 raise util.Abort(_("please specify just one revision"))
3367 3367
3368 3368 if not rev:
3369 3369 rev = node
3370 3370
3371 3371 if check and clean:
3372 3372 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
3373 3373
3374 3374 if check:
3375 3375 # we could use dirty() but we can ignore merge and branch trivia
3376 3376 c = repo[None]
3377 3377 if c.modified() or c.added() or c.removed():
3378 3378 raise util.Abort(_("uncommitted local changes"))
3379 3379
3380 3380 if date:
3381 3381 if rev:
3382 3382 raise util.Abort(_("you can't specify a revision and a date"))
3383 3383 rev = cmdutil.finddate(ui, repo, date)
3384 3384
3385 3385 if clean or check:
3386 3386 return hg.clean(repo, rev)
3387 3387 else:
3388 3388 return hg.update(repo, rev)
3389 3389
3390 3390 def verify(ui, repo):
3391 3391 """verify the integrity of the repository
3392 3392
3393 3393 Verify the integrity of the current repository.
3394 3394
3395 3395 This will perform an extensive check of the repository's
3396 3396 integrity, validating the hashes and checksums of each entry in
3397 3397 the changelog, manifest, and tracked files, as well as the
3398 3398 integrity of their crosslinks and indices.
3399 3399 """
3400 3400 return hg.verify(repo)
3401 3401
3402 3402 def version_(ui):
3403 3403 """output version and copyright information"""
3404 3404 ui.write(_("Mercurial Distributed SCM (version %s)\n")
3405 3405 % util.version())
3406 3406 ui.status(_(
3407 3407 "\nCopyright (C) 2005-2010 Matt Mackall <mpm@selenic.com> and others\n"
3408 3408 "This is free software; see the source for copying conditions. "
3409 3409 "There is NO\nwarranty; "
3410 3410 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
3411 3411 ))
3412 3412
3413 3413 # Command options and aliases are listed here, alphabetically
3414 3414
3415 3415 globalopts = [
3416 3416 ('R', 'repository', '',
3417 3417 _('repository root directory or name of overlay bundle file')),
3418 3418 ('', 'cwd', '', _('change working directory')),
3419 3419 ('y', 'noninteractive', None,
3420 3420 _('do not prompt, assume \'yes\' for any required answers')),
3421 3421 ('q', 'quiet', None, _('suppress output')),
3422 3422 ('v', 'verbose', None, _('enable additional output')),
3423 3423 ('', 'config', [],
3424 3424 _('set/override config option (use \'section.name=value\')')),
3425 3425 ('', 'debug', None, _('enable debugging output')),
3426 3426 ('', 'debugger', None, _('start debugger')),
3427 3427 ('', 'encoding', encoding.encoding, _('set the charset encoding')),
3428 3428 ('', 'encodingmode', encoding.encodingmode,
3429 3429 _('set the charset encoding mode')),
3430 3430 ('', 'traceback', None, _('always print a traceback on exception')),
3431 3431 ('', 'time', None, _('time how long the command takes')),
3432 3432 ('', 'profile', None, _('print command execution profile')),
3433 3433 ('', 'version', None, _('output version information and exit')),
3434 3434 ('h', 'help', None, _('display help and exit')),
3435 3435 ]
3436 3436
3437 3437 dryrunopts = [('n', 'dry-run', None,
3438 3438 _('do not perform actions, just print output'))]
3439 3439
3440 3440 remoteopts = [
3441 3441 ('e', 'ssh', '', _('specify ssh command to use')),
3442 3442 ('', 'remotecmd', '', _('specify hg command to run on the remote side')),
3443 3443 ]
3444 3444
3445 3445 walkopts = [
3446 3446 ('I', 'include', [], _('include names matching the given patterns')),
3447 3447 ('X', 'exclude', [], _('exclude names matching the given patterns')),
3448 3448 ]
3449 3449
3450 3450 commitopts = [
3451 3451 ('m', 'message', '', _('use <text> as commit message')),
3452 3452 ('l', 'logfile', '', _('read commit message from <file>')),
3453 3453 ]
3454 3454
3455 3455 commitopts2 = [
3456 3456 ('d', 'date', '', _('record datecode as commit date')),
3457 3457 ('u', 'user', '', _('record the specified user as committer')),
3458 3458 ]
3459 3459
3460 3460 templateopts = [
3461 3461 ('', 'style', '', _('display using template map file')),
3462 3462 ('', 'template', '', _('display with template')),
3463 3463 ]
3464 3464
3465 3465 logopts = [
3466 3466 ('p', 'patch', None, _('show patch')),
3467 3467 ('g', 'git', None, _('use git extended diff format')),
3468 3468 ('l', 'limit', '', _('limit number of changes displayed')),
3469 3469 ('M', 'no-merges', None, _('do not show merges')),
3470 3470 ] + templateopts
3471 3471
3472 3472 diffopts = [
3473 3473 ('a', 'text', None, _('treat all files as text')),
3474 3474 ('g', 'git', None, _('use git extended diff format')),
3475 3475 ('', 'nodates', None, _('omit dates from diff headers'))
3476 3476 ]
3477 3477
3478 3478 diffopts2 = [
3479 3479 ('p', 'show-function', None, _('show which function each change is in')),
3480 3480 ('', 'reverse', None, _('produce a diff that undoes the changes')),
3481 3481 ('w', 'ignore-all-space', None,
3482 3482 _('ignore white space when comparing lines')),
3483 3483 ('b', 'ignore-space-change', None,
3484 3484 _('ignore changes in the amount of white space')),
3485 3485 ('B', 'ignore-blank-lines', None,
3486 3486 _('ignore changes whose lines are all blank')),
3487 3487 ('U', 'unified', '', _('number of lines of context to show')),
3488 3488 ('', 'stat', None, _('output diffstat-style summary of changes')),
3489 3489 ]
3490 3490
3491 3491 similarityopts = [
3492 3492 ('s', 'similarity', '',
3493 3493 _('guess renamed files by similarity (0<=s<=100)'))
3494 3494 ]
3495 3495
3496 3496 table = {
3497 3497 "^add": (add, walkopts + dryrunopts, _('[OPTION]... [FILE]...')),
3498 3498 "addremove":
3499 3499 (addremove, similarityopts + walkopts + dryrunopts,
3500 3500 _('[OPTION]... [FILE]...')),
3501 3501 "^annotate|blame":
3502 3502 (annotate,
3503 3503 [('r', 'rev', '', _('annotate the specified revision')),
3504 3504 ('', 'follow', None,
3505 3505 _('follow copies/renames and list the filename (DEPRECATED)')),
3506 3506 ('', 'no-follow', None, _("don't follow copies and renames")),
3507 3507 ('a', 'text', None, _('treat all files as text')),
3508 3508 ('u', 'user', None, _('list the author (long with -v)')),
3509 3509 ('f', 'file', None, _('list the filename')),
3510 3510 ('d', 'date', None, _('list the date (short with -q)')),
3511 3511 ('n', 'number', None, _('list the revision number (default)')),
3512 3512 ('c', 'changeset', None, _('list the changeset')),
3513 3513 ('l', 'line-number', None,
3514 3514 _('show line number at the first appearance'))
3515 3515 ] + walkopts,
3516 3516 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
3517 3517 "archive":
3518 3518 (archive,
3519 3519 [('', 'no-decode', None, _('do not pass files through decoders')),
3520 3520 ('p', 'prefix', '', _('directory prefix for files in archive')),
3521 3521 ('r', 'rev', '', _('revision to distribute')),
3522 3522 ('t', 'type', '', _('type of distribution to create')),
3523 3523 ] + walkopts,
3524 3524 _('[OPTION]... DEST')),
3525 3525 "backout":
3526 3526 (backout,
3527 3527 [('', 'merge', None,
3528 3528 _('merge with old dirstate parent after backout')),
3529 3529 ('', 'parent', '', _('parent to choose when backing out merge')),
3530 3530 ('r', 'rev', '', _('revision to backout')),
3531 3531 ] + walkopts + commitopts + commitopts2,
3532 3532 _('[OPTION]... [-r] REV')),
3533 3533 "bisect":
3534 3534 (bisect,
3535 3535 [('r', 'reset', False, _('reset bisect state')),
3536 3536 ('g', 'good', False, _('mark changeset good')),
3537 3537 ('b', 'bad', False, _('mark changeset bad')),
3538 3538 ('s', 'skip', False, _('skip testing changeset')),
3539 3539 ('c', 'command', '', _('use command to check changeset state')),
3540 3540 ('U', 'noupdate', False, _('do not update to target'))],
3541 3541 _("[-gbsr] [-U] [-c CMD] [REV]")),
3542 3542 "branch":
3543 3543 (branch,
3544 3544 [('f', 'force', None,
3545 3545 _('set branch name even if it shadows an existing branch')),
3546 3546 ('C', 'clean', None, _('reset branch name to parent branch name'))],
3547 3547 _('[-fC] [NAME]')),
3548 3548 "branches":
3549 3549 (branches,
3550 3550 [('a', 'active', False,
3551 3551 _('show only branches that have unmerged heads')),
3552 3552 ('c', 'closed', False,
3553 3553 _('show normal and closed branches'))],
3554 3554 _('[-ac]')),
3555 3555 "bundle":
3556 3556 (bundle,
3557 3557 [('f', 'force', None,
3558 3558 _('run even when the destination is unrelated')),
3559 3559 ('r', 'rev', [],
3560 3560 _('a changeset intended to be added to the destination')),
3561 3561 ('b', 'branch', [],
3562 3562 _('a specific branch you would like to bundle')),
3563 3563 ('', 'base', [],
3564 3564 _('a base changeset assumed to be available at the destination')),
3565 3565 ('a', 'all', None, _('bundle all changesets in the repository')),
3566 3566 ('t', 'type', 'bzip2', _('bundle compression type to use')),
3567 3567 ] + remoteopts,
3568 3568 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]')),
3569 3569 "cat":
3570 3570 (cat,
3571 3571 [('o', 'output', '', _('print output to file with formatted name')),
3572 3572 ('r', 'rev', '', _('print the given revision')),
3573 3573 ('', 'decode', None, _('apply any matching decode filter')),
3574 3574 ] + walkopts,
3575 3575 _('[OPTION]... FILE...')),
3576 3576 "^clone":
3577 3577 (clone,
3578 3578 [('U', 'noupdate', None,
3579 3579 _('the clone will include an empty working copy (only a repository)')),
3580 3580 ('u', 'updaterev', '',
3581 3581 _('revision, tag or branch to check out')),
3582 3582 ('r', 'rev', [],
3583 3583 _('include the specified changeset')),
3584 3584 ('b', 'branch', [],
3585 3585 _('clone only the specified branch')),
3586 3586 ('', 'pull', None, _('use pull protocol to copy metadata')),
3587 3587 ('', 'uncompressed', None,
3588 3588 _('use uncompressed transfer (fast over LAN)')),
3589 3589 ] + remoteopts,
3590 3590 _('[OPTION]... SOURCE [DEST]')),
3591 3591 "^commit|ci":
3592 3592 (commit,
3593 3593 [('A', 'addremove', None,
3594 3594 _('mark new/missing files as added/removed before committing')),
3595 3595 ('', 'close-branch', None,
3596 3596 _('mark a branch as closed, hiding it from the branch list')),
3597 3597 ] + walkopts + commitopts + commitopts2,
3598 3598 _('[OPTION]... [FILE]...')),
3599 3599 "copy|cp":
3600 3600 (copy,
3601 3601 [('A', 'after', None, _('record a copy that has already occurred')),
3602 3602 ('f', 'force', None,
3603 3603 _('forcibly copy over an existing managed file')),
3604 3604 ] + walkopts + dryrunopts,
3605 3605 _('[OPTION]... [SOURCE]... DEST')),
3606 3606 "debugancestor": (debugancestor, [], _('[INDEX] REV1 REV2')),
3607 3607 "debugcheckstate": (debugcheckstate, [], ''),
3608 3608 "debugcommands": (debugcommands, [], _('[COMMAND]')),
3609 3609 "debugcomplete":
3610 3610 (debugcomplete,
3611 3611 [('o', 'options', None, _('show the command options'))],
3612 3612 _('[-o] CMD')),
3613 3613 "debugdate":
3614 3614 (debugdate,
3615 3615 [('e', 'extended', None, _('try extended date formats'))],
3616 3616 _('[-e] DATE [RANGE]')),
3617 3617 "debugdata": (debugdata, [], _('FILE REV')),
3618 3618 "debugfsinfo": (debugfsinfo, [], _('[PATH]')),
3619 3619 "debugindex": (debugindex, [], _('FILE')),
3620 3620 "debugindexdot": (debugindexdot, [], _('FILE')),
3621 3621 "debuginstall": (debuginstall, [], ''),
3622 3622 "debugrebuildstate":
3623 3623 (debugrebuildstate,
3624 3624 [('r', 'rev', '', _('revision to rebuild to'))],
3625 3625 _('[-r REV] [REV]')),
3626 3626 "debugrename":
3627 3627 (debugrename,
3628 3628 [('r', 'rev', '', _('revision to debug'))],
3629 3629 _('[-r REV] FILE')),
3630 3630 "debugsetparents":
3631 3631 (debugsetparents, [], _('REV1 [REV2]')),
3632 3632 "debugstate":
3633 3633 (debugstate,
3634 3634 [('', 'nodates', None, _('do not display the saved mtime'))],
3635 3635 _('[OPTION]...')),
3636 3636 "debugsub":
3637 3637 (debugsub,
3638 3638 [('r', 'rev', '', _('revision to check'))],
3639 3639 _('[-r REV] [REV]')),
3640 3640 "debugwalk": (debugwalk, walkopts, _('[OPTION]... [FILE]...')),
3641 3641 "^diff":
3642 3642 (diff,
3643 3643 [('r', 'rev', [], _('revision')),
3644 3644 ('c', 'change', '', _('change made by revision'))
3645 3645 ] + diffopts + diffopts2 + walkopts,
3646 3646 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...')),
3647 3647 "^export":
3648 3648 (export,
3649 3649 [('o', 'output', '', _('print output to file with formatted name')),
3650 3650 ('', 'switch-parent', None, _('diff against the second parent')),
3651 3651 ('r', 'rev', [], _('revisions to export')),
3652 3652 ] + diffopts,
3653 3653 _('[OPTION]... [-o OUTFILESPEC] REV...')),
3654 3654 "^forget":
3655 3655 (forget,
3656 3656 [] + walkopts,
3657 3657 _('[OPTION]... FILE...')),
3658 3658 "grep":
3659 3659 (grep,
3660 3660 [('0', 'print0', None, _('end fields with NUL')),
3661 3661 ('', 'all', None, _('print all revisions that match')),
3662 3662 ('f', 'follow', None,
3663 3663 _('follow changeset history,'
3664 3664 ' or file history across copies and renames')),
3665 3665 ('i', 'ignore-case', None, _('ignore case when matching')),
3666 3666 ('l', 'files-with-matches', None,
3667 3667 _('print only filenames and revisions that match')),
3668 3668 ('n', 'line-number', None, _('print matching line numbers')),
3669 3669 ('r', 'rev', [], _('search in given revision range')),
3670 3670 ('u', 'user', None, _('list the author (long with -v)')),
3671 3671 ('d', 'date', None, _('list the date (short with -q)')),
3672 3672 ] + walkopts,
3673 3673 _('[OPTION]... PATTERN [FILE]...')),
3674 3674 "heads":
3675 3675 (heads,
3676 3676 [('r', 'rev', '', _('show only heads which are descendants of REV')),
3677 3677 ('t', 'topo', False, _('show topological heads only')),
3678 3678 ('a', 'active', False,
3679 3679 _('show active branchheads only [DEPRECATED]')),
3680 3680 ('c', 'closed', False,
3681 3681 _('show normal and closed branch heads')),
3682 3682 ] + templateopts,
3683 3683 _('[-ac] [-r STARTREV] [REV]...')),
3684 3684 "help": (help_, [], _('[TOPIC]')),
3685 3685 "identify|id":
3686 3686 (identify,
3687 3687 [('r', 'rev', '', _('identify the specified revision')),
3688 3688 ('n', 'num', None, _('show local revision number')),
3689 3689 ('i', 'id', None, _('show global revision id')),
3690 3690 ('b', 'branch', None, _('show branch')),
3691 3691 ('t', 'tags', None, _('show tags'))],
3692 3692 _('[-nibt] [-r REV] [SOURCE]')),
3693 3693 "import|patch":
3694 3694 (import_,
3695 3695 [('p', 'strip', 1,
3696 3696 _('directory strip option for patch. This has the same '
3697 3697 'meaning as the corresponding patch option')),
3698 3698 ('b', 'base', '', _('base path')),
3699 3699 ('f', 'force', None,
3700 3700 _('skip check for outstanding uncommitted changes')),
3701 3701 ('', 'no-commit', None,
3702 3702 _("don't commit, just update the working directory")),
3703 3703 ('', 'exact', None,
3704 3704 _('apply patch to the nodes from which it was generated')),
3705 3705 ('', 'import-branch', None,
3706 3706 _('use any branch information in patch (implied by --exact)'))] +
3707 3707 commitopts + commitopts2 + similarityopts,
3708 3708 _('[OPTION]... PATCH...')),
3709 3709 "incoming|in":
3710 3710 (incoming,
3711 3711 [('f', 'force', None,
3712 3712 _('run even if remote repository is unrelated')),
3713 3713 ('n', 'newest-first', None, _('show newest record first')),
3714 3714 ('', 'bundle', '', _('file to store the bundles into')),
3715 3715 ('r', 'rev', [],
3716 3716 _('a remote changeset intended to be added')),
3717 3717 ('b', 'branch', [],
3718 3718 _('a specific branch you would like to pull')),
3719 3719 ] + logopts + remoteopts,
3720 3720 _('[-p] [-n] [-M] [-f] [-r REV]...'
3721 3721 ' [--bundle FILENAME] [SOURCE]')),
3722 3722 "^init":
3723 3723 (init,
3724 3724 remoteopts,
3725 3725 _('[-e CMD] [--remotecmd CMD] [DEST]')),
3726 3726 "locate":
3727 3727 (locate,
3728 3728 [('r', 'rev', '', _('search the repository as it is in REV')),
3729 3729 ('0', 'print0', None,
3730 3730 _('end filenames with NUL, for use with xargs')),
3731 3731 ('f', 'fullpath', None,
3732 3732 _('print complete paths from the filesystem root')),
3733 3733 ] + walkopts,
3734 3734 _('[OPTION]... [PATTERN]...')),
3735 3735 "^log|history":
3736 3736 (log,
3737 3737 [('f', 'follow', None,
3738 3738 _('follow changeset history,'
3739 3739 ' or file history across copies and renames')),
3740 3740 ('', 'follow-first', None,
3741 3741 _('only follow the first parent of merge changesets')),
3742 3742 ('d', 'date', '', _('show revisions matching date spec')),
3743 3743 ('C', 'copies', None, _('show copied files')),
3744 3744 ('k', 'keyword', [], _('do case-insensitive search for a keyword')),
3745 3745 ('r', 'rev', [], _('show the specified revision or range')),
3746 3746 ('', 'removed', None, _('include revisions where files were removed')),
3747 3747 ('m', 'only-merges', None, _('show only merges')),
3748 3748 ('u', 'user', [], _('revisions committed by user')),
3749 3749 ('', 'only-branch', [],
3750 3750 _('show only changesets within the given named branch (DEPRECATED)')),
3751 3751 ('b', 'branch', [],
3752 3752 _('show changesets within the given named branch')),
3753 3753 ('P', 'prune', [],
3754 3754 _('do not display revision or any of its ancestors')),
3755 3755 ] + logopts + walkopts,
3756 3756 _('[OPTION]... [FILE]')),
3757 3757 "manifest":
3758 3758 (manifest,
3759 3759 [('r', 'rev', '', _('revision to display'))],
3760 3760 _('[-r REV]')),
3761 3761 "^merge":
3762 3762 (merge,
3763 3763 [('f', 'force', None, _('force a merge with outstanding changes')),
3764 3764 ('r', 'rev', '', _('revision to merge')),
3765 3765 ('P', 'preview', None,
3766 3766 _('review revisions to merge (no merge is performed)'))],
3767 3767 _('[-P] [-f] [[-r] REV]')),
3768 3768 "outgoing|out":
3769 3769 (outgoing,
3770 3770 [('f', 'force', None,
3771 3771 _('run even when the destination is unrelated')),
3772 3772 ('r', 'rev', [],
3773 3773 _('a changeset intended to be included in the destination')),
3774 3774 ('n', 'newest-first', None, _('show newest record first')),
3775 3775 ('b', 'branch', [],
3776 3776 _('a specific branch you would like to push')),
3777 3777 ] + logopts + remoteopts,
3778 3778 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
3779 3779 "parents":
3780 3780 (parents,
3781 3781 [('r', 'rev', '', _('show parents of the specified revision')),
3782 3782 ] + templateopts,
3783 3783 _('[-r REV] [FILE]')),
3784 3784 "paths": (paths, [], _('[NAME]')),
3785 3785 "^pull":
3786 3786 (pull,
3787 3787 [('u', 'update', None,
3788 3788 _('update to new branch head if changesets were pulled')),
3789 3789 ('f', 'force', None,
3790 3790 _('run even when remote repository is unrelated')),
3791 3791 ('r', 'rev', [],
3792 3792 _('a remote changeset intended to be added')),
3793 3793 ('b', 'branch', [],
3794 3794 _('a specific branch you would like to pull')),
3795 3795 ] + remoteopts,
3796 3796 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
3797 3797 "^push":
3798 3798 (push,
3799 3799 [('f', 'force', None, _('force push')),
3800 3800 ('r', 'rev', [],
3801 3801 _('a changeset intended to be included in the destination')),
3802 3802 ('b', 'branch', [],
3803 3803 _('a specific branch you would like to push')),
3804 3804 ] + remoteopts,
3805 3805 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
3806 3806 "recover": (recover, []),
3807 3807 "^remove|rm":
3808 3808 (remove,
3809 3809 [('A', 'after', None, _('record delete for missing files')),
3810 3810 ('f', 'force', None,
3811 3811 _('remove (and delete) file even if added or modified')),
3812 3812 ] + walkopts,
3813 3813 _('[OPTION]... FILE...')),
3814 3814 "rename|mv":
3815 3815 (rename,
3816 3816 [('A', 'after', None, _('record a rename that has already occurred')),
3817 3817 ('f', 'force', None,
3818 3818 _('forcibly copy over an existing managed file')),
3819 3819 ] + walkopts + dryrunopts,
3820 3820 _('[OPTION]... SOURCE... DEST')),
3821 3821 "resolve":
3822 3822 (resolve,
3823 3823 [('a', 'all', None, _('select all unresolved files')),
3824 3824 ('l', 'list', None, _('list state of files needing merge')),
3825 3825 ('m', 'mark', None, _('mark files as resolved')),
3826 3826 ('u', 'unmark', None, _('unmark files as resolved')),
3827 3827 ('n', 'no-status', None, _('hide status prefix'))]
3828 3828 + walkopts,
3829 3829 _('[OPTION]... [FILE]...')),
3830 3830 "revert":
3831 3831 (revert,
3832 3832 [('a', 'all', None, _('revert all changes when no arguments given')),
3833 3833 ('d', 'date', '', _('tipmost revision matching date')),
3834 3834 ('r', 'rev', '', _('revert to the specified revision')),
3835 3835 ('', 'no-backup', None, _('do not save backup copies of files')),
3836 3836 ] + walkopts + dryrunopts,
3837 3837 _('[OPTION]... [-r REV] [NAME]...')),
3838 3838 "rollback": (rollback, dryrunopts),
3839 3839 "root": (root, []),
3840 3840 "^serve":
3841 3841 (serve,
3842 3842 [('A', 'accesslog', '', _('name of access log file to write to')),
3843 3843 ('d', 'daemon', None, _('run server in background')),
3844 3844 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
3845 3845 ('E', 'errorlog', '', _('name of error log file to write to')),
3846 3846 # use string type, then we can check if something was passed
3847 3847 ('p', 'port', '', _('port to listen on (default: 8000)')),
3848 3848 ('a', 'address', '',
3849 3849 _('address to listen on (default: all interfaces)')),
3850 3850 ('', 'prefix', '',
3851 3851 _('prefix path to serve from (default: server root)')),
3852 3852 ('n', 'name', '',
3853 3853 _('name to show in web pages (default: working directory)')),
3854 3854 ('', 'webdir-conf', '', _('name of the webdir config file'
3855 3855 ' (serve more than one repository)')),
3856 3856 ('', 'pid-file', '', _('name of file to write process ID to')),
3857 3857 ('', 'stdio', None, _('for remote clients')),
3858 3858 ('t', 'templates', '', _('web templates to use')),
3859 3859 ('', 'style', '', _('template style to use')),
3860 3860 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
3861 3861 ('', 'certificate', '', _('SSL certificate file'))],
3862 3862 _('[OPTION]...')),
3863 3863 "showconfig|debugconfig":
3864 3864 (showconfig,
3865 3865 [('u', 'untrusted', None, _('show untrusted configuration options'))],
3866 3866 _('[-u] [NAME]...')),
3867 3867 "^summary|sum":
3868 3868 (summary,
3869 3869 [('', 'remote', None, _('check for push and pull'))], '[--remote]'),
3870 3870 "^status|st":
3871 3871 (status,
3872 3872 [('A', 'all', None, _('show status of all files')),
3873 3873 ('m', 'modified', None, _('show only modified files')),
3874 3874 ('a', 'added', None, _('show only added files')),
3875 3875 ('r', 'removed', None, _('show only removed files')),
3876 3876 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
3877 3877 ('c', 'clean', None, _('show only files without changes')),
3878 3878 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
3879 3879 ('i', 'ignored', None, _('show only ignored files')),
3880 3880 ('n', 'no-status', None, _('hide status prefix')),
3881 3881 ('C', 'copies', None, _('show source of copied files')),
3882 3882 ('0', 'print0', None,
3883 3883 _('end filenames with NUL, for use with xargs')),
3884 3884 ('', 'rev', [], _('show difference from revision')),
3885 3885 ('', 'change', '', _('list the changed files of a revision')),
3886 3886 ] + walkopts,
3887 3887 _('[OPTION]... [FILE]...')),
3888 3888 "tag":
3889 3889 (tag,
3890 3890 [('f', 'force', None, _('replace existing tag')),
3891 3891 ('l', 'local', None, _('make the tag local')),
3892 3892 ('r', 'rev', '', _('revision to tag')),
3893 3893 ('', 'remove', None, _('remove a tag')),
3894 3894 # -l/--local is already there, commitopts cannot be used
3895 3895 ('m', 'message', '', _('use <text> as commit message')),
3896 3896 ] + commitopts2,
3897 3897 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...')),
3898 3898 "tags": (tags, [], ''),
3899 3899 "tip":
3900 3900 (tip,
3901 3901 [('p', 'patch', None, _('show patch')),
3902 3902 ('g', 'git', None, _('use git extended diff format')),
3903 3903 ] + templateopts,
3904 3904 _('[-p] [-g]')),
3905 3905 "unbundle":
3906 3906 (unbundle,
3907 3907 [('u', 'update', None,
3908 3908 _('update to new branch head if changesets were unbundled'))],
3909 3909 _('[-u] FILE...')),
3910 3910 "^update|up|checkout|co":
3911 3911 (update,
3912 3912 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
3913 3913 ('c', 'check', None, _('check for uncommitted changes')),
3914 3914 ('d', 'date', '', _('tipmost revision matching date')),
3915 3915 ('r', 'rev', '', _('revision'))],
3916 3916 _('[-c] [-C] [-d DATE] [[-r] REV]')),
3917 3917 "verify": (verify, []),
3918 3918 "version": (version_, []),
3919 3919 }
3920 3920
3921 3921 norepo = ("clone init version help debugcommands debugcomplete debugdata"
3922 3922 " debugindex debugindexdot debugdate debuginstall debugfsinfo")
3923 3923 optionalrepo = ("identify paths serve showconfig debugancestor")
@@ -1,29 +1,29
1 1 Mercurial's default format for showing changes between two versions of
2 2 a file is compatible with the unified format of GNU diff, which can be
3 3 used by GNU patch and many other standard tools.
4 4
5 5 While this standard format is often enough, it does not encode the
6 6 following information:
7 7
8 8 - executable status and other permission bits
9 9 - copy or rename information
10 10 - changes in binary files
11 11 - creation or deletion of empty files
12 12
13 13 Mercurial also supports the extended diff format from the git VCS
14 14 which addresses these limitations. The git diff format is not produced
15 15 by default because a few widespread tools still do not understand this
16 16 format.
17 17
18 18 This means that when generating diffs from a Mercurial repository
19 (e.g. with "hg export"), you should be careful about things like file
19 (e.g. with :hg:`export`), you should be careful about things like file
20 20 copies and renames or other things mentioned above, because when
21 21 applying a standard diff to a different repository, this extra
22 22 information is lost. Mercurial's internal operations (like push and
23 23 pull) are not affected by this, because they use an internal binary
24 24 format for communicating changes.
25 25
26 26 To make Mercurial produce the git extended diff format, use the --git
27 27 option available for many commands, or set 'git = True' in the [diff]
28 28 section of your hgrc. You do not need to set this option when
29 29 importing diffs in this format or using them in the mq extension.
@@ -1,63 +1,63
1 1 Valid URLs are of the form::
2 2
3 3 local/filesystem/path[#revision]
4 4 file://local/filesystem/path[#revision]
5 5 http://[user[:pass]@]host[:port]/[path][#revision]
6 6 https://[user[:pass]@]host[:port]/[path][#revision]
7 7 ssh://[user[:pass]@]host[:port]/[path][#revision]
8 8
9 9 Paths in the local filesystem can either point to Mercurial
10 repositories or to bundle files (as created by 'hg bundle' or 'hg
11 incoming --bundle').
10 repositories or to bundle files (as created by :hg:`bundle` or :hg:`
11 incoming --bundle`).
12 12
13 13 An optional identifier after # indicates a particular branch, tag, or
14 changeset to use from the remote repository. See also 'hg help
15 revisions'.
14 changeset to use from the remote repository. See also :hg:`help
15 revisions`.
16 16
17 17 Some features, such as pushing to http:// and https:// URLs are only
18 18 possible if the feature is explicitly enabled on the remote Mercurial
19 19 server.
20 20
21 21 Some notes about using SSH with Mercurial:
22 22
23 23 - SSH requires an accessible shell account on the destination machine
24 24 and a copy of hg in the remote path or specified with as remotecmd.
25 25 - path is relative to the remote user's home directory by default. Use
26 26 an extra slash at the start of a path to specify an absolute path::
27 27
28 28 ssh://example.com//tmp/repository
29 29
30 30 - Mercurial doesn't use its own compression via SSH; the right thing
31 31 to do is to configure it in your ~/.ssh/config, e.g.::
32 32
33 33 Host *.mylocalnetwork.example.com
34 34 Compression no
35 35 Host *
36 36 Compression yes
37 37
38 38 Alternatively specify "ssh -C" as your ssh command in your hgrc or
39 39 with the --ssh command line option.
40 40
41 41 These URLs can all be stored in your hgrc with path aliases under the
42 42 [paths] section like so::
43 43
44 44 [paths]
45 45 alias1 = URL1
46 46 alias2 = URL2
47 47 ...
48 48
49 49 You can then use the alias for any command that uses a URL (for
50 example 'hg pull alias1' will be treated as 'hg pull URL1').
50 example :hg:`pull alias1` will be treated as :hg:`pull URL1`).
51 51
52 52 Two path aliases are special because they are used as defaults when
53 53 you do not provide the URL to a command:
54 54
55 55 default:
56 56 When you create a repository with hg clone, the clone command saves
57 57 the location of the source repository as the new repository's
58 58 'default' path. This is then used when you omit path from push- and
59 59 pull-like commands (including incoming and outgoing).
60 60
61 61 default-push:
62 62 The push command will look for a path named 'default-push', and
63 63 prefer it over 'default' if both are defined.
@@ -1,637 +1,637
1 1 Mercurial Distributed SCM
2 2
3 3 basic commands:
4 4
5 5 add add the specified files on the next commit
6 6 annotate show changeset information by line for each file
7 7 clone make a copy of an existing repository
8 8 commit commit the specified files or all outstanding changes
9 9 diff diff repository (or selected files)
10 10 export dump the header and diffs for one or more changesets
11 11 forget forget the specified files on the next commit
12 12 init create a new repository in the given directory
13 13 log show revision history of entire repository or files
14 14 merge merge working directory with another revision
15 15 pull pull changes from the specified source
16 16 push push changes to the specified destination
17 17 remove remove the specified files on the next commit
18 18 serve start stand-alone webserver
19 19 status show changed files in the working directory
20 20 summary summarize working directory state
21 21 update update working directory (or switch revisions)
22 22
23 23 use "hg help" for the full list of commands or "hg -v" for details
24 24 add add the specified files on the next commit
25 25 annotate show changeset information by line for each file
26 26 clone make a copy of an existing repository
27 27 commit commit the specified files or all outstanding changes
28 28 diff diff repository (or selected files)
29 29 export dump the header and diffs for one or more changesets
30 30 forget forget the specified files on the next commit
31 31 init create a new repository in the given directory
32 32 log show revision history of entire repository or files
33 33 merge merge working directory with another revision
34 34 pull pull changes from the specified source
35 35 push push changes to the specified destination
36 36 remove remove the specified files on the next commit
37 37 serve start stand-alone webserver
38 38 status show changed files in the working directory
39 39 summary summarize working directory state
40 40 update update working directory (or switch revisions)
41 41 Mercurial Distributed SCM
42 42
43 43 list of commands:
44 44
45 45 add add the specified files on the next commit
46 46 addremove add all new files, delete all missing files
47 47 annotate show changeset information by line for each file
48 48 archive create an unversioned archive of a repository revision
49 49 backout reverse effect of earlier changeset
50 50 bisect subdivision search of changesets
51 51 branch set or show the current branch name
52 52 branches list repository named branches
53 53 bundle create a changegroup file
54 54 cat output the current or given revision of files
55 55 clone make a copy of an existing repository
56 56 commit commit the specified files or all outstanding changes
57 57 copy mark files as copied for the next commit
58 58 diff diff repository (or selected files)
59 59 export dump the header and diffs for one or more changesets
60 60 forget forget the specified files on the next commit
61 61 grep search for a pattern in specified files and revisions
62 62 heads show current repository heads or show branch heads
63 63 help show help for a given topic or a help overview
64 64 identify identify the working copy or specified revision
65 65 import import an ordered set of patches
66 66 incoming show new changesets found in source
67 67 init create a new repository in the given directory
68 68 locate locate files matching specific patterns
69 69 log show revision history of entire repository or files
70 70 manifest output the current or given revision of the project manifest
71 71 merge merge working directory with another revision
72 72 outgoing show changesets not found in the destination
73 73 parents show the parents of the working directory or revision
74 74 paths show aliases for remote repositories
75 75 pull pull changes from the specified source
76 76 push push changes to the specified destination
77 77 recover roll back an interrupted transaction
78 78 remove remove the specified files on the next commit
79 79 rename rename files; equivalent of copy + remove
80 80 resolve various operations to help finish a merge
81 81 revert restore individual files or directories to an earlier state
82 82 rollback roll back the last transaction (dangerous)
83 83 root print the root (top) of the current working directory
84 84 serve start stand-alone webserver
85 85 showconfig show combined config settings from all hgrc files
86 86 status show changed files in the working directory
87 87 summary summarize working directory state
88 88 tag add one or more tags for the current or given revision
89 89 tags list repository tags
90 90 tip show the tip revision
91 91 unbundle apply one or more changegroup files
92 92 update update working directory (or switch revisions)
93 93 verify verify the integrity of the repository
94 94 version output version and copyright information
95 95
96 96 additional help topics:
97 97
98 98 config Configuration Files
99 99 dates Date Formats
100 100 patterns File Name Patterns
101 101 environment Environment Variables
102 102 revisions Specifying Single Revisions
103 103 multirevs Specifying Multiple Revisions
104 104 diffs Diff Formats
105 105 templating Template Usage
106 106 urls URL Paths
107 107 extensions Using additional features
108 108
109 109 use "hg -v help" to show aliases and global options
110 110 add add the specified files on the next commit
111 111 addremove add all new files, delete all missing files
112 112 annotate show changeset information by line for each file
113 113 archive create an unversioned archive of a repository revision
114 114 backout reverse effect of earlier changeset
115 115 bisect subdivision search of changesets
116 116 branch set or show the current branch name
117 117 branches list repository named branches
118 118 bundle create a changegroup file
119 119 cat output the current or given revision of files
120 120 clone make a copy of an existing repository
121 121 commit commit the specified files or all outstanding changes
122 122 copy mark files as copied for the next commit
123 123 diff diff repository (or selected files)
124 124 export dump the header and diffs for one or more changesets
125 125 forget forget the specified files on the next commit
126 126 grep search for a pattern in specified files and revisions
127 127 heads show current repository heads or show branch heads
128 128 help show help for a given topic or a help overview
129 129 identify identify the working copy or specified revision
130 130 import import an ordered set of patches
131 131 incoming show new changesets found in source
132 132 init create a new repository in the given directory
133 133 locate locate files matching specific patterns
134 134 log show revision history of entire repository or files
135 135 manifest output the current or given revision of the project manifest
136 136 merge merge working directory with another revision
137 137 outgoing show changesets not found in the destination
138 138 parents show the parents of the working directory or revision
139 139 paths show aliases for remote repositories
140 140 pull pull changes from the specified source
141 141 push push changes to the specified destination
142 142 recover roll back an interrupted transaction
143 143 remove remove the specified files on the next commit
144 144 rename rename files; equivalent of copy + remove
145 145 resolve various operations to help finish a merge
146 146 revert restore individual files or directories to an earlier state
147 147 rollback roll back the last transaction (dangerous)
148 148 root print the root (top) of the current working directory
149 149 serve start stand-alone webserver
150 150 showconfig show combined config settings from all hgrc files
151 151 status show changed files in the working directory
152 152 summary summarize working directory state
153 153 tag add one or more tags for the current or given revision
154 154 tags list repository tags
155 155 tip show the tip revision
156 156 unbundle apply one or more changegroup files
157 157 update update working directory (or switch revisions)
158 158 verify verify the integrity of the repository
159 159 version output version and copyright information
160 160
161 161 additional help topics:
162 162
163 163 config Configuration Files
164 164 dates Date Formats
165 165 patterns File Name Patterns
166 166 environment Environment Variables
167 167 revisions Specifying Single Revisions
168 168 multirevs Specifying Multiple Revisions
169 169 diffs Diff Formats
170 170 templating Template Usage
171 171 urls URL Paths
172 172 extensions Using additional features
173 173 %% test short command list with verbose option
174 174 Mercurial Distributed SCM (version xxx)
175 175
176 176 Copyright (C) 2005-2010 Matt Mackall <mpm@selenic.com> and others
177 177 This is free software; see the source for copying conditions. There is NO
178 178 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
179 179
180 180 basic commands:
181 181
182 182 add:
183 183 add the specified files on the next commit
184 184 annotate, blame:
185 185 show changeset information by line for each file
186 186 clone:
187 187 make a copy of an existing repository
188 188 commit, ci:
189 189 commit the specified files or all outstanding changes
190 190 diff:
191 191 diff repository (or selected files)
192 192 export:
193 193 dump the header and diffs for one or more changesets
194 194 forget:
195 195 forget the specified files on the next commit
196 196 init:
197 197 create a new repository in the given directory
198 198 log, history:
199 199 show revision history of entire repository or files
200 200 merge:
201 201 merge working directory with another revision
202 202 pull:
203 203 pull changes from the specified source
204 204 push:
205 205 push changes to the specified destination
206 206 remove, rm:
207 207 remove the specified files on the next commit
208 208 serve:
209 209 start stand-alone webserver
210 210 status, st:
211 211 show changed files in the working directory
212 212 summary, sum:
213 213 summarize working directory state
214 214 update, up, checkout, co:
215 215 update working directory (or switch revisions)
216 216
217 217 global options:
218 218 -R --repository repository root directory or name of overlay bundle file
219 219 --cwd change working directory
220 220 -y --noninteractive do not prompt, assume 'yes' for any required answers
221 221 -q --quiet suppress output
222 222 -v --verbose enable additional output
223 223 --config set/override config option (use 'section.name=value')
224 224 --debug enable debugging output
225 225 --debugger start debugger
226 226 --encoding set the charset encoding (default: ascii)
227 227 --encodingmode set the charset encoding mode (default: strict)
228 228 --traceback always print a traceback on exception
229 229 --time time how long the command takes
230 230 --profile print command execution profile
231 231 --version output version information and exit
232 232 -h --help display help and exit
233 233
234 234 use "hg help" for the full list of commands
235 235 hg add [OPTION]... [FILE]...
236 236
237 237 add the specified files on the next commit
238 238
239 239 Schedule files to be version controlled and added to the repository.
240 240
241 241 The files will be added to the repository at the next commit. To undo an
242 242 add before that, see hg forget.
243 243
244 244 If no names are given, add all files to the repository.
245 245
246 246 use "hg -v help add" to show verbose help
247 247
248 248 options:
249 249
250 250 -I --include include names matching the given patterns
251 251 -X --exclude exclude names matching the given patterns
252 252 -n --dry-run do not perform actions, just print output
253 253
254 254 use "hg -v help add" to show global options
255 255 %% verbose help for add
256 256 hg add [OPTION]... [FILE]...
257 257
258 258 add the specified files on the next commit
259 259
260 260 Schedule files to be version controlled and added to the repository.
261 261
262 262 The files will be added to the repository at the next commit. To undo an
263 263 add before that, see hg forget.
264 264
265 265 If no names are given, add all files to the repository.
266 266
267 267 An example showing how new (unknown) files are added automatically by "hg
268 268 add":
269 269
270 270 $ ls
271 271 foo.c
272 272 $ hg status
273 273 ? foo.c
274 274 $ hg add
275 275 adding foo.c
276 276 $ hg status
277 277 A foo.c
278 278
279 279 options:
280 280
281 281 -I --include include names matching the given patterns
282 282 -X --exclude exclude names matching the given patterns
283 283 -n --dry-run do not perform actions, just print output
284 284
285 285 global options:
286 286 -R --repository repository root directory or name of overlay bundle file
287 287 --cwd change working directory
288 288 -y --noninteractive do not prompt, assume 'yes' for any required answers
289 289 -q --quiet suppress output
290 290 -v --verbose enable additional output
291 291 --config set/override config option (use 'section.name=value')
292 292 --debug enable debugging output
293 293 --debugger start debugger
294 294 --encoding set the charset encoding (default: ascii)
295 295 --encodingmode set the charset encoding mode (default: strict)
296 296 --traceback always print a traceback on exception
297 297 --time time how long the command takes
298 298 --profile print command execution profile
299 299 --version output version information and exit
300 300 -h --help display help and exit
301 301 %% test help option with version option
302 302 Mercurial Distributed SCM (version xxx)
303 303
304 304 Copyright (C) 2005-2010 Matt Mackall <mpm@selenic.com> and others
305 305 This is free software; see the source for copying conditions. There is NO
306 306 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
307 307
308 308 hg add [OPTION]... [FILE]...
309 309
310 310 add the specified files on the next commit
311 311
312 312 Schedule files to be version controlled and added to the repository.
313 313
314 314 The files will be added to the repository at the next commit. To undo an
315 315 add before that, see hg forget.
316 316
317 317 If no names are given, add all files to the repository.
318 318
319 319 use "hg -v help add" to show verbose help
320 320
321 321 options:
322 322
323 323 -I --include include names matching the given patterns
324 324 -X --exclude exclude names matching the given patterns
325 325 -n --dry-run do not perform actions, just print output
326 326
327 327 use "hg -v help add" to show global options
328 328 hg add: option --skjdfks not recognized
329 329 hg add [OPTION]... [FILE]...
330 330
331 331 add the specified files on the next commit
332 332
333 333 Schedule files to be version controlled and added to the repository.
334 334
335 335 The files will be added to the repository at the next commit. To undo an
336 336 add before that, see hg forget.
337 337
338 338 If no names are given, add all files to the repository.
339 339
340 340 use "hg -v help add" to show verbose help
341 341
342 342 options:
343 343
344 344 -I --include include names matching the given patterns
345 345 -X --exclude exclude names matching the given patterns
346 346 -n --dry-run do not perform actions, just print output
347 347
348 348 use "hg -v help add" to show global options
349 349 %% test ambiguous command help
350 350 list of commands:
351 351
352 352 add add the specified files on the next commit
353 353 addremove add all new files, delete all missing files
354 354
355 355 use "hg -v help ad" to show aliases and global options
356 356 %% test command without options
357 357 hg verify
358 358
359 359 verify the integrity of the repository
360 360
361 361 Verify the integrity of the current repository.
362 362
363 363 This will perform an extensive check of the repository's integrity,
364 364 validating the hashes and checksums of each entry in the changelog,
365 365 manifest, and tracked files, as well as the integrity of their crosslinks
366 366 and indices.
367 367
368 368 use "hg -v help verify" to show global options
369 369 hg diff [OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...
370 370
371 371 diff repository (or selected files)
372 372
373 373 Show differences between revisions for the specified files.
374 374
375 375 Differences between files are shown using the unified diff format.
376 376
377 377 NOTE: diff may generate unexpected results for merges, as it will default
378 378 to comparing against the working directory's first parent changeset if no
379 379 revisions are specified.
380 380
381 381 When two revision arguments are given, then changes are shown between
382 382 those revisions. If only one revision is specified then that revision is
383 383 compared to the working directory, and, when no revisions are specified,
384 384 the working directory files are compared to its parent.
385 385
386 386 Alternatively you can specify -c/--change with a revision to see the
387 387 changes in that changeset relative to its first parent.
388 388
389 389 Without the -a/--text option, diff will avoid generating diffs of files it
390 390 detects as binary. With -a, diff will generate a diff anyway, probably
391 391 with undesirable results.
392 392
393 393 Use the -g/--git option to generate diffs in the git extended diff format.
394 For more information, read 'hg help diffs'.
394 For more information, read "hg help diffs".
395 395
396 396 options:
397 397
398 398 -r --rev revision
399 399 -c --change change made by revision
400 400 -a --text treat all files as text
401 401 -g --git use git extended diff format
402 402 --nodates omit dates from diff headers
403 403 -p --show-function show which function each change is in
404 404 --reverse produce a diff that undoes the changes
405 405 -w --ignore-all-space ignore white space when comparing lines
406 406 -b --ignore-space-change ignore changes in the amount of white space
407 407 -B --ignore-blank-lines ignore changes whose lines are all blank
408 408 -U --unified number of lines of context to show
409 409 --stat output diffstat-style summary of changes
410 410 -I --include include names matching the given patterns
411 411 -X --exclude exclude names matching the given patterns
412 412
413 413 use "hg -v help diff" to show global options
414 414 hg status [OPTION]... [FILE]...
415 415
416 416 aliases: st
417 417
418 418 show changed files in the working directory
419 419
420 420 Show status of files in the repository. If names are given, only files
421 421 that match are shown. Files that are clean or ignored or the source of a
422 422 copy/move operation, are not listed unless -c/--clean, -i/--ignored,
423 423 -C/--copies or -A/--all are given. Unless options described with "show
424 424 only ..." are given, the options -mardu are used.
425 425
426 426 Option -q/--quiet hides untracked (unknown and ignored) files unless
427 427 explicitly requested with -u/--unknown or -i/--ignored.
428 428
429 429 NOTE: status may appear to disagree with diff if permissions have changed
430 430 or a merge has occurred. The standard diff format does not report
431 431 permission changes and diff only reports changes relative to one merge
432 432 parent.
433 433
434 434 If one revision is given, it is used as the base revision. If two
435 435 revisions are given, the differences between them are shown. The --change
436 436 option can also be used as a shortcut to list the changed files of a
437 437 revision from its first parent.
438 438
439 439 The codes used to show the status of files are:
440 440
441 441 M = modified
442 442 A = added
443 443 R = removed
444 444 C = clean
445 445 ! = missing (deleted by non-hg command, but still tracked)
446 446 ? = not tracked
447 447 I = ignored
448 448 = origin of the previous file listed as A (added)
449 449
450 450 options:
451 451
452 452 -A --all show status of all files
453 453 -m --modified show only modified files
454 454 -a --added show only added files
455 455 -r --removed show only removed files
456 456 -d --deleted show only deleted (but tracked) files
457 457 -c --clean show only files without changes
458 458 -u --unknown show only unknown (not tracked) files
459 459 -i --ignored show only ignored files
460 460 -n --no-status hide status prefix
461 461 -C --copies show source of copied files
462 462 -0 --print0 end filenames with NUL, for use with xargs
463 463 --rev show difference from revision
464 464 --change list the changed files of a revision
465 465 -I --include include names matching the given patterns
466 466 -X --exclude exclude names matching the given patterns
467 467
468 468 use "hg -v help status" to show global options
469 469 hg status [OPTION]... [FILE]...
470 470
471 471 show changed files in the working directory
472 472 hg: unknown command 'foo'
473 473 Mercurial Distributed SCM
474 474
475 475 basic commands:
476 476
477 477 add add the specified files on the next commit
478 478 annotate show changeset information by line for each file
479 479 clone make a copy of an existing repository
480 480 commit commit the specified files or all outstanding changes
481 481 diff diff repository (or selected files)
482 482 export dump the header and diffs for one or more changesets
483 483 forget forget the specified files on the next commit
484 484 init create a new repository in the given directory
485 485 log show revision history of entire repository or files
486 486 merge merge working directory with another revision
487 487 pull pull changes from the specified source
488 488 push push changes to the specified destination
489 489 remove remove the specified files on the next commit
490 490 serve start stand-alone webserver
491 491 status show changed files in the working directory
492 492 summary summarize working directory state
493 493 update update working directory (or switch revisions)
494 494
495 495 use "hg help" for the full list of commands or "hg -v" for details
496 496 hg: unknown command 'skjdfks'
497 497 Mercurial Distributed SCM
498 498
499 499 basic commands:
500 500
501 501 add add the specified files on the next commit
502 502 annotate show changeset information by line for each file
503 503 clone make a copy of an existing repository
504 504 commit commit the specified files or all outstanding changes
505 505 diff diff repository (or selected files)
506 506 export dump the header and diffs for one or more changesets
507 507 forget forget the specified files on the next commit
508 508 init create a new repository in the given directory
509 509 log show revision history of entire repository or files
510 510 merge merge working directory with another revision
511 511 pull pull changes from the specified source
512 512 push push changes to the specified destination
513 513 remove remove the specified files on the next commit
514 514 serve start stand-alone webserver
515 515 status show changed files in the working directory
516 516 summary summarize working directory state
517 517 update update working directory (or switch revisions)
518 518
519 519 use "hg help" for the full list of commands or "hg -v" for details
520 520 %% test command with no help text
521 521 hg nohelp
522 522
523 523 (no help text available)
524 524
525 525 use "hg -v help nohelp" to show global options
526 526 %% test that default list of commands omits extension commands
527 527 Mercurial Distributed SCM
528 528
529 529 list of commands:
530 530
531 531 add add the specified files on the next commit
532 532 addremove add all new files, delete all missing files
533 533 annotate show changeset information by line for each file
534 534 archive create an unversioned archive of a repository revision
535 535 backout reverse effect of earlier changeset
536 536 bisect subdivision search of changesets
537 537 branch set or show the current branch name
538 538 branches list repository named branches
539 539 bundle create a changegroup file
540 540 cat output the current or given revision of files
541 541 clone make a copy of an existing repository
542 542 commit commit the specified files or all outstanding changes
543 543 copy mark files as copied for the next commit
544 544 diff diff repository (or selected files)
545 545 export dump the header and diffs for one or more changesets
546 546 forget forget the specified files on the next commit
547 547 grep search for a pattern in specified files and revisions
548 548 heads show current repository heads or show branch heads
549 549 help show help for a given topic or a help overview
550 550 identify identify the working copy or specified revision
551 551 import import an ordered set of patches
552 552 incoming show new changesets found in source
553 553 init create a new repository in the given directory
554 554 locate locate files matching specific patterns
555 555 log show revision history of entire repository or files
556 556 manifest output the current or given revision of the project manifest
557 557 merge merge working directory with another revision
558 558 outgoing show changesets not found in the destination
559 559 parents show the parents of the working directory or revision
560 560 paths show aliases for remote repositories
561 561 pull pull changes from the specified source
562 562 push push changes to the specified destination
563 563 recover roll back an interrupted transaction
564 564 remove remove the specified files on the next commit
565 565 rename rename files; equivalent of copy + remove
566 566 resolve various operations to help finish a merge
567 567 revert restore individual files or directories to an earlier state
568 568 rollback roll back the last transaction (dangerous)
569 569 root print the root (top) of the current working directory
570 570 serve start stand-alone webserver
571 571 showconfig show combined config settings from all hgrc files
572 572 status show changed files in the working directory
573 573 summary summarize working directory state
574 574 tag add one or more tags for the current or given revision
575 575 tags list repository tags
576 576 tip show the tip revision
577 577 unbundle apply one or more changegroup files
578 578 update update working directory (or switch revisions)
579 579 verify verify the integrity of the repository
580 580 version output version and copyright information
581 581
582 582 enabled extensions:
583 583
584 584 helpext (no help text available)
585 585
586 586 additional help topics:
587 587
588 588 config Configuration Files
589 589 dates Date Formats
590 590 patterns File Name Patterns
591 591 environment Environment Variables
592 592 revisions Specifying Single Revisions
593 593 multirevs Specifying Multiple Revisions
594 594 diffs Diff Formats
595 595 templating Template Usage
596 596 urls URL Paths
597 597 extensions Using additional features
598 598
599 599 use "hg -v help" to show aliases and global options
600 600 %% test list of commands with command with no help text
601 601 helpext extension - no help text available
602 602
603 603 list of commands:
604 604
605 605 nohelp (no help text available)
606 606
607 607 use "hg -v help helpext" to show aliases and global options
608 608 %% test a help topic
609 609 Specifying Single Revisions
610 610
611 611 Mercurial supports several ways to specify individual revisions.
612 612
613 613 A plain integer is treated as a revision number. Negative integers are
614 614 treated as sequential offsets from the tip, with -1 denoting the tip, -2
615 615 denoting the revision prior to the tip, and so forth.
616 616
617 617 A 40-digit hexadecimal string is treated as a unique revision identifier.
618 618
619 619 A hexadecimal string less than 40 characters long is treated as a unique
620 620 revision identifier and is referred to as a short-form identifier. A
621 621 short-form identifier is only valid if it is the prefix of exactly one
622 622 full-length identifier.
623 623
624 624 Any other string is treated as a tag or branch name. A tag name is a
625 625 symbolic name associated with a revision identifier. A branch name denotes
626 626 the tipmost revision of that branch. Tag and branch names must not contain
627 627 the ":" character.
628 628
629 629 The reserved name "tip" is a special tag that always identifies the most
630 630 recent revision.
631 631
632 632 The reserved name "null" indicates the null revision. This is the revision
633 633 of an empty repository, and the parent of revision 0.
634 634
635 635 The reserved name "." indicates the working directory parent. If no
636 636 working directory is checked out, it is equivalent to null. If an
637 637 uncommitted merge is in progress, "." is the revision of the first parent.
@@ -1,218 +1,218
1 1 % help (no mq, so no qrecord)
2 2 hg: unknown command 'qrecord'
3 3 Mercurial Distributed SCM
4 4
5 5 basic commands:
6 6
7 7 add add the specified files on the next commit
8 8 annotate show changeset information by line for each file
9 9 clone make a copy of an existing repository
10 10 commit commit the specified files or all outstanding changes
11 11 diff diff repository (or selected files)
12 12 export dump the header and diffs for one or more changesets
13 13 forget forget the specified files on the next commit
14 14 init create a new repository in the given directory
15 15 log show revision history of entire repository or files
16 16 merge merge working directory with another revision
17 17 pull pull changes from the specified source
18 18 push push changes to the specified destination
19 19 remove remove the specified files on the next commit
20 20 serve start stand-alone webserver
21 21 status show changed files in the working directory
22 22 summary summarize working directory state
23 23 update update working directory (or switch revisions)
24 24
25 25 use "hg help" for the full list of commands or "hg -v" for details
26 26 % help (mq present)
27 27 hg qrecord [OPTION]... PATCH [FILE]...
28 28
29 29 interactively record a new patch
30 30
31 See 'hg help qnew' & 'hg help record' for more information and usage.
31 See "hg help qnew" & "hg help record" for more information and usage.
32 32
33 33 options:
34 34
35 35 -e --edit edit commit message
36 36 -g --git use git extended diff format
37 37 -U --currentuser add "From: <current user>" to patch
38 38 -u --user add "From: <given user>" to patch
39 39 -D --currentdate add "Date: <current date>" to patch
40 40 -d --date add "Date: <given date>" to patch
41 41 -I --include include names matching the given patterns
42 42 -X --exclude exclude names matching the given patterns
43 43 -m --message use <text> as commit message
44 44 -l --logfile read commit message from <file>
45 45
46 46 use "hg -v help qrecord" to show global options
47 47 % base commit
48 48 % changing files
49 49 % whole diff
50 50 diff -r 1057167b20ef 1.txt
51 51 --- a/1.txt
52 52 +++ b/1.txt
53 53 @@ -1,5 +1,5 @@
54 54 1
55 55 -2
56 56 +2 2
57 57 3
58 58 -4
59 59 +4 4
60 60 5
61 61 diff -r 1057167b20ef 2.txt
62 62 --- a/2.txt
63 63 +++ b/2.txt
64 64 @@ -1,5 +1,5 @@
65 65 a
66 66 -b
67 67 +b b
68 68 c
69 69 d
70 70 e
71 71 diff -r 1057167b20ef dir/a.txt
72 72 --- a/dir/a.txt
73 73 +++ b/dir/a.txt
74 74 @@ -1,4 +1,4 @@
75 75 -hello world
76 76 +hello world!
77 77
78 78 someone
79 79 up
80 80 % qrecord a.patch
81 81 diff --git a/1.txt b/1.txt
82 82 2 hunks, 4 lines changed
83 83 examine changes to '1.txt'? [Ynsfdaq?]
84 84 @@ -1,3 +1,3 @@
85 85 1
86 86 -2
87 87 +2 2
88 88 3
89 89 record change 1/6 to '1.txt'? [Ynsfdaq?]
90 90 @@ -3,3 +3,3 @@
91 91 3
92 92 -4
93 93 +4 4
94 94 5
95 95 record change 2/6 to '1.txt'? [Ynsfdaq?]
96 96 diff --git a/2.txt b/2.txt
97 97 1 hunks, 2 lines changed
98 98 examine changes to '2.txt'? [Ynsfdaq?]
99 99 @@ -1,5 +1,5 @@
100 100 a
101 101 -b
102 102 +b b
103 103 c
104 104 d
105 105 e
106 106 record change 4/6 to '2.txt'? [Ynsfdaq?]
107 107 diff --git a/dir/a.txt b/dir/a.txt
108 108 1 hunks, 2 lines changed
109 109 examine changes to 'dir/a.txt'? [Ynsfdaq?]
110 110
111 111 % after qrecord a.patch 'tip'
112 112 changeset: 1:5d1ca63427ee
113 113 tag: qtip
114 114 tag: tip
115 115 tag: a.patch
116 116 tag: qbase
117 117 user: test
118 118 date: Thu Jan 01 00:00:00 1970 +0000
119 119 summary: aaa
120 120
121 121 diff -r 1057167b20ef -r 5d1ca63427ee 1.txt
122 122 --- a/1.txt Thu Jan 01 00:00:00 1970 +0000
123 123 +++ b/1.txt Thu Jan 01 00:00:00 1970 +0000
124 124 @@ -1,5 +1,5 @@
125 125 1
126 126 -2
127 127 +2 2
128 128 3
129 129 4
130 130 5
131 131 diff -r 1057167b20ef -r 5d1ca63427ee 2.txt
132 132 --- a/2.txt Thu Jan 01 00:00:00 1970 +0000
133 133 +++ b/2.txt Thu Jan 01 00:00:00 1970 +0000
134 134 @@ -1,5 +1,5 @@
135 135 a
136 136 -b
137 137 +b b
138 138 c
139 139 d
140 140 e
141 141
142 142
143 143 % after qrecord a.patch 'diff'
144 144 diff -r 5d1ca63427ee 1.txt
145 145 --- a/1.txt
146 146 +++ b/1.txt
147 147 @@ -1,5 +1,5 @@
148 148 1
149 149 2 2
150 150 3
151 151 -4
152 152 +4 4
153 153 5
154 154 diff -r 5d1ca63427ee dir/a.txt
155 155 --- a/dir/a.txt
156 156 +++ b/dir/a.txt
157 157 @@ -1,4 +1,4 @@
158 158 -hello world
159 159 +hello world!
160 160
161 161 someone
162 162 up
163 163 % qrecord b.patch
164 164 diff --git a/1.txt b/1.txt
165 165 1 hunks, 2 lines changed
166 166 examine changes to '1.txt'? [Ynsfdaq?]
167 167 @@ -1,5 +1,5 @@
168 168 1
169 169 2 2
170 170 3
171 171 -4
172 172 +4 4
173 173 5
174 174 record change 1/3 to '1.txt'? [Ynsfdaq?]
175 175 diff --git a/dir/a.txt b/dir/a.txt
176 176 1 hunks, 2 lines changed
177 177 examine changes to 'dir/a.txt'? [Ynsfdaq?]
178 178 @@ -1,4 +1,4 @@
179 179 -hello world
180 180 +hello world!
181 181
182 182 someone
183 183 up
184 184 record change 3/3 to 'dir/a.txt'? [Ynsfdaq?]
185 185
186 186 % after qrecord b.patch 'tip'
187 187 changeset: 2:b056198bf878
188 188 tag: qtip
189 189 tag: tip
190 190 tag: b.patch
191 191 user: test
192 192 date: Thu Jan 01 00:00:00 1970 +0000
193 193 summary: bbb
194 194
195 195 diff -r 5d1ca63427ee -r b056198bf878 1.txt
196 196 --- a/1.txt Thu Jan 01 00:00:00 1970 +0000
197 197 +++ b/1.txt Thu Jan 01 00:00:00 1970 +0000
198 198 @@ -1,5 +1,5 @@
199 199 1
200 200 2 2
201 201 3
202 202 -4
203 203 +4 4
204 204 5
205 205 diff -r 5d1ca63427ee -r b056198bf878 dir/a.txt
206 206 --- a/dir/a.txt Thu Jan 01 00:00:00 1970 +0000
207 207 +++ b/dir/a.txt Thu Jan 01 00:00:00 1970 +0000
208 208 @@ -1,4 +1,4 @@
209 209 -hello world
210 210 +hello world!
211 211
212 212 someone
213 213 up
214 214
215 215
216 216 % after qrecord b.patch 'diff'
217 217
218 218 % --- end ---
@@ -1,654 +1,654
1 1 % help
2 2 hg record [OPTION]... [FILE]...
3 3
4 4 interactively select changes to commit
5 5
6 6 If a list of files is omitted, all changes reported by "hg status" will be
7 7 candidates for recording.
8 8
9 See 'hg help dates' for a list of formats valid for -d/--date.
9 See "hg help dates" for a list of formats valid for -d/--date.
10 10
11 11 You will be prompted for whether to record changes to each modified file,
12 12 and for files with multiple changes, for each change to use. For each
13 13 query, the following responses are possible:
14 14
15 15 y - record this change
16 16 n - skip this change
17 17
18 18 s - skip remaining changes to this file
19 19 f - record remaining changes to this file
20 20
21 21 d - done, skip remaining changes and files
22 22 a - record all changes to all remaining files
23 23 q - quit, recording no changes
24 24
25 25 ? - display help
26 26
27 27 options:
28 28
29 29 -A --addremove mark new/missing files as added/removed before committing
30 30 --close-branch mark a branch as closed, hiding it from the branch list
31 31 -I --include include names matching the given patterns
32 32 -X --exclude exclude names matching the given patterns
33 33 -m --message use <text> as commit message
34 34 -l --logfile read commit message from <file>
35 35 -d --date record datecode as commit date
36 36 -u --user record the specified user as committer
37 37
38 38 use "hg -v help record" to show global options
39 39 % select no files
40 40 diff --git a/empty-rw b/empty-rw
41 41 new file mode 100644
42 42 examine changes to 'empty-rw'? [Ynsfdaq?]
43 43 no changes to record
44 44
45 45 changeset: -1:000000000000
46 46 tag: tip
47 47 user:
48 48 date: Thu Jan 01 00:00:00 1970 +0000
49 49
50 50
51 51 % select files but no hunks
52 52 diff --git a/empty-rw b/empty-rw
53 53 new file mode 100644
54 54 examine changes to 'empty-rw'? [Ynsfdaq?]
55 55 abort: empty commit message
56 56
57 57 changeset: -1:000000000000
58 58 tag: tip
59 59 user:
60 60 date: Thu Jan 01 00:00:00 1970 +0000
61 61
62 62
63 63 % record empty file
64 64 diff --git a/empty-rw b/empty-rw
65 65 new file mode 100644
66 66 examine changes to 'empty-rw'? [Ynsfdaq?]
67 67
68 68 changeset: 0:c0708cf4e46e
69 69 tag: tip
70 70 user: test
71 71 date: Thu Jan 01 00:00:00 1970 +0000
72 72 summary: empty
73 73
74 74
75 75 % summary shows we updated to the new cset
76 76 parent: 0:c0708cf4e46e tip
77 77 empty
78 78 branch: default
79 79 commit: (clean)
80 80 update: (current)
81 81
82 82 % rename empty file
83 83 diff --git a/empty-rw b/empty-rename
84 84 rename from empty-rw
85 85 rename to empty-rename
86 86 examine changes to 'empty-rw' and 'empty-rename'? [Ynsfdaq?]
87 87
88 88 changeset: 1:d695e8dcb197
89 89 tag: tip
90 90 user: test
91 91 date: Thu Jan 01 00:00:01 1970 +0000
92 92 summary: rename
93 93
94 94
95 95 % copy empty file
96 96 diff --git a/empty-rename b/empty-copy
97 97 copy from empty-rename
98 98 copy to empty-copy
99 99 examine changes to 'empty-rename' and 'empty-copy'? [Ynsfdaq?]
100 100
101 101 changeset: 2:1d4b90bea524
102 102 tag: tip
103 103 user: test
104 104 date: Thu Jan 01 00:00:02 1970 +0000
105 105 summary: copy
106 106
107 107
108 108 % delete empty file
109 109 diff --git a/empty-copy b/empty-copy
110 110 deleted file mode 100644
111 111 examine changes to 'empty-copy'? [Ynsfdaq?]
112 112
113 113 changeset: 3:b39a238f01a1
114 114 tag: tip
115 115 user: test
116 116 date: Thu Jan 01 00:00:03 1970 +0000
117 117 summary: delete
118 118
119 119
120 120 % add binary file
121 121 1 changesets found
122 122 diff --git a/tip.bundle b/tip.bundle
123 123 new file mode 100644
124 124 this is a binary file
125 125 examine changes to 'tip.bundle'? [Ynsfdaq?]
126 126
127 127 changeset: 4:ad816da3711e
128 128 tag: tip
129 129 user: test
130 130 date: Thu Jan 01 00:00:04 1970 +0000
131 131 summary: binary
132 132
133 133 diff -r b39a238f01a1 -r ad816da3711e tip.bundle
134 134 Binary file tip.bundle has changed
135 135
136 136 % change binary file
137 137 1 changesets found
138 138 diff --git a/tip.bundle b/tip.bundle
139 139 this modifies a binary file (all or nothing)
140 140 examine changes to 'tip.bundle'? [Ynsfdaq?]
141 141
142 142 changeset: 5:dccd6f3eb485
143 143 tag: tip
144 144 user: test
145 145 date: Thu Jan 01 00:00:05 1970 +0000
146 146 summary: binary-change
147 147
148 148 diff -r ad816da3711e -r dccd6f3eb485 tip.bundle
149 149 Binary file tip.bundle has changed
150 150
151 151 % rename and change binary file
152 152 1 changesets found
153 153 diff --git a/tip.bundle b/top.bundle
154 154 rename from tip.bundle
155 155 rename to top.bundle
156 156 this modifies a binary file (all or nothing)
157 157 examine changes to 'tip.bundle' and 'top.bundle'? [Ynsfdaq?]
158 158
159 159 changeset: 6:7fa44105f5b3
160 160 tag: tip
161 161 user: test
162 162 date: Thu Jan 01 00:00:06 1970 +0000
163 163 summary: binary-change-rename
164 164
165 165 diff -r dccd6f3eb485 -r 7fa44105f5b3 tip.bundle
166 166 Binary file tip.bundle has changed
167 167 diff -r dccd6f3eb485 -r 7fa44105f5b3 top.bundle
168 168 Binary file top.bundle has changed
169 169
170 170 % add plain file
171 171 diff --git a/plain b/plain
172 172 new file mode 100644
173 173 examine changes to 'plain'? [Ynsfdaq?]
174 174
175 175 changeset: 7:11fb457c1be4
176 176 tag: tip
177 177 user: test
178 178 date: Thu Jan 01 00:00:07 1970 +0000
179 179 summary: plain
180 180
181 181 diff -r 7fa44105f5b3 -r 11fb457c1be4 plain
182 182 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
183 183 +++ b/plain Thu Jan 01 00:00:07 1970 +0000
184 184 @@ -0,0 +1,10 @@
185 185 +1
186 186 +2
187 187 +3
188 188 +4
189 189 +5
190 190 +6
191 191 +7
192 192 +8
193 193 +9
194 194 +10
195 195
196 196 % modify end of plain file
197 197 diff --git a/plain b/plain
198 198 1 hunks, 1 lines changed
199 199 examine changes to 'plain'? [Ynsfdaq?]
200 200 @@ -8,3 +8,4 @@
201 201 8
202 202 9
203 203 10
204 204 +11
205 205 record this change to 'plain'? [Ynsfdaq?]
206 206 % modify end of plain file, no EOL
207 207 diff --git a/plain b/plain
208 208 1 hunks, 1 lines changed
209 209 examine changes to 'plain'? [Ynsfdaq?]
210 210 @@ -9,3 +9,4 @@
211 211 9
212 212 10
213 213 11
214 214 +7264f99c5f5ff3261504828afa4fb4d406c3af54
215 215 \ No newline at end of file
216 216 record this change to 'plain'? [Ynsfdaq?]
217 217 % modify end of plain file, add EOL
218 218 diff --git a/plain b/plain
219 219 1 hunks, 2 lines changed
220 220 examine changes to 'plain'? [Ynsfdaq?]
221 221 @@ -9,4 +9,4 @@
222 222 9
223 223 10
224 224 11
225 225 -7264f99c5f5ff3261504828afa4fb4d406c3af54
226 226 \ No newline at end of file
227 227 +7264f99c5f5ff3261504828afa4fb4d406c3af54
228 228 record this change to 'plain'? [Ynsfdaq?]
229 229 % modify beginning, trim end, record both
230 230 diff --git a/plain b/plain
231 231 2 hunks, 4 lines changed
232 232 examine changes to 'plain'? [Ynsfdaq?]
233 233 @@ -1,4 +1,4 @@
234 234 -1
235 235 +2
236 236 2
237 237 3
238 238 4
239 239 record change 1/2 to 'plain'? [Ynsfdaq?]
240 240 @@ -8,5 +8,3 @@
241 241 8
242 242 9
243 243 10
244 244 -11
245 245 -7264f99c5f5ff3261504828afa4fb4d406c3af54
246 246 record change 2/2 to 'plain'? [Ynsfdaq?]
247 247
248 248 changeset: 11:efca65c9b09e
249 249 tag: tip
250 250 user: test
251 251 date: Thu Jan 01 00:00:10 1970 +0000
252 252 summary: begin-and-end
253 253
254 254 diff -r cd07d48e8cbe -r efca65c9b09e plain
255 255 --- a/plain Thu Jan 01 00:00:10 1970 +0000
256 256 +++ b/plain Thu Jan 01 00:00:10 1970 +0000
257 257 @@ -1,4 +1,4 @@
258 258 -1
259 259 +2
260 260 2
261 261 3
262 262 4
263 263 @@ -8,5 +8,3 @@
264 264 8
265 265 9
266 266 10
267 267 -11
268 268 -7264f99c5f5ff3261504828afa4fb4d406c3af54
269 269
270 270 % trim beginning, modify end
271 271 % record end
272 272 diff --git a/plain b/plain
273 273 2 hunks, 5 lines changed
274 274 examine changes to 'plain'? [Ynsfdaq?]
275 275 @@ -1,9 +1,6 @@
276 276 -2
277 277 -2
278 278 -3
279 279 4
280 280 5
281 281 6
282 282 7
283 283 8
284 284 9
285 285 record change 1/2 to 'plain'? [Ynsfdaq?]
286 286 @@ -4,7 +1,7 @@
287 287 4
288 288 5
289 289 6
290 290 7
291 291 8
292 292 9
293 293 -10
294 294 +10.new
295 295 record change 2/2 to 'plain'? [Ynsfdaq?]
296 296
297 297 changeset: 12:7d1e66983c15
298 298 tag: tip
299 299 user: test
300 300 date: Thu Jan 01 00:00:11 1970 +0000
301 301 summary: end-only
302 302
303 303 diff -r efca65c9b09e -r 7d1e66983c15 plain
304 304 --- a/plain Thu Jan 01 00:00:10 1970 +0000
305 305 +++ b/plain Thu Jan 01 00:00:11 1970 +0000
306 306 @@ -7,4 +7,4 @@
307 307 7
308 308 8
309 309 9
310 310 -10
311 311 +10.new
312 312
313 313 % record beginning
314 314 diff --git a/plain b/plain
315 315 1 hunks, 3 lines changed
316 316 examine changes to 'plain'? [Ynsfdaq?]
317 317 @@ -1,6 +1,3 @@
318 318 -2
319 319 -2
320 320 -3
321 321 4
322 322 5
323 323 6
324 324 record this change to 'plain'? [Ynsfdaq?]
325 325
326 326 changeset: 13:a09fc62a0e61
327 327 tag: tip
328 328 user: test
329 329 date: Thu Jan 01 00:00:12 1970 +0000
330 330 summary: begin-only
331 331
332 332 diff -r 7d1e66983c15 -r a09fc62a0e61 plain
333 333 --- a/plain Thu Jan 01 00:00:11 1970 +0000
334 334 +++ b/plain Thu Jan 01 00:00:12 1970 +0000
335 335 @@ -1,6 +1,3 @@
336 336 -2
337 337 -2
338 338 -3
339 339 4
340 340 5
341 341 6
342 342
343 343 % add to beginning, trim from end
344 344 % record end
345 345 diff --git a/plain b/plain
346 346 2 hunks, 4 lines changed
347 347 examine changes to 'plain'? [Ynsfdaq?]
348 348 @@ -1,6 +1,9 @@
349 349 +1
350 350 +2
351 351 +3
352 352 4
353 353 5
354 354 6
355 355 7
356 356 8
357 357 9
358 358 record change 1/2 to 'plain'? [Ynsfdaq?]
359 359 @@ -1,7 +4,6 @@
360 360 4
361 361 5
362 362 6
363 363 7
364 364 8
365 365 9
366 366 -10.new
367 367 record change 2/2 to 'plain'? [Ynsfdaq?]
368 368 % add to beginning, middle, end
369 369 % record beginning, middle
370 370 diff --git a/plain b/plain
371 371 3 hunks, 7 lines changed
372 372 examine changes to 'plain'? [Ynsfdaq?]
373 373 @@ -1,2 +1,5 @@
374 374 +1
375 375 +2
376 376 +3
377 377 4
378 378 5
379 379 record change 1/3 to 'plain'? [Ynsfdaq?]
380 380 @@ -1,6 +4,8 @@
381 381 4
382 382 5
383 383 +5.new
384 384 +5.reallynew
385 385 6
386 386 7
387 387 8
388 388 9
389 389 record change 2/3 to 'plain'? [Ynsfdaq?]
390 390 @@ -3,4 +8,6 @@
391 391 6
392 392 7
393 393 8
394 394 9
395 395 +10
396 396 +11
397 397 record change 3/3 to 'plain'? [Ynsfdaq?]
398 398
399 399 changeset: 15:7d137997f3a6
400 400 tag: tip
401 401 user: test
402 402 date: Thu Jan 01 00:00:14 1970 +0000
403 403 summary: middle-only
404 404
405 405 diff -r c0b8e5fb0be6 -r 7d137997f3a6 plain
406 406 --- a/plain Thu Jan 01 00:00:13 1970 +0000
407 407 +++ b/plain Thu Jan 01 00:00:14 1970 +0000
408 408 @@ -1,5 +1,10 @@
409 409 +1
410 410 +2
411 411 +3
412 412 4
413 413 5
414 414 +5.new
415 415 +5.reallynew
416 416 6
417 417 7
418 418 8
419 419
420 420 % record end
421 421 diff --git a/plain b/plain
422 422 1 hunks, 2 lines changed
423 423 examine changes to 'plain'? [Ynsfdaq?]
424 424 @@ -9,3 +9,5 @@
425 425 7
426 426 8
427 427 9
428 428 +10
429 429 +11
430 430 record this change to 'plain'? [Ynsfdaq?]
431 431
432 432 changeset: 16:4959e3ff13eb
433 433 tag: tip
434 434 user: test
435 435 date: Thu Jan 01 00:00:15 1970 +0000
436 436 summary: end-only
437 437
438 438 diff -r 7d137997f3a6 -r 4959e3ff13eb plain
439 439 --- a/plain Thu Jan 01 00:00:14 1970 +0000
440 440 +++ b/plain Thu Jan 01 00:00:15 1970 +0000
441 441 @@ -9,3 +9,5 @@
442 442 7
443 443 8
444 444 9
445 445 +10
446 446 +11
447 447
448 448 adding subdir/a
449 449 diff --git a/subdir/a b/subdir/a
450 450 1 hunks, 1 lines changed
451 451 examine changes to 'subdir/a'? [Ynsfdaq?]
452 452 @@ -1,1 +1,2 @@
453 453 a
454 454 +a
455 455 record this change to 'subdir/a'? [Ynsfdaq?]
456 456
457 457 changeset: 18:40698cd490b2
458 458 tag: tip
459 459 user: test
460 460 date: Thu Jan 01 00:00:16 1970 +0000
461 461 summary: subdir-change
462 462
463 463 diff -r 661eacdc08b9 -r 40698cd490b2 subdir/a
464 464 --- a/subdir/a Thu Jan 01 00:00:16 1970 +0000
465 465 +++ b/subdir/a Thu Jan 01 00:00:16 1970 +0000
466 466 @@ -1,1 +1,2 @@
467 467 a
468 468 +a
469 469
470 470 % help, quit
471 471 diff --git a/subdir/f1 b/subdir/f1
472 472 1 hunks, 1 lines changed
473 473 examine changes to 'subdir/f1'? [Ynsfdaq?]
474 474 y - record this change
475 475 n - skip this change
476 476 s - skip remaining changes to this file
477 477 f - record remaining changes to this file
478 478 d - done, skip remaining changes and files
479 479 a - record all changes to all remaining files
480 480 q - quit, recording no changes
481 481 ? - display help
482 482 examine changes to 'subdir/f1'? [Ynsfdaq?]
483 483 abort: user quit
484 484 % skip
485 485 diff --git a/subdir/f1 b/subdir/f1
486 486 1 hunks, 1 lines changed
487 487 examine changes to 'subdir/f1'? [Ynsfdaq?]
488 488 diff --git a/subdir/f2 b/subdir/f2
489 489 1 hunks, 1 lines changed
490 490 examine changes to 'subdir/f2'? [Ynsfdaq?] abort: response expected
491 491 % no
492 492 diff --git a/subdir/f1 b/subdir/f1
493 493 1 hunks, 1 lines changed
494 494 examine changes to 'subdir/f1'? [Ynsfdaq?]
495 495 diff --git a/subdir/f2 b/subdir/f2
496 496 1 hunks, 1 lines changed
497 497 examine changes to 'subdir/f2'? [Ynsfdaq?] abort: response expected
498 498 % f, quit
499 499 diff --git a/subdir/f1 b/subdir/f1
500 500 1 hunks, 1 lines changed
501 501 examine changes to 'subdir/f1'? [Ynsfdaq?]
502 502 diff --git a/subdir/f2 b/subdir/f2
503 503 1 hunks, 1 lines changed
504 504 examine changes to 'subdir/f2'? [Ynsfdaq?]
505 505 abort: user quit
506 506 % s, all
507 507 diff --git a/subdir/f1 b/subdir/f1
508 508 1 hunks, 1 lines changed
509 509 examine changes to 'subdir/f1'? [Ynsfdaq?]
510 510 diff --git a/subdir/f2 b/subdir/f2
511 511 1 hunks, 1 lines changed
512 512 examine changes to 'subdir/f2'? [Ynsfdaq?]
513 513
514 514 changeset: 20:d2d8c25276a8
515 515 tag: tip
516 516 user: test
517 517 date: Thu Jan 01 00:00:18 1970 +0000
518 518 summary: x
519 519
520 520 diff -r 25eb2a7694fb -r d2d8c25276a8 subdir/f2
521 521 --- a/subdir/f2 Thu Jan 01 00:00:17 1970 +0000
522 522 +++ b/subdir/f2 Thu Jan 01 00:00:18 1970 +0000
523 523 @@ -1,1 +1,2 @@
524 524 b
525 525 +b
526 526
527 527 % f
528 528 diff --git a/subdir/f1 b/subdir/f1
529 529 1 hunks, 1 lines changed
530 530 examine changes to 'subdir/f1'? [Ynsfdaq?]
531 531
532 532 changeset: 21:1013f51ce32f
533 533 tag: tip
534 534 user: test
535 535 date: Thu Jan 01 00:00:19 1970 +0000
536 536 summary: y
537 537
538 538 diff -r d2d8c25276a8 -r 1013f51ce32f subdir/f1
539 539 --- a/subdir/f1 Thu Jan 01 00:00:18 1970 +0000
540 540 +++ b/subdir/f1 Thu Jan 01 00:00:19 1970 +0000
541 541 @@ -1,1 +1,2 @@
542 542 a
543 543 +a
544 544
545 545 % preserve chmod +x
546 546 diff --git a/subdir/f1 b/subdir/f1
547 547 old mode 100644
548 548 new mode 100755
549 549 1 hunks, 1 lines changed
550 550 examine changes to 'subdir/f1'? [Ynsfdaq?]
551 551 @@ -1,2 +1,3 @@
552 552 a
553 553 a
554 554 +a
555 555 record this change to 'subdir/f1'? [Ynsfdaq?]
556 556
557 557 changeset: 22:5df857735621
558 558 tag: tip
559 559 user: test
560 560 date: Thu Jan 01 00:00:20 1970 +0000
561 561 summary: z
562 562
563 563 diff --git a/subdir/f1 b/subdir/f1
564 564 old mode 100644
565 565 new mode 100755
566 566 --- a/subdir/f1
567 567 +++ b/subdir/f1
568 568 @@ -1,2 +1,3 @@
569 569 a
570 570 a
571 571 +a
572 572
573 573 % preserve execute permission on original
574 574 diff --git a/subdir/f1 b/subdir/f1
575 575 1 hunks, 1 lines changed
576 576 examine changes to 'subdir/f1'? [Ynsfdaq?]
577 577 @@ -1,3 +1,4 @@
578 578 a
579 579 a
580 580 a
581 581 +b
582 582 record this change to 'subdir/f1'? [Ynsfdaq?]
583 583
584 584 changeset: 23:a4ae36a78715
585 585 tag: tip
586 586 user: test
587 587 date: Thu Jan 01 00:00:21 1970 +0000
588 588 summary: aa
589 589
590 590 diff --git a/subdir/f1 b/subdir/f1
591 591 --- a/subdir/f1
592 592 +++ b/subdir/f1
593 593 @@ -1,3 +1,4 @@
594 594 a
595 595 a
596 596 a
597 597 +b
598 598
599 599 % preserve chmod -x
600 600 diff --git a/subdir/f1 b/subdir/f1
601 601 old mode 100755
602 602 new mode 100644
603 603 1 hunks, 1 lines changed
604 604 examine changes to 'subdir/f1'? [Ynsfdaq?]
605 605 @@ -2,3 +2,4 @@
606 606 a
607 607 a
608 608 b
609 609 +c
610 610 record this change to 'subdir/f1'? [Ynsfdaq?]
611 611
612 612 changeset: 24:1460f6e47966
613 613 tag: tip
614 614 user: test
615 615 date: Thu Jan 01 00:00:22 1970 +0000
616 616 summary: ab
617 617
618 618 diff --git a/subdir/f1 b/subdir/f1
619 619 old mode 100755
620 620 new mode 100644
621 621 --- a/subdir/f1
622 622 +++ b/subdir/f1
623 623 @@ -2,3 +2,4 @@
624 624 a
625 625 a
626 626 b
627 627 +c
628 628
629 629 % with win32ext
630 630 diff --git a/subdir/f1 b/subdir/f1
631 631 1 hunks, 1 lines changed
632 632 examine changes to 'subdir/f1'? [Ynsfdaq?]
633 633 @@ -3,3 +3,4 @@
634 634 a
635 635 b
636 636 c
637 637 +d
638 638 record this change to 'subdir/f1'? [Ynsfdaq?]
639 639
640 640 changeset: 25:5bacc1f6e9cf
641 641 tag: tip
642 642 user: test
643 643 date: Thu Jan 01 00:00:23 1970 +0000
644 644 summary: w1
645 645
646 646 diff -r 1460f6e47966 -r 5bacc1f6e9cf subdir/f1
647 647 --- a/subdir/f1 Thu Jan 01 00:00:22 1970 +0000
648 648 +++ b/subdir/f1 Thu Jan 01 00:00:23 1970 +0000
649 649 @@ -3,3 +3,4 @@
650 650 a
651 651 b
652 652 c
653 653 +d
654 654
General Comments 0
You need to be logged in to leave comments. Login now